Get the OpenID using the cloud function

Currently, OpenID can be obtained from the small program side or the cloud function side

X1 gets the OpenID from the small program

The method of obtaining openID from the small program side is complicated. Instead of directly obtaining OpenID, the back end requests the openID through credentials

  • steps

    • The applet calls wx.login to get a code credential. This credential has a short expiration date and will be replaced when you log in again
    • Send the obtained code to the official interface URL of wechat (in the parameters after the URL, the capitalized value is replaced with the code given by your actual AppID, Appsecret and login).
    https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code
    Copy the code
    • Receive the res from the other party, which provides various user-related information
  • The problem

    • Currently, it appears that the applets do not allow the above interface to be added as a legitimate domain name that the applets can access, so a server is required to complete the request
    • The obtained data is encrypted and needs to be decrypted using the corresponding algorithm. See official documents for decryption methods

X2 gets the user OpenID from the cloud function

Cloud.getwxcontext () in the cloud function can get the user’s OpenID directly, without requiring complex authentication to get it remotely

  • steps
    • After the cloud function is configured, initiate a request from the page where the applet needs OpenID (I used TCB-Router here to process the request).
    • The cloud function retrieves the OpenID through cloud.getwxContext () and passes it back to the front end
    • The applet is received successfully

Add: Get unionID

  • Unionid is a unified identifier designed by wechat officials for different small programs or public accounts of the same subject, while OpenID is different in different applications

  • To obtain

    • The method is the same as the openID method above. However, the public number seems to be able to use a similar small program side to send code to obtain
    • In fact, the packet sent by code itself contains the OpenID and UnionID
    • The applets cloud function is also obtained through cloud.getwxContext (), which can be accessed through{UNIONID,OPENID}Deconstruct both signs