关于微信小程序:微信小程序用云函数获取绑定的手机号

4次阅读

共计 1107 个字符,预计需要花费 3 分钟才能阅读完成。

  1. 首先,在页面里写个获取手机号的专用 button,(这是小程序官网规定的)

    <button class="btn-sure" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"> 点击获取手机号 </button>
  2. 而后在该页面同目录的 js 文件写对应办法:
getPhoneNumber(e) {
    let self = this;
    wx.cloud.callFunction({
      name: 'getMobileNumber',
      data: {code: e.detail.code, // 根底库最低 2.21.2,否则获取不到}
    }).then(res => {
      self.setData({userPhoneNumber: res.result.phoneInfo.phoneNumber})
    })
  },
  1. 在 cloudfunctions 文件夹上右键新建云函数 getMobileNumber,如下图

    其中,config.json 的内容如下:
{
  "permissions": {
    "openapi": ["templateMessage.send"]
  }
}

index.js 的内容如下:

const cloud = require('wx-server-sdk')

// cloud.init() 
cloud.init({env: '云函数的环境 id' // 传不传都行,app.js 里曾经配置过了的})

exports.main = async (event, context) => {const phoneResult = await cloud.openapi.phonenumber.getPhoneNumber({code:event.code})
  return phoneResult
}

package.json 的内容是生成的,大抵如下:

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

app.js 的配置如下:

App({onLaunch: function () {if (!wx.cloud) {console.error('请应用 2.2.3 或以上的根底库以应用云能力');
    } else {
      wx.cloud.init({
        env: "云函数的环境 id",
        traceUser: true,
      });
    }
  }
})
正文完
 0