Photo by Danial RiCaRoS on Unsplash

UnionID is a unique identifier for a user across different WeChat related platform.

It’s one of those things that gets put in the back burner because we assumed it’s supposed to be simple after binding account to an Open Platform Account, but here’s the catch.

Source: https://developers.weixin.qq.com/miniprogram/en/dev/api/unionID.html

The Catch

To summarize the above, wx.login can only get UnionID under the condition where the user has already authorized a mobile app or followed an official account that’s already bound to the same Open Platform Account.

wx.login({
success: function(res) {
if (res.code) {
//Send network request
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('Login failed!' + res.errMsg)
}
}
});
// In test.com/onLogin, use code to get User Information
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
This will return UnionID, if the condition above is met
{
"openid": "OPENID",
"session_key": "SESSIONKEY",
"unionid": "UNIONID"
}

So what if your mini-program is the first point of contact for your user?

The Solution

  1. Use <button open-type="getUserInfo" bindgetuserinfo="onGotUserInfo"></button>

2. In onGotUserInfo, it returns

{
userInfo: {
nickName,
avatarUrl,
gender,
city,
province,
country,
language
},
rawData: String,
signature: String,
encryptedData: String,
iv: String
}

*Notice userInfo doesn’t give you unionID

3. Decrypt encryptedData using iv, appId and sessionKey

sessionKey comes from the wx.login

Official Code Sample:

https://res.wx.qq.com/wxdoc/dist/assets/media/aes-sample.eae1f364.zip

Official Document About Decryption:

开放数据校验与解密 · 小程序

Conclusion

There are a lot more to WeChat related development. If you would like to learn more about it, I put together a free WeChat glossary just for you.


How to get UnionID for WeChat Mini program? was originally published in China Software Development on Medium, where people are continuing the conversation by highlighting and responding to this story.