Connect Mobile Apps to WeChat

WeChat Open Platform account (微信开放平台账号) is different from WeChat Official account (微信公众平台账号). Authgear supports integrating WeChat Login with a WeChat Open Platform account.

Prerequisite

  • Register a WeChat Open Platform account (微信开放平台账号).

  • Register a Mobile Application (移动应用).

    • For iOS, WeChat Open Platform requires your app to support Associated Domains and Universal Links. See the official documentation from Apple for details.

    • For Android, WeChat Open Platform requires you to tell them the MD5 fingerprint of the signing keystore.

Get the information from WeChat Open Platform

  • Get the appid (Client ID).

where to find appid
where to find appid
  • Get the appsecret (Client Secret). It will only be shown once. You need to re-generate if you lose it.

where to find appsecret
where to find appsecret
  • Get the 原始ID (Account ID) of your WeChat Open Platform account.

where to find account ID
where to find account ID

Configure Sign in with WeChat in the Authgear portal

  1. Sign in to the Authgear portal.

  2. Select your project.

  3. In the navigation menu, go to Authentication > Social / Enterprise Login.

  4. Click Add Connection.

  5. Select WeChat Mobile / 移动应用.

  6. Fill in Client ID with the appid.

  7. Fill in Client Secret with the appsecret.

  8. Fill in Account ID with the 原始ID.

  9. Add a WeChat Redirect URI. This is typically a custom URI with the scheme being your iOS bundle identifier or your Android package name. For example, com.myapp://authgear/open_wechat_app.

  10. Save.

Integrate the WeChat SDK into your iOS app

You can skip this section if you do not have an iOS app.

This section assumes you install the WeChat SDK with CocoaPods.

To integrate the WeChat SDK into your iOS app, you have to read the official integration guide.

This section reminds you some of the important points that you may miss in the official integration guide.

Install the latest version of the WeChat SDK for iOS

pod "WechatOpenSDK-XCFramework", "~> 2.0.4"

The latest version can be found at this URL As of the time of writing, the latest version is 2.0.4.

Specify your WeChat appid in Info.plist

	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>weixin</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>wxYOUR_WECHAT_APPID</string>
			</array>
		</dict>
	</array>

Specify LSApplicationQueriesSchemes in Info.plist

	<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>weixin</string>
		<string>weixinULAPI</string>
		<string>weixinURLParamsAPI</string>
	</array>

In case you have other schemes, you need to make sure the WeChat ones are the first 50 items.

Make sure OTHER_LDFLAGS contains -ObjC

If you fail to do so, you will encounter this error.

The WeChat SDK for iOS depends on the Objective-C runtime. Therefore, your app has to link to the Objective-C runtime. To do so, you need to make sure OTHER_LDFLAGS contains -ObjC.

The -ObjC flag is so special in CocoaPods that you CANNOT add it with CocoaPods post_install hook.

If your iOS app is written in React Native, the app is likely to have OTHER_LDFLAGS including -ObjC already, as React Native depend on the Objective-C runtime.

In other case, you need to manually edit your Build Settings to include the -ObjC flag.

Add the integration code for the WeChat SDK for iOS

In your AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Insert this line to register your WeChat mobile application.
    WXApi.registerApp("wxYOUR_WECHAT_APPID", universalLink: "https://myapp.com/wechat/")
    return true
  }

  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    // Forward the URL to the WeChat SDK.
    // If the URL is about WeChat integration, onResp will be called.
    WXApi.handleOpen(url, delegate: self)
    return true
  }

  func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    // Forward the URL to the WeChat SDK.
    // If the URL is about WeChat integration, onResp will be called.
    WXApi.handleOpen(url, delegate: self)
    return true
  }

  func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    // Forward the NSUserActivity to the WeChat SDK.
    // If the NSUserActivity is about WeChat integration, onResp will be called.
    WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    return true
  }

  // Implements WXApiDelegate.
  // You need not do any thing special in this method.
  func onReq(_ req: BaseReq) {}

  // The WeChat SDK will call this method if the forwarded callbacks are about WeChat.
  func onResp(_ resp: BaseResp) {
    guard let authResp = resp as? SendAuthResp else {
      return
    }


    let errCode = WXErrCode(rawValue: authResp.errCode)
    if errCode == WXSuccess {
      let state = authResp.state
      let code = authResp.code
      // Forward code to Authgear SDK.
    } else {
      // Handle the error returned by the WeChat SDK properly to deliver good user experience.
    }
  }
}

