# Support WeChat Login & Payment

FinClip provides the capability to support Mini-Programs reusing WeChat login and payment. For commonly used functions such as wx.login, wx.getUserProfile, button - getphonenumber, and requestPayment, when a Mini-Program runs within FinClip, it can automatically redirect to the corresponding WeChat Mini-Program to obtain relevant data and complete the business loop after configuration.

# 1. Quick Start

# Step 1: Add Redirect Page

Add a redirect page to the WeChat Mini-Program and publish the WeChat Mini-Program online. The redirect page serves as the communication bridge between the FinClip Mini-Program and the WeChat Mini-Program. FinClip currently provides a template page for quick integration, which can be obtained through the following two methods:

# Method 1: Automatic Integration via Developer Tools

Open the Mini-Program project in the Developer Tools, right-click on the Mini-Program page directory, and select "Add Authorization Page". The Developer Tools will automatically insert the relevant page. image.png

# Method 2: Manual Integration

Download the Mini-Program Authorization Page Resources (opens new window), extract them into the Mini-Program, and add the page path to app.json.

# Step 2: Configure Association

Go to the FinClip Management Console 【Mini-Program Management - My Mini-Programs - WeChat Association Support - Associate WeChat Mini-Program】to configure.

Configuration Parameters

Mini-Program Original ID: Available in WeChat Official Account Platform - Settings - Basic Settings - Bottom of the page - Original ID.

Associated Page: The corresponding page path added in Step 1.

# Step 3: APP Implements Interfaces

Integrate the WeChat Open SDK and implement opening the Mini-Program and receiving callbacks.

# Method 1

Integrate the FinClip WeChat Extension SDK

# Method 2

# iOS Sample Code
// Inject login method
    [[FATClient sharedClient] registerExtensionApi:@"login" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
        NSString *wxid = appletInfo.wechatLoginInfo[@"wechatOriginId"];
        NSString *path = appletInfo.wechatLoginInfo[@"profileUrl"];
        BOOL canWXLogin = [WXApi isWXAppInstalled] && [wxid length] > 0 && [path length] > 0;
        if (!canWXLogin) {
            callback(FATExtensionCodeFailure, @{@"errMsg" : @"login:fail"});
            return;
        }
        self.callback = callback;
        WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
        req.userName = wxid;
        req.path = path;
        req.miniProgramType = WXMiniProgramTypeRelease;
        [WXApi sendReq:req completion:^(BOOL success) {
            NSLog(@"Open WeChat:%d", success);
        }];
    }];

// Inject payment method
    [[FATClient sharedClient] registerExtensionApi:@"requestPayment" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
        FATAppletInfo *appInfo = [[FATClient sharedClient] currentApplet];
        NSDictionary *info = appInfo.wechatLoginInfo;
        NSDictionary *dataDic = param;
        NSString *payString = [NSString stringWithFormat:@"?appId=%@&nonceStr=%@&package=%@&paySign=%@&signType=%@&timeStamp=%@&type=%@", dataDic[@"appId"], dataDic[@"nonceStr"],dataDic[@"package"], dataDic[@"paySign"], dataDic[@"signType"], dataDic[@"timeStamp"], dataDic[@"type"]];
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = info[@"wechatOriginId"];
        launchMiniProgramReq.path = [NSString stringWithFormat:@"%@%@", info[@"paymentUrl"], payString];
        if (appInfo.appletVersionType == FATAppletVersionTypeRelease) {
            launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //Release version
        } else if (appInfo.appletVersionType == FATAppletVersionTypeTrial) {
            launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //Development version
        } else {
            launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //Trial version
        }
        [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
            NSLog(@"Open WeChat:%d", success);
        }];
    }];
        
// WeChat result callback
- (void)onResp:(BaseResp *)resp {
    FATExtensionCode code = FATExtensionCodeSuccess;
    if (resp.errCode != WXSuccess) {
        code = FATExtensionCodeFailure;
    }
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]]) {//Open Mini-Program
        NSString *extMsg = ((WXLaunchMiniProgramResp *)resp).extMsg;
        if (extMsg.length <= 0) {
            self.callback(FATExtensionCodeFailure, nil);
        }
        else {
            self.callback(code, [self dictionaryWithJsonString:extMsg]);
        
        }
    }
}

// Convert string to dictionary
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) return nil;

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData(jsonData  options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"JSON parsing failed:%@",err);
        return nil;
    }
    return dic;
}
# Android Sample Code
class WxModule(context: Context) : AppletApi(context) {
    private var globalWechatLoginCallback: ICallback? = null

    override fun apis(): Array<String> {
        return arrayOf("login", "requestPayment")
    }

    override fun invoke(appId: String, event: String, param: JSONObject, callback: ICallback) {
        val finAppInfo = appletApiManager.getAppletInfo(appId)
        if (finAppInfo == null) {
            callback.onFail()
            return
        }
        val wechatLoginInfo = finAppInfo.wechatLoginInfo
        if (wechatLoginInfo == null || TextUtils.isEmpty(wechatLoginInfo.wechatOriginId)) {
            callback.onFail()
            return
        }
        globalWechatLoginCallback = callback
        when (event) {
            "login"-> login(wechatLoginInfo)
            "requestPayment"-> requestPayment(wechatLoginInfo, param)
        }
    }

    private fun login(wechatLoginInfo: WechatLoginInfo){
        val req = WXLaunchMiniProgram.Req()
        // WeChat Mini-Program Original ID
        req.userName = wechatLoginInfo.wechatOriginId
        // Path with parameters to launch the Mini-Program page, defaults to the Mini-Program homepage if left blank
        req.path = wechatLoginInfo.profileUrl ?: ""
        // Optionally open Development version, Trial version, and Release version
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
        val done = WXAPiHandler.wxApi?.sendReq(req)
    }

    private fun requestPayment(wechatLoginInfo: WechatLoginInfo, param: JSONObject){
        val req = WXLaunchMiniProgram.Req()
        // WeChat Mini-Program Original ID
        req.userName = wechatLoginInfo.wechatOriginId
        // Path with parameters to launch the Mini-Program page, defaults to the Mini-Program homepage if left blank
        // Concatenate payment parameters here
        val profileUrlSB = StringBuilder(wechatLoginInfo.paymentUrl)
        profileUrlSB.append("?type=${param.optString("type")}")
        profileUrlSB.append("&appId=${param.optString("appId")}")
        profileUrlSB.append("&nonceStr=${param.optString("nonceStr")}")
        profileUrlSB.append("&package=${param.optString("package")}")
        profileUrlSB.append("&paySign=${param.optString("paySign")}")
        profileUrlSB.append("&signType=${param.optString("signType")}")
        profileUrlSB.append("&timeStamp=${param.optString("timeStamp")}")
        req.path = profileUrlSB.toString()
        // Optionally open Development version, Trial version, and Release version
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
        val done = WXAPiHandler.wxApi?.sendReq(req)
    }
}

/**
 * WeChat Callback
 *
 * In this example, both login and requestPayment are executed via the WeChat Mini-Program,
 * so only the response type WXLaunchMiniProgram needs to be handled.
 */
override fun onResp(resp: BaseResp) {
    if (resp is WXLaunchMiniProgram.Resp && !TextUtils.isEmpty(resp.extMsg)) {
        val json = JSONObject()
        json.put("result", resp.extMsg)
        globalWechatLoginCallback?.onSuccess(json)
    } else {
        globalWechatLoginCallback?.onFail()
    }
}

# 2. Principle Explanation

The specific flowchart is shown below.

As shown in the figure above, this feature is implemented as follows:

  • The FinClip Mini-Program calls interfaces (wx.login, wx.getUserProfile, wx.getPhoneNumber, wx.requestPayment);
  • The App side injects interfaces (wx.login, wx.getUserProfile, wx.getPhoneNumber, wx.requestPayment);
  • The App side integrates the WeChat Open SDK and obtains WeChat login Mini-Program related information configured in the Management Console;
  • Executes the WXLaunchMiniProgram method to open the authorization page of the WeChat login Mini-Program;
  • The Mini-Program executes relevant WeChat interfaces based on the App's parameters to obtain information and returns it to the App;
  • The App passes the interface data back to the FinClip Mini-Program.

Please Note

According to the WeChat official announcement (opens new window), after December 27, 2021, user nickname and avatar information will no longer be provided to developers. You may need to handle the logic for obtaining user avatars and nicknames yourself.

# 3. Help

If you need assistance, you can use the ticket function within FinClip or join the developer community for more help and support.

You can also check our official DEMO projects (iOS (opens new window), Android (opens new window)) for more code examples.

© FinClip with ❤ , Since 2017