WeChat Mini Program mobile phone number login process


foreword

Foreword: Recently, I am using uni-app to develop small programs. The product needs to log in and bind the mobile phone number by default. Now you need to log in and directly bind your mobile phone number, so I studied the process. I saw some articles on the Internet that getPhoneNumber gets back the mobile phone number, and then needs to trigger wx.login to get back the user's personal information, which actually caused some misunderstandings for me in the early stage. Write an article to record yourself. The uni-app used by the landlord, if it is not this framework, just replace the corresponding api with wx at the beginning


1. Implementation method

Call getPhoneNumber to get back the encryptedData and iv, then silently call uni.login to get back the code, pass these three parameters to the backend together, let the backend adjust the WeChat interface to get back the session_key and openid, and decrypt the phone number in encryptedData. So far, we have implemented user login and binding mobile phone number. As for user avatar and nickname, WeChat has open data, and we can directly use code to obtain it. The code is given below

2. Use steps

1. Arouse WeChat mobile phone number authorization

code show as below:

<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">
    <div >微信用户一键登录</div>
</button>
    getPhoneNumber(e){
    
    
        uni.login({
    
    
        success: (res) => {
    
    
          this.code = res.code;
          if (this.code) {
    
    
              console.log("验证登陆请求");
              if(e.detail.errMsg == "getPhoneNumber:ok"){
    
    
                  console.log("用户点击了接受", e)
                  this.phone = e.detail.encryptedData;
                  this.iv = e.detail.iv;
                  this.getAccessToken(); // 将code、phone、iv发给后台,让后台解密手机号,拿回openid和session
                }else{
    
    
                  console.log("用户点击了拒绝")
              }
          }
        },
        fail: () => {
    
    
            this.$refs.toast.hide();
            this.$refs.toast.error("登录失败!请重新授权登录!");
        },
      });
   },

2. Obtain WeChat open data: open-data

Obtaining open-data, here is just an example to take the user's avatar. The
specific types of open-data that can be obtained can be viewed on the official website, and directions: https://developers.weixin.qq.com/miniprogram/dev/component/open-data .html

<open-data type="userAvatarUrl" mode="aspectFill" v-else></open-data>

Summarize

Above, the user only needs one authorization to bind the mobile phone number and display the avatar and user nickname.
Reference articles:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
https://developers.weixin.qq.com/minigame/dev/guide/open-ability/ login.html

Guess you like

Origin blog.csdn.net/qq_31915745/article/details/112768760