search
HomeWeChat AppletMini Program DevelopmentA brief analysis of mini program development practice: how to obtain a mobile phone number

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:掘金社区. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),