微信小程序云调用获取手机号码

用代码说话

只有用户主动触发才能发起获取手机号码的API

button组件的open-type设置为getPhoneNumber,用户授权之后通过bindgetphonenumber获取微信服务器的加密数据,

开通云开发之后就可以获取到CloudId

创建云函数(getMobile):

index.js

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  var moblie = event.weRunData.data.phoneNumber;
  return {
    moblie
  }
}

package.json:

{
  "name": "getMobile",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "wx-server-sdk": "latest"
  }
}

小程序端调用


  getPhoneNumber(e) {
    console.log(e)
    const that = this;
    wx.cloud.callFunction({
      name: 'getMobile',
      data: {
        weRunData: wx.cloud.CloudID(e.detail.cloudID),
      }
    }).then(res => {
        console.log(res)
        that.setData({
          phone: res.result.moblie
        })
    }).catch(err => {
      console.error(err);
    });
  }

你可能感兴趣的:(小程序)