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.


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.

success: function(res) {
if (res.code) {
//Send network request
url: '',
data: {
code: res.code
} else {
console.log('Login failed!' + res.errMsg)
// In, use code to get User Information
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: {
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:

Official Document About Decryption:

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


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.