WeChat applet to obtain user mobile phone number tutorial (front end + back end)

1. Background introduction

When developing a WeChat applet, the user needs to log in to WeChat and obtain the user's mobile phone number as the user's unique identifier (userId), so explore ways to obtain the user's mobile phone number;

(Of course, it is also possible to obtain the code through wx.login, and then exchange for the user's openid)

The current version of the WeChat Mini Program obtains the user's mobile phone number as follows:

Front-end development reference: mobile phone number quick filling component | WeChat open document

Backend development reference:

Quickly fill in mobile phone number | WeChat open document

Proceed as follows:

① Use the function of quickly filling in the mobile phone number to  open-type set the value of the button component to getPhoneNumber

②The user clicks the button, and a pop-up window pops up to apply for obtaining the user's mobile phone number:

③ If the user clicks Allow, the dynamic token code can be obtained through bindgetphonenumberthe event callback (note that the code here is different from the code of wx.

④ Pass the code to the developer background, and call the interface provided by the WeChat background in the developer background  phonenumber.getPhoneNumber , and consume the code in exchange for the user's mobile phone number

Note that the function of obtaining the mobile phone number seems to be only allowed to be used by certified applets. If it is not certified, only the test number can be used.

Otherwise, an error will be reported:

2. Front-end code

Development environment: Uniapp framework

The version of the basic library for WeChat applet debugging: 2.32.1

Basic idea: Bind the button to monitor events, obtain user authorization, get the code, and pass it to the backend to exchange for the user's mobile phone number:

code show as below:

button:

<button open-type="getPhoneNumber" class="login_button" @getphonenumber="login" v-show="!logged">登录</button>

login function:

//登录按钮
login(e) {
  console.log(e)
  var detail = e.detail
  if (detail.errMsg == "getPhoneNumber:ok") {
    console.log("用户同意授权")
    var code = detail.code
    uni.request({
      url: "http://localhost:8081/getPhoneNumber", //调用接口
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        code: code, //请求体中封装code
      },
      success(e) {
        console.log(e)
        var userId = e.data.phone_info.purePhoneNumber;
        uni.setStorage({
          key: "userId",
          data: userId,
          success() {
            uni.switchTab({
              url: "../../pages/homePage/homepage"
            })
          }
        })
      },
      fail(e) {
        uni.showModal({
          title: "错误!",
          content: "网络错误!",
          complete() {
          }
        })
      }
    })
  }
}

3. Backend code

Development environment: springboot

Development tools: idea

If you have any questions about creating a springboot project for idea, you can refer to the back-end code part of this article:

Baidu translation API usage tutorial (front end + back end)_THE WHY's Blog-CSDN Blog

The code is displayed as follows:

@RestController
    public class PhoneNumberController {

        @PostMapping("/getPhoneNumber")
        public Object getPhoneNumber(@RequestBody Map<String,Object> data)
        {
            //通过appid和secret来获取token
            //WXContent.APPID是自定义的全局变量
            String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WXContent.APPID, WXContent.APPSECRET);
            JSONObject token = JSON.parseObject(HttpUtil.get(tokenUrl));

            //通过token和code来获取用户手机号
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");

            //封装请求体
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("code", data.get("code").toString());

            //封装请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);

            //通过RestTemplate发送请求,获取到用户手机号码
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

            //返回到前端展示
            return response.getBody();
        }
    }

4. Results display

There is a function of caching the user id in my front-end code. If you log in successfully, you can view the user id in the cache, as follows:

5. Supplement: get user avatar

The function of the WeChat applet to obtain user information seems to be outrageous, and it has been changed over and over again. At present, most of them are realized by clicking on the profile picture to apply for the WeChat profile picture.

<button class="mine_avatar_wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
  <image class="mine_image" :src="avatarUrl"></image>
</button>

By open-typebinding the function of selecting the user's avatar, and then clicking the button, a pop-up window will pop up:

The onChooseAvatar function gets the WeChat avatar and renders it on the page

onChooseAvatar(e)
	{
			this.avatarUrl = e.detail.avatarUrl
			uni.setStorageSync('avatarUrl',this.avatarUrl)
	},

Here you can choose to use user avatar to modify the user avatar to WeChat avatar:

If you have any questions, please leave a message to discuss, the author is also a beginner, please correct me if there are mistakes~

Guess you like

Origin blog.csdn.net/qq_51235856/article/details/131158254