Wechat applet login analysis

The following back-end code is executed in the Node Egg framework, do not confuse, share only login registration ideas, if you want to learn programming well, a lot of hands

According to the flow chart provided by wechat official, when a small program needs to register and login, it must obtain the corresponding code through wx.login from the small program client and send it to the back end to obtain the unique identification code (openid) through wechat official interface.

Interface api.weixin.qq.com/sns/jscode2 here…

Applets are registered in two ways

The first kind of

Through manual click authorization login registration, if the current user enters and clicks authorization for the first time, it will register in the login first, if already registered, it will directly log in

Bind click authorization with a click event named login using the bindtap attribute

Click authorization

Define a login method in the js file of the login page as follows

login(){
      // When the user clicks authorization, execute the login method and obtain the information of the current user through the wx.getUserProfile open interface.
      wx.getUserProfile({
        desc: 'For user registration'.// Specify the purpose of obtaining the user's personal information, which will be displayed in the subsequent pop-up window
        success: (res) = > {
          For example, the "my" page will display the user's avatar and nickname, etc., and define a userINFO variable to receive the user's information and send it to the backend together
          let userInfo = res.userInfo;
          wx.setStorageSync('userInfo', userInfo);
          this.setData({
            userInfo,
            hasUserInfo: true
          })
          console.log(res);
          // When the code is executed at this point, the open interface wx.login will be executed to obtain temporary credentials of wechat users
          wx.login({
            success (res) {
              // When wx.login returns the result, retrieve the unique certificate and store it in the userInfo variable created above
              userInfo.code = res.code;
              // Pass variables to the back end via POST
              axios.post({url: '/wxlogin'.data:userInfo})
              .then((data) = >{
                console.log(data);
                wx.setStorageSync('token', data.data.data.token);
              }).catch(e= >{
                console.log(e); }}}})),fail:(res) = >{
          console.log("Authorization failed",res); }})},Copy the code

The backend part

Create a new weixin. ts at the Controller layer and define a wxAuth method user route to execute the method and receive the UserInfo sent by the applet

public async wxAuth(){
   const { ctx } = this;

   const userInfo = ctx.request.body;

   // The following two need to go to wechat small program background, these two are the developer's APP related information, do not disclose, the following are my modifications, so it is ok to display, generally put in the config, so that packaging and compilation will not be disclosed, if you follow the following, it is easy to obtain
   const AppId = 'wxc3e768e332c12f4c';
   const AppSecret = '8fb8e48c87e05cec2762518770fd3f09';

   // Get the openID from the wechat open interface. This step should be done in the service layer, but I don't bother to write it in the controller
   const result = await ctx.curl(`https://api.weixin.qq.com/sns/jscode2session?appid=${AppId}&secret=${AppSecret}&js_code=${userInfo.code}&grant_type=authorization_code`, {dataType: "json".timeout: 5000.method: "GET".data: JSON.stringify({})
   })
   if (result.data.errcode === 41008) {throw new Error("The lack of code")}if (result.data.errcode === 40029) {throw new Error("Invalid code")}if (result.data.errcode === 45011) {throw new Error("Code frequency limit")}if (result.data.errcode === -1) {throw new Error("System busy, please try again later.")}if (result.data.errcode === 40163) {throw new Error("Current code is already in use")}/* * "data": {"session_key": "FSn2szxyuYndSbdowg5Zzw==", "openID ": {"session_key": "FSn2szxyuYndSbdowg5Zzw=="," openID ": "o0teF4mqBhpe-pfa01QK4xc3l4c0" } * */


   // Deconstruct session_key and openID
   // @ts-ignore
   const {session_key,openid} = result;


   Select * from userinfo; select * from userinfo; select * from userinfo; select * from userinfo

   let User = {
      opId: openid,
      avatarUrl: userInfo.avatarUrl,
      userName: userInfo.nickName,
      gender: userInfo.gender,
      provider: "WeiXin".accessToken: session_key
   }

   // Call the gotoAdmin method of the same level and pass in the User variable to decide whether to register or log in directly
   await this.goToAdmin(User)
}

public async goToAdmin(_User){
   // const {ctx} = this;

   // Use Try and catch to determine whether to register and log in

   try {
      // Run the following command to query the user in the service layer
      // Perform your back-end logins, such as token issuance, user information return, etc
   }catch (e) {
      // The user does not register and log in first, for example, create a user name by uUID, and then pass the data from the front end and generate good user information to the database, and then return the data to the small program}}Copy the code

The second way

Is similar to the above, the entrance of the small program file is executed within wx. Login, when a user came in quietly in the background to his registration, when users click on the button, the authorized to access to user data sent to the backend storage, two methods can, one kind is authorized at the same time, the registration and save the user data, one is the register first, then save the user data