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 Chinese social networks, it is not so.

Why has this article been born? Everything is simple, WeChat mobile app integration is today a usual practice in China, but we faced a number of problems with WeChat integration during our recent project.

It was a mobile application for a data science platform full-stack development. To say it was difficult is to say nothing. We can only tell you that we took knocks and found ourselves at every dead end possible in the process of integration of this social network into the app.

We intentionally studied WeChat mobile API integration nuances and specifics in-depth to know all the ropes of the work with this SDK. Stfalcon provides service to clients all over the world and works for various markets, so WeChat attracted our attention as the most popular social network in China. Moreover, it has long ago exceeded the level of a simple social platform.

The amount of its monthly active users exceeded one billion two years ago. Now it’s already considered a “super app for everything” due to its wide range of functions possible through multiple WeChat 3rd party integration options.

Due to WeChat payment API, it can boast being almost a monopoly in the field of e-wallets and online payments in the region, even offline payments in the streets of China are now often made with WeChat, as well as the charity to homeless, by the way.

Variable CRMs with WeChat integration and WeChat QR code API reveal almost limitless business and not only possibilities for QR codes generating, scanning, and usage for various purposes.

With such a potential concealed in this social network, we could not leave every nuance of its integration unattended. So, let’s get down to the matter.

Troubled patient: WeChat

The first thought coming into mind: «This is a popular social network, there should be a manual or a tutorial and a WeChat developer API to use.» 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 WeChat integration 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.

Ivanna

Ivanna

Client Manager

Contact us, and we will share our case studies related to app development

Get a Free Consultation

Step 1. WeChat Android SDK Installation.

We install a WeChat 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. App Creation in the Admin Panel

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 :).

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

Step 3. WeChat Object Registration

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 4. WeChat Login API Integration

WeChat Login integration on Android starts with the processing of the 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 5. Login Results Processing Integration

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 {
 
   privatevar code: String? =nullvar resp: BaseResp? =null
 
   privatevar 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 6. Adding Activity Details to Manifest

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 7. Adding Address API Request

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 8. Application Signature Generation and Installation

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: Application Launch

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, was blessed with a WeChat API for developer Bible 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.

Our Experience

Stfalcon carried out a project for a client from Kuala Lumpur, dealing with Information Technology and Services. Our team managed the full-stack development of a mobile application for a data science platform. We successfully delivered a functional platform for data predictions with content and social features implementation. Our developers built the app using PHP, open-source code (distributed with open license), and WeChat 3rd party integration for continued user engagement. We also implemented video capabilities for users to join through hashtags.

Final Thoughts

After carrying out this project, the Stfalcon team has really expanded the expertize in WeChat Android integration and is now aware of its multiple nuances. If you look for the developers experienced in working with this Chinese social network SDK, we are ready to fulfill a project for you, just contact our expert. We have already sacrificed a unicorn to be on the safe side ;)