In your SceneDelegate (if you have one)

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    // Assume your AppDelegate is the single point of handling WeChat callback,
    // you need to get it back.
    let appDelegate = UIApplication.shared.delegate as? AppDelegate

    // Forward the NSUserActivity to the WeChat SDK.
    // If the NSUserActivity is about WeChat integration, onResp on AppDelegate will be called.
    WXApi.handleOpenUniversalLink(userActivity, delegate: appDelegate)
  }
}

Integrate the WeChat SDK into your Android app

You can skip this section if you do not have an Android app.

To integrate the WeChat SDK into your Android app, you have to read the official integration guide.

This section reminds you some of the important points that you may miss in the official integration guide.

Install the latest version of the WeChat SDK for Android

implementation "com.tencent.mm.opensdk:wechat-sdk-android:6.8.34"

The latest version can be found at this URL As of the time of writing, the latest version is 6.8.34.

Declare <queries> in your AndroidManifest.xml

You need to declare in your AndroidManifest.xml that your app is supposed to query the existence of the WeChat app at runtime.

Add this to your AndroidManifest.xml.

    <queries>
        <package android:name="com.tencent.mm" />
    </queries>

Declare your callback Activity in your AndroidManifest.xml

The WeChat SDK opens the Activity PACKAGE_NAME.wxapi.WXEntryActivity. You need to implement that Activity and declare it in your AndroidManifest.xml.

  <activity
    <!-- android:name MUST match the package name you tell WeChat Open Platform -->
    android:name="com.myapp.wxapi.WXEntryActivity"
    <!-- It must be exported, otherwise the WeChat app will not be able to open it -->
    android:exported="true"
    <!-- The official guide says it should be singleTask -->
    android:launchMode="singleTask"
    <!-- android:taskAffinity MUST match the package name you tell WeChat Open Platform -->
    android:taskAffinity="com.myapp"
    android:theme="@android:style/Theme.Translucent.NoTitleBar">
  </activity>

Implement the callback Activity

The full Java name of the Activity must be PACKAGE_NAME.wxapi.WXEntryActivity. If the package name you tell WeChat Open Platform is com.myapp, then the full Java name of the Activity must be com.myapp.wxapi.WXEntryActivity.

Here is an example implementation that is based on BroadcastReceiver:

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, "wxYOUR_WECHAT_APPID", true);
        api.registerApp("wxYOUR_WECHAT_APPID");

        try {
            Intent intent = getIntent();
            api.handleIntent(intent, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        String error = null;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                error = "errcode_cancel";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                error = "errcode_deny";
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                error = "errcode_unsupported";
                break;
            default:
                error = "errcode_unknown";
                break;
        }

        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            SendAuth.Resp authResp = (SendAuth.Resp)resp;

            String state = authResp.state;
            Intent intent = new Intent(state);
            intent.putExtra("state", state);

            intent.setPackage(this.getApplicationContext().getPackageName());
            if (error != null) {
                intent.putExtra("error", error);
            } else {
                intent.putExtra("code", authResp.code);
            }

            this.getApplicationContext().sendBroadcast(intent);
        }
        finish();
    }
}

Make sure your Android app is signed by the keystore you tell WeChat Open Platform

On WeChat Open Platform, you need to tell it the MD5 fingerprint of the keystore you use to sign your Android app.

If you use Google Play Console to distribute your Android app, it is likely that you are using Play App Signing. With Play App Signing, you tell Google the fingerprint of the keystore you originally sign your app. Google removes the signature and uses its managed keystore to sign the app before distributing the app to Play Store. The final app running on the device of course bears the signature of the managed keystore. This is also the signature the WeChat SDK sees when it validates the signature.

