How to get UnionID for WeChat Mini program?

David Yu
David Yu
Mar 10, 2019 · 2 min read

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.

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

*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.

China Software Development

Sharing software development required in China

David Yu

Written by

David Yu

Software Freelancer based in Shanghai. More articles at https://shanghaicoders.com

China Software Development

Sharing software development required in China

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade