gogoWebsite

WeChat Small Program Development - User Authorization Login

Updated to 6 months ago

This article will help readers to realize the authorization login of users on applets based on WeChat Developer Tools & C# environment.

Prepare:

WeChat developer tools download address: /miniprogram/dev/devtools/

WeChat small program development documentation: /miniprogram/dev/

Development:

At the beginning of the development, we need to clarify the authorization login process that has been developed by WeChat, cf.Official API - Login Interface

You'll see a good login authorization process for developers on the WeChat side:

As shown in the figure, it is a smooth flow of user login authorization.

Why do you say it is a smooth flow? Because in the real small program development, we are not sure when the user needs to start the call such as the above login process (eg: the user in some specific scenarios of credentials lost, but Ta did not exit the small program but in the small program to do the jump and other related operations, that is, it is possible to lead to some unanticipated anomalies), so we need to add a layer of detection mechanisms outside of the downstream process to address these exception scenarios, and the official API can just solve this problem to some extent.

So, our certification process should actually be:

- Applet Verify login state as invalid

- success : Callback function for successful interface call, session_key has not expired, end of process;

    - fail :Callback function for interface call failure, session_key has expired

-The applet side gets the code and submits it to its own server.

-Submit Appid + appSecret + code to WeChat server to get session_key & openid.

-The server generates a 3rd_session based on session_key & openid.The WeChat side proposes that based on security considerations, developers are advised not to transmit openid and other critical information for data transfer) and returns the 3rd_session to the applet.

-" applet-side storage of 3rd_session (when credentials are required for subsequent user actions)

-Get user information and 3rd_session data on the applet side and submit it to your server.

-The process ends when the SQL user data information on your server is updated;

Ideas organized, the next realization of the process

Small program end:

In the applet, create a new generic JS for basic support

and cite it on some of the pages that need it

var common = require("../Common/")

Next, implement the logic in

//user login
function userLogin() {
  ({
    success: function () {
      //landed state
    },
    fail: function () {
      //不landed state
      onLogin()
    }
  })
}

function onLogin() {
  ({
    success: function (res) {
      if () {
        //Launching a web request
        ({
          url: 'Our Server ApiUrl',
          data: {
            code:
          },
          success: function (res) {
            const self = this
            if (logical success) {
              //Get user credentials Storage 3rd_session
              var json = ()
              ({
                key: "third_Session",
                data: json.third_Session
              })
              getUserInfo()
            }
            else {

            }
          },
          fail: function (res) {

          }
        })
      }
    },
    fail: function (res) {
  
    }
  })

}

function getUserInfo() {
  ({
    success: function (res) {
      var userInfo =
      userInfoSetInSQL(userInfo)
    },
    fail: function () {
      userAccess()
    }
  })
}

function userInfoSetInSQL(userInfo) {
  ({
    key: 'third_Session',
    success: function (res) {
      ({
        url: 'Our Server ApiUrl',
        data: {
          third_Session: ,
          nickName: ,
          avatarUrl: ,
          gender: ,
          province: ,
          city: ,
          country:
        },
        success: function (res) {
          if (logical success) {
            //SQLUpdate user data successfully
          }
          else {
            //SQLFailed to update user data
          }
        }
      })
    }
  })
}

At this point, the small program side of the process is basically complete, and then the realization of their own service APIs

Login Interface Logic Example

 if (("CODE"))
        {
            string apiUrl = ("/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", , , dicRequestData["CODE"]);
        
            HttpWebRequest myRequest = (HttpWebRequest)(apiUrl);
             = "GET";
            HttpWebResponse myResponse = (HttpWebResponse)();
            StreamReader reader = new StreamReader((), Encoding.UTF8);
            string content = ();
            ();
            ();
            ();

            //analyze
            userModel ReMsg = <userModel>(content); //analyze
            if ((!()) && (!(ReMsg.session_key)))
            {
                // successes Custom Generation3rd_sessiontogether withopenid&session_keyBind and return3rd_session

            }
            else
            {
                // incorrect No users acquiredopenid maybe session
            }
        }
        else
        {
            // incorrect No users acquired凭证code
        }

UserInfoUpdate interface will not be repeated here, the user can operate the data according to their own situation, the WeChat party returns the relevant parameters when the call is successful as follows

At this point, the basic authorization of the applet to log in and obtain user information is completed.

Last but not least, a little trick I learned from someone else to make a few bucks, so give me a little credit! ! !!! (๑-̀ㅂ-́)و✧

After carefully reading all of the above

If there's anything you don't understand, feel free to ask.

Note: The above content has been abridged to retain only the general content. In specific projects there must be part of the logic needs to be adjusted, citation students please note that