# Mini-Program Payment FAQ

Note

For WeChat Pay, you can also use FinClip's associated WeChat Mini-Program payment feature to reduce development costs and quickly reuse WeChat Pay capabilities. Click here to learn more

Since FinClip Mini-Programs run within third-party APPs integrated with the FinClip Mini-Program SDK (outside of WeChat), they cannot directly use the WeChat Pay functionality implemented in WeChat Mini-Programs. Instead, the third-party APP must first integrate WeChat Pay capabilities. The Mini-Program then invokes the APP's WeChat Pay functionality, which subsequently redirects to WeChat to complete the payment.

The specific implementation steps are as follows:

# 1. APP Integrates WeChat Pay

First, the APP needs to integrate WeChat Pay capabilities: WeChat Pay supports mobile APPs registered and verified on the Open Platform (opens new window). After the APP integrates payment, merchants use the SDK provided by WeChat to call the WeChat Pay module to fulfill payment collection needs.

(iOS Phone). For detailed instructions, please refer to the WeChat Pay APP Integration Introduction (opens new window) and Guidance Document (opens new window).

# 2. APP Implements Custom Injection Interface

After the APP integrates WeChat Pay capabilities, developers need to register a custom interface to inject the payment capability into the SDK, allowing the Mini-Program to call it. The detailed explanation is as follows.

# 2.1 Android

For specific instructions on registering custom Mini-Program interfaces, please refer to FinClip Mini-Program Open Platform - Custom Mini-Program Interfaces

  1. Create a custom Api class implementing the AbsApi interface, specifying the api name as "requestPayment".
public class WxPayApi extends AbsApi {

    private final Context context;

    public WxPayApi(Context context) {
        this.context = context;
    }

    private static final String API_NAME_REQUEST_PAYMENT = "requestPayment";

    @Override
    public String[] apis() {
        return new String[]{API_NAME_REQUEST_PAYMENT};
    }
    
    // ...
}

​

  1. Register the custom Api class.
if (FinAppClient.INSTANCE.isFinAppProcess(this)) {
	return;
}

// SDK initialization result callback, used to receive SDK initialization status
FinCallback<Object> callback = new FinCallback<Object>() {
    @Override
    public void onSuccess(Object result) {
        // SDK initialization successful, register custom Mini-Program interface
 FinAppClient.INSTANCE.getExtensionApiManager().registerApi(new WxPayApi(DemoApp.this));
    }

    // ...
};

​

  1. Implement the invoke() method in the custom Api class. Inside the invoke method, call the backend order placement interface, and after successful order placement, invoke WeChat Pay.
@Override
public void invoke(String event, JSONObject param, ICallback callback) {
    if (API_NAME_REQUEST_PAYMENT.equals(event)) {
        IWXAPI wxApi = WXAPIFactory.createWXAPI(context, null);
        // Check if WeChat is installed
        if (!wxApi.isWXAppInstalled()) {
            JSONObject result = new JSONObject();
            try {
                result.put("errMsg", "WeChat not installed");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            callback.onFail(result);
            return;
        }

        // Call the backend order placement interface to obtain parameters needed to invoke WeChat Pay (implementation omitted here, developers please implement accordingly)
        // ...

        PayReq request = new PayReq();
        request.appId = Constants.WX_APP_ID;
        request.partnerId = mchid;
        request.prepayId = prepayId;
        request.packageValue = "Sign=WXPay"; // WeChat order details extension string, temporarily use fixed value Sign=WXPay
        request.nonceStr = nonceStr; // Random string, no longer than 32 characters
        request.timeStamp = timeStamp;
        request.sign = sign;
        wxApi.sendReq(request); // Invoke WeChat Pay
    }
}

​

  1. In the WXPayEntryActivity handling WeChat Pay information callbacks, use the custom api invoke method's callback object parameter within the result callback method to return the payment result to the Mini-Program.
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    // ...

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            WxPayApi.notifyPayResult(resp.errCode);
            finish();
        }
    }

}

public class WxPayApi extends AbsApi {

    // ...

    private static ICallback callback;

