Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The small program needs to obtain the mobile phone number is often used, there are two methods to achieve: (1) server method: Code2Session is used to obtain the session_key, and then decrypts the obtained encryptedData to obtain the mobile phone number. (2) By calling the cloud function method: it must be triggered by button’s click, including the head picture and customer service, which need to be triggered and obtained by Button’s click.

It should be noted that obtaining the mobile phone number is not currently available for personal authentication, that is, only domestic authenticated enterprise accounts can be used. For details, please refer to the official website document to obtain the phone number

Let’s share the cloud function method with you. The steps are as follows:

(1) Get cloudID via getPhoneNumber, which can only be triggered by button.

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" 
class="uploader-text"> Please click authorize your mobile phone number </button>Copy the code

Interface style:

(2) Define cloud functions

async function getPhoneNum(event) {
  var moblie = event.weRunData.data.phoneNumber;
  return moblie
}
Copy the code

Note to beginners: cloudfunctions are defined in cloudfunctions and need to be exported in index.js. You also need to add the event name on the cloud development page.

(3) Call the cloud function

getPhoneNumber(e){
    let cloudID = e.detail.cloudID // Open data ID
   
    if(! cloudID) { app.showToast('User not authorized')
        return
    }
    // Call the cloud function to get the phone number
    wx.cloud.callFunction({
        name: 'getPhoneNum'.data: {
          weRunData: wx.cloud.CloudID(e.detail.cloudID),
        }
      })
      .then( res= > {
          console.log('Mobile phone Number', res)
      })
      .catch( err= > {
        console.log('Err', err)
      })
  },
Copy the code

(4) The result is as follows