Applet development learning record - get user openid

Main function: the applet obtains the user's openid as the user's unique identification code.

Function Description: the reason to obtain the openid of the user is that it has unique identification and is used as the unique identification to identify the user. With a unique ID, we can know who used our applet. The rules formulated by wechat make it impossible for the applet to directly obtain the user's openid. It needs to send a request to wechat through the interface of cloud development mode or our own server as a transit.   

Although wechat hopes that we can obtain the unique identification code and sessionkey and generate a user-defined login status in combination with the project (for example, the account password independent of wechat is used for login), my applet does not involve this function at present. I just want to learn the development of applet, so I only need openid as the user's unique identification certificate.

Main steps:

First list the official steps as follows:

  1. The front end calls Wx Login obtains the temporary login certificate code and sends it to our development server through request
  2. The development server sends a request to the wechat open interface with a temporary code in exchange for the user's unique ID OpenID and session key session_key

Official tutorial:


Official login flow sequence diagram

Example code:

wx.login({              //The applet calls login to obtain the temporary login certificate code
  success (res) {
    if (res.code) {
      //Initiate network request
        url: ' ', / / our backend interface address
        data: {
          code: res.code        //Pass code as a parameter into the backend
    } else {
      console.log('Login failed!' + res.errMsg)



But I don't need so many steps. I just want an openid. So my steps:

  1. The front end calls login to GET the code and sends the code to the back end by initiating a GET request
  2. The backend obtains the code, sends a GET request to wechat, and gets the openid and session_key
  3. Return openid to the front end
  4. The front end gets the openid and adds some basic information (avatar, nickname, gender, etc.) to the server as user data


Only the sequence diagram of openid is needed


Applet side: wrote a function with the function name getopenid. I wrote it in util and need promise to handle asynchronous communication, because the success callback function is asynchronous after the request is initiated, which means that the acquisition time will fluctuate with the network or other reasons. This will cause me to call this getopenid function on another page to get the openid, and I don't know when I can read the value. Therefore, peomise is used to avoid this situation. Wait until the success callback is read, and then return. Directly call getopenid once to obtain openid, which is in place in one step.

//Parameter Description:
//url: back end interface
//Appid: the appid of the developer
//Secret: developer secret
const getopenid= function(url,appid,secret) {
  var promise = new Promise(function(resolve, reject) {  //promise is used here to avoid asynchronous communication
    const app = getApp()
      success: function(res) {
        if (res.code) {
          //Initiate network request like backend
            url: url,//Request url
            data: {
              code: res.code,//login is obtained after success
              appid:appid,//Applet development id
              secret:secret,//Applet development key
            method: 'GET',
            success:function(res) {
              console.log("Login complete",res),
              app.globalData.openid= JSON.parse(,//
              console.log("user openid by:",app.globalData.openid)
              resolve(app.globalData.openid);//Completed asynchronously and returned openid
            fail:function (res) {
              reject("Login failed, please check the server");
        } else {
          console.log('Failed to get user login status!' + res.errMsg)
  return promise;

Here is an example of calling getopenid on another page:

var promise = util.getopenid(newurl,app.globalData.appid,app.globalData.secret)  //Use promise object to handle asynchronous login. Get user openid

    promise.then( function(openid) {
//Use promise to wait for the asynchronous process to end. 
//promise.then does not execute until its state changes.
//The default is wait status, which is displayed in util Set success in getopenid function, the callback function changes to success status after execution, and returns openid value
    }, function ( error ) {

    } );



Back end: the framework I use is ASP NET. Core, language C#, platform VS2019. Create a new controller at the back end and copy it into it for use.


Wechat request address:

APPID and SECRET are already available, and JSCODE is an applet call Wx Get login.

using System.Net;
using Newtonsoft.Json;
using System.IO;

        /*Get applet openid*/
        public string Getopenid(string code,string appid,string secret)
            string url = ""+ appid +"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
            return BaseGetString(url);

        public  string BaseGetString(string src)
            var obj = BaseGetObject(src);
            Formatting microsoftDataFormatSettings = default(Formatting);
            return JsonConvert.SerializeObject(obj, microsoftDataFormatSettings);

        public static dynamic BaseGetObject(string src)
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(src);
            request.Method = "GET";
            request.ContentType = "text/html;charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            return new
                data = retString,
                Success = true


Tags: ASP.NET MySQL Mini Program openid

Posted by jlp09550 on Wed, 18 May 2022 15:48:25 +0300