    public static void notifyPayResult(int errCode) {
        if (callback != null) {
            if (errCode == 0) {
                callback.onSuccess(null);
            } else {
                JSONObject result = new JSONObject();
                try {
                    result.put("errCode", errCode);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                callback.onFail(result);
            }
            WxPayApi.callback = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        callback = null;
    }

    @Override
    public void invoke(String event, JSONObject param, ICallback callback) {
        if (API_NAME_REQUEST_PAYMENT.equals(event)) {
            WxPayApi.callback = null;

            // ...
        }
    } 
}

​

  1. FinClip also provides an official Android APP Demo Project and Mini-Program (opens new window) as an example. If needed, you can download and experience it.

# 2.2 iOS

  1. In the native App, call the SDK's method to inject the requestPayment method, where requestPayment is the corresponding payment method name for WeChat Mini-Programs.
__weak typeof(self) weakSelf = self;
[[FATClient sharedClient] registerExtensionApi:@"requestPayment" handle:^(id param, FATExtensionApiCallback callback) {
    // Order placement - payment call, notify Mini-Program of the result via callback
    [weakSelf getTestPayment:callback];
}];
  1. Simulate order placement and payment
// During payment, the payment callback is asynchronous, so hold the Mini-Program's callback here and call it at the appropriate time (users can implement their own logic according to their scenario)
@property (nonatomic, copy) FATExtensionApiCallback callback;
- (void)getTestPayment:(FATExtensionApiCallback)callback {
    NSString *urlString = @"https://xxx.example.com/api/order"; // Order placement interface, simulate order placement
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    requset.HTTPMethod = @"POST";
    __weak typeof(self) weakSelf = self;
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode == 200) {
            // After successful order placement, simulate WeChat Pay
            PayReq *request = [[PayReq alloc] init];
            request.partnerId = @"partnerId";
            request.prepayId = @"prepayId";
            request.package = @"Sign=WXPay";
            request.nonceStr = @"nonceStr";
            request.timeStamp = 100000;
            request.sign= @"sign";
            dispatch_async(dispatch_get_main_queue(), ^{
                [WXApi sendReq:request completion:^(BOOL success) {
                    if (success) {
                        // When WeChat is successfully invoked, hold the callback for later use (implementation can vary, this is just simulation)
                        weakSelf.callback = callback;
                    } else {
                        // When WeChat invocation fails, directly call the callback with failure
                        callback(FATExtensionCodeFailure, nil);
                    }
                }];
            });
            return;
        }
        callback(FATExtensionCodeFailure, nil);
    }];
    [task resume];
}
  1. Handle callback upon successful WeChat Pay
#pragma mark - WXApiDelegate
// Callback for initiating payment request
- (void)onReq:(BaseReq *)req {
    
}

// Callback for payment result
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *response = (PayResp*)resp;
        //response.errCode
//        WXSuccess           = 0,    /**< Success    */
//        WXErrCodeCommon     = -1,   /**< Common error type    */
//        WXErrCodeUserCancel = -2,   /**< User canceled and returned    */
//        WXErrCodeSentFail   = -3,   /**< Send failed    */
//        WXErrCodeAuthDeny   = -4,   /**< Authorization failed    */
//        WXErrCodeUnsupport  = -5,   /**< WeChat not supported    */
        switch (response.errCode) {
            case WXSuccess: // Call callback upon payment success
                self.callback(FATExtensionCodeSuccess, nil);
                break;
                
            default:    // Call callback upon payment failure
                self.callback(FATExtensionCodeFailure, nil);
                break;
        }
    }
}

Note

The callback for the Mini-Program payment api requestPayment needs to be maintained by the user. Because the payment function is asynchronous, the callback for the Mini-Program payment api requestPayment must be called within the payment success or failure callback.

This pseudocode uses the current class to hold the Mini-Program payment api requestPayment callback, which is then called within the payment function's callback. Users can use other techniques for handling based on their own scenario requirements.

  1. FinClip also provides an official iOS APP Demo Project and Mini-Program (opens new window) as an example. You can download and experience it.

# 3. Mini-Program Implements Interface Call

After the mobile-side related APIs are prepared, use the following code in the Mini-Program:

// Code called within the Mini-Program
wx.requestPayment({
  success: (res) => {
    console.log('payment success', res)
  },
  fail: (res) => {
    console.log('payment fail', res.errMsg)
  }
})

# 4. Mini-Program Integrates Alipay

The steps for integrating Alipay into a FinClip Mini-Program are basically the same as those for integrating WeChat Pay, and will not be repeated here. For APP integration of Alipay, please refer to the document Alipay Integration Documentation (opens new window).

© FinClip with ❤ , Since 2017