Home  >  Article  >  WeChat Applet  >  A brief analysis of mini program development practice: how to obtain a mobile phone number

A brief analysis of mini program development practice: how to obtain a mobile phone number

青灯夜游
青灯夜游forward
2021-11-09 10:19:096440browse

How does the mini program obtain the user’s mobile phone number? The following article will introduce to you the method of obtaining the user's mobile phone number in the development of WeChat applet. I hope it will be helpful to you!

A brief analysis of mini program development practice: how to obtain a mobile phone number

1. Background

When you usually use third-party WeChat mini programs, you often need to obtain a WeChat mobile phone number. , as shown in the figure below:

A brief analysis of mini program development practice: how to obtain a mobile phone number

[Related learning recommendations: 小program development tutorial]

How is this implemented? Woolen cloth? The following is a record of how to obtain a WeChat mobile number.

**Note: **You need to have a WeChat mini program account, and this account is certified by the enterprise. (The function of obtaining a mobile phone number does not take effect for personal mini program numbers)

Then let’s start the programming journey of obtaining a mobile phone number together.

2. Code implementation

2.1 Create a new project

in the app.json file Add "pages/getphonenumber/getphonenumber", as shown below:

A brief analysis of mini program development practice: how to obtain a mobile phone number

2.2 Prepare the ciphertext parsing tool class

Obtain the mobile phone number through the interface provided by the WeChat applet. The returned data is encrypted, so the returned encrypted data needs to be decrypted.

1) Create a new terminal

In the WeChat developer tools, click "Terminal" -""New Terminal" as shown below:

A brief analysis of mini program development practice: how to obtain a mobile phone number

2) Execute npm init command

//After executing npm init, you need to enter some information, just keep clicking the "Enter" key

As shown in the figure below:

A brief analysis of mini program development practice: how to obtain a mobile phone number

3) Execute npm install crypto-js --save , npm install js-base64 --save# in sequence

##As shown below:

A brief analysis of mini program development practice: how to obtain a mobile phone number

4) Build npm

in the menu of WeChat development tools Select "Tools" -> "Build npm" in the bar and the build is complete.

2.3 Parsing class implementation

Create a new WXBizDataCrypt.js file in the utils folder of the project. The code implementation is as follows:

var CryptoJS = require("crypto-js");
var Base64 = require("js-base64");

//解析加密数据
function decode(sesionKey,iv,data) {
  var key = CryptoJS.enc.Base64.parse(sesionKey);
  var iv = CryptoJS.enc.Base64.parse(iv);
  var decrypt = CryptoJS.AES.decrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return Base64.decode(CryptoJS.enc.Base64.stringify(decrypt));
}

module.exports = {
 decode
}

2.4 Get the mobile phone number code implementation

##2.4.1 getphonenumber.js implementation

Note: The appId and secret need to be replaced with the

// pages/getphonenumber/getphonenumber.js
const WXBizDataCrypt = require('../../utils/WXBizDataCrypt');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNum:'',
    sessionKey:'',
    openId:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSessionKey();
  },

  getPhoneNumber: function(e){
    if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
      wx.showToast({
        title: '拒绝授权,无法获取用户手机号码!',
      }) 
      return;
    }
    //解密数据获取手机号码
    this.decryptData(this.data.sessionKey,e.detail.iv,e.detail.encryptedData);
  },

  //获取SessionKey
  getSessionKey: function(){
    wx.login({
      success:res =>{
        console.log('code:'+res.code);
        var data = {
          'appid':'***********',//注意appId、secret需要替换为自身小程序的
          'secret':'**************************',
          'js_code':res.code,
          'grant_type':'authorization_code'
        };

        wx.request({
          url:'https://api.weixin.qq.com/sns/jscode2session',
          data:data,
          method:'GET',
          success:res =>{
            console.log("jscode2session result: ",res);
            this.setData({
              sessionKey:res.data.session_key,
              openId: res.data.openId
            })
          },
          fail:function(res){
            console.log("获取jscodeSession fail: ",res);
          }
        })
      }
    })
  },

  //解密数据
  decryptData: function(key,iv,encryptedData){
    var processData = WXBizDataCrypt.decode(key,iv,encryptedData);
    console.log("解密数据: ",processData);
    var jsonObj = JSON.parse(processData);
    this.setData({
      phoneNum: jsonObj['phoneNumber']
    })
  },
})

of your own applet. 2.4.2 getphonenumber.wxml implementation

<!--pages/getphonenumber/getphonenumber.wxml-->
<button type="primary"  bindgetphonenumber="getPhoneNumber" open-type=&#39;getPhoneNumber&#39;>获取手机号码</button>
<text>获取到的手机号码:{{phoneNum}}</text>
At this point, the encoding process has been completed. Note: Under normal circumstances, obtaining jscode2session is implemented on the server side. Here I implement all obtaining sessionKey on the applet. Refer to the official website link of the mini program:

3. Operation rendering

Click to get the mobile phone number:

A brief analysis of mini program development practice: how to obtain a mobile phone numberFor more programming-related knowledge, please visit:

Programming Video

! !

The above is the detailed content of A brief analysis of mini program development practice: how to obtain a mobile phone number. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete