WeChat Login Integration Process: Tips And Tricks To Know

Following the latest trends in functionality implementation, we constantly face the necessity of social media support integration into the applications we develop. As a rule, no problems set in during Facebook integration or any other popular American or European social network. However, with the Chinese social networks, it is no so.

Troubled patient: WeChat

The first thought coming into mind: «This is a popular social network, there should be a manual or a tutorial.» The search results in the first approximation reveal the most popular article from medium.com.

However, in a few minutes already you realize, that the social network is Chinese and the manuals are also in Chinese. To be more precise, I would admit, that the English-language version exists, but contains only the instructions for some initial steps. So, get ready to constantly use a translator. What else should you get ready for? Prepare to look for the ways to solve the possible problems in Chinese in case something goes wrong and the plan fails. You should also bear in mind that there are plenty of outdated solutions on the internet, which work with the old API versions.

Step 1.

We install an SDK into our project.

By the way there are 2 variants:

  1. We need to get analytics from WeChat.
  2. We do not need analytics from WeChat.

In the first case, we do without the dependencies section of the app module and add the following:

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:5.4.3'

If analytics is needed, we should add:

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:5.4.3'

Besides, it’s necessary not to forget about the manifest:

Step 2.

We create our app in the admin panel: https://open.weixin.qq.com

Everything is easy here.

  1. Click the big green button «Create Mobile Application», and fill in the general info about the app.
  2. Fill in the platform details, add AppID and the relevant information.
  3. Add the personal info required in the final steps. It may be scan copies of your documents, bank statement and tons of other details at times.
  4. Finally, pay $99 and go through the app verification process, which takes no less, no more than 5-7 business days. Here you can start crying :).

Step 3.

After the successful WeChat account verification, you should recollect what you were about a week ago :).

Step 4.

We create and register a copy of the WeChat object. Wechat_app_id is taken from the admin panel and app_secret should be generated and saved here as well.

To do this, add the following code in the application class:

IWXAPI = WXAPIFactory.createWXAPI(this, getString(R.string.wechat_app_id), true)
IWXAPI?.registerApp(getString(R.string.wechat_app_id))

Step 5.

We add the main action - the processing of login button clicking. In our example, it would be something like this:

private fun onClickWeChatLogin() {
   val app = application as? App
   if (app?.IWXAPI == null) {
       app?.IWXAPI = WXAPIFactory.createWXAPI(this, getString(R.string.wechat_app_id), true)
       app?.IWXAPI?.registerApp(getString(R.string.wechat_app_id))
   }
 
   if (app?.IWXAPI?.isWXAppInstalled == false) {
       toast("Wechat has not been installed on your mobile phone. Please login after installation.")
       return
   }
 
   val req = SendAuth.Req()
   req.scope = "snsapi_userinfo"
   req.state = "wechat_sdk_xb_live_state"
   app?.IWXAPI?.sendReq(req)
}

Step 6.

We add login results processing. To do this, you need to create an additional wxapi package at the root of the package and to create an activity called WXPayEntryActivity in it. For example, if the package name is com.example.myapp, then the full path to this activity should be: com.example.myapp.wxapi.WXPayEntryActivity.

IWXAPIEventHandler interface implementation should be added to this activity.

We retrieve an object already registered by WeChat in the onResume method and specify who should process the callbacks.

app = application as App
 
       val handleIntent = app?.IWXAPI?.handleIntent(intent, this)
       if (handleIntent == null) {
           finish()
       }

At the same time, we redefine the onNewIntent, onResp, and onReq methods.

override fun onNewIntent(intent: Intent?) {
       super.onNewIntent(intent)
 
       setIntent(intent)
       app?.IWXAPI?.handleIntent(intent, this)
   }
 override fun onResp(baseResp: BaseResp?) {
       when (baseResp?.errCode) {
           BaseResp.ErrCode.ERR_OK -> {
               val code = (baseResp as SendAuth.Resp).code
               viewModel.get().getWeChatToken(code)
           }
           BaseResp.ErrCode.ERR_USER_CANCEL -> {
               finish()
           }
           BaseResp.ErrCode.ERR_AUTH_DENIED -> {
               finish()
           }
       }
   }
override fun onReq(p0: BaseReq?) {
       finish()
   }

A login result comes in the onResp method. In this callback, we will receive a temporary code, which we will then use to make a request on the appropriate endpoint, passing app_secret and this code.

class WXEntryActivity : AppCompatActivity(), IWXAPIEventHandler {
 
   private var code: String? = null
   var resp: BaseResp? = null
 
   private var app: App? = null
 
   @Inject
   @ViewModelInjection
   lateinit var viewModel: ViewModelInjectionField<WXEntryVM>
 
   override fun onResume() {
       super.onResume()
       app = application as App
       app?.IWXAPI?.handleIntent(intent, this)
 
       observeSuccess()
       observeError()
   }
 
   override fun onNewIntent(intent: Intent?) {
       super.onNewIntent(intent)
 
       setIntent(intent)
       app?.IWXAPI?.handleIntent(intent, this)
   }
 
   override fun onResp(baseResp: BaseResp?) {
       if (baseResp != null) {
           resp = baseResp
           code = (baseResp as SendAuth.Resp).code
       }
       when (baseResp?.errCode) {
           BaseResp.ErrCode.ERR_OK -> {
               viewModel.get().getWeChatToken(code)
           }
           BaseResp.ErrCode.ERR_USER_CANCEL -> {
               finish()
           }
           BaseResp.ErrCode.ERR_AUTH_DENIED -> {
               finish()
           }
       }
   }
 
   override fun onReq(p0: BaseReq?) {
       finish()
   }
 
   private fun observeSuccess() {
       viewModel.get().onSuccess.observe(this, Observer {
           startActivity(intentFor<MainActivity>().newTask().clearTask())
           finish()
       })
   }
 
   private fun observeError() {
       viewModel.get().error.observe(this, Observer {
           toast(it)
       })
   }
}

Step 7.

We add information about our activity in the Manifest.

<activity
   android:name="com.example.myapp.wxapi.WXEntryActivity"
   android:exported="true"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" />

Please note that you must specify the parameter: android:exported="true"

Step 8.

We add address API request:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=&grant_type=authorization_code

Only after this step we will receive the authorization token, which should be sent to backend.

Step 9.

We generate the application signature and install our app on a device that has the WeChat application installed already. Then we download the official signature generation application, specify the package name and generate the hash key. This key should be added to the admin panel.

The final step.

We launch the application, cross our fingers and pray that everything will work. If you are the most fortunate person in the world, who have gone through the Masons consecration ceremony, and have besides sacrificed a unicorn to be on the safe side, everything will work from the first time. If it’s not so, I suggest to look at the small tips and tricks below, which may help.

Tips and tricks

  • Check that the WXEntryActivity file name and path are correct.
  • Check that the correct hash key was generated by the utility.
  • If you use a debug build, you must duplicate the WXEntryActivity file on the com.example.myapp.debug.wxapi.WXPayEntryActivity path.
  • When adding SHA-1 keys to the admin panel, keep in mind that debug and release builds have different hash keys. If you change the hash keys, wait a few minutes, then try to log in to WeChat again and only then try to log in to the application.