用代码说话

只有用户主动触发才能发起获取手机号码的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"
  }
}

小程序端调用

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号码</button>
  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);
    });
  }
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