To get the MD5 fingerprint of the managed keystore, refer to the following screenshot:

where to find the MD5 fingerprint of the managed keystore
where to find the MD5 fingerprint of the managed keystore

Note that the MD5 fingerprint you see on Google Play Console is a colon-delimited uppercase hex string, while WeChat Open Platform expects you to provide a plain lowercase hex string.

For example, suppose the MD5 fingerprint you get from Google Play Console is D4:1D:8C:D9:8F:00:B2:04:E9:80:09:98:EC:F8:42:7E, you can use the following shell command to do the conversion.

$ echo "D4:1D:8C:D9:8F:00:B2:04:E9:80:09:98:EC:F8:42:7E" | sed 's/://g' | tr 'A-Z' 'a-z'
d41d8cd98f00b204e9800998ecf8427e

The output d41d8cd98f00b204e9800998ecf8427e is in the expected WeChat Open Platform format.

For those of you who produce the final signature of your app using your own keystore, you can use the following shell command to output the MD5 fingerprint.

keytool -exportcert -keystore "$STORE_FILE" -storepass "$STORE_PASSWORD" -alias "$KEY_ALIAS" -rfc | openssl x509 -noout -fingerprint -md5

Where

  • STORE_FILE is an environment variable pointing to the keystore file on your machine, for example, ./mykeystore.jks.

  • STORE_PASSWORD is an environment variable containing the password of the keystore.

  • KEY_ALIAS is an environment variable indicating which key in the keystore to use.

Configure Authgear SDK for WeChat

You have 2 actions to take:

  1. Switch to WebKitWebViewUIImplementation when you initialize the Authgear SDK.

  2. Implement the callback / delegate of WebKitWebViewUIImplementation.

Switch to WebKitWebViewUIImplementation

import Authgear

let uiImplementation = WKWebViewUIImplementation()
// Put the WeChat redirect URI you added in the Authgear portal here.
uiImplementation.wechatRedirectURI = URL(string: "com.myapp://authgear/open_wechat_app")!
// You need to implement the delegate to bridge between the WeChat SDK and the Authgear SDK.
uiImplementation.authgearDelegate = self

self.authgear = Authgear(
  clientId: "AUTHGEAR_CLIENT_ID",
  endpoint: "https://myapp.authgear.cloud",
  uiImplementation: uiImplementation
)

Implement the callback / delegate of WebKitWebViewUIImplementation

This section assume you have integrated the WeChat SDK according to

In particular,

  • On iOS, you implement WXApiDelegate on your AppDelegate.

  • On Android, your WXEntryActivity sends a broadcast with state being the Intent action.

In your AppDelegate.swift

import Authgear

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate, AuthgearDelegate {
  // authgear is assumed to be initialised somewhere else.
  var authgear: Authgear!

  // Implements AuthgearDelegate
  func sendWechatAuthRequest(_ state: String) {
    // Open WeChat using the WeChat SDK.
    let req = SendAuthReq()
    req.scope = "snsapi_userinfo"
    req.state = state
    WXApi.send(req)
  }

  // Implements WXApiDelegate
  func onResp(_ resp: BaseResp) {
    guard let authResp = resp as? SendAuthResp else {
      return
    }

    let errCode = WXErrCode(rawValue: authResp.errCode)
    if errCode == WXSuccess {
      let state = authResp.state
      let code = authResp.code
      // Forward code to Authgear SDK.
      self.authgear?.wechatAuthCallback(code: code, state: state) { result in
        switch result {
        case .success():
          // The code was sent to Authgear successfully.
          // The end-user will proceed the login in the WebView.
          // You do not need to do anything here.
          break
        case let .failure(error):
          // Handle the error returned by the Authgear SDK properly to deliver good user experience.
        }
      }
    } else {
      // Handle the error returned by the WeChat SDK properly to deliver good user experience.
    }
  }
}

Last updated

Was this helpful?