小程序云函数运用

timg1123.jpg

获取openid,appid,unionid

在项目根目录找到 project.config.json 文件,新增 cloudfunctionRoot 字段,指定本地已存在的目录作为云函数的本地根目录

示例:

{ "cloudfunctionRoot": "./cloudfunctions/" }

云函数.png
Snipaste_20210930_171536.jpg

此处新建云函数,与在cloudfunctions文件夹函数名字的相同

Snipaste_20201123_164522.jpg

之后上传部署上去

Snipaste_20210930_172729.jpg

下面是一个云函数默认的index.js文件,新建完不用修改,可以拿到openid,appid,unionid,授权手机号后可以在event里面拿到手机号

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() // 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext() return { event, openid: wxContext.OPENID, appid: wxContext.APPID, unionid: wxContext.UNIONID, } }

小程序端获取openid

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
wx.cloud.callFunction({ name: 'getMobile', complete: res => { openId = res.result.userInfo.openId; } })

或Promise风格

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
wx.cloud.callFunction({ // 云函数名称 name: 'add', // 传给云函数的参数 data: { a: 1, b: 2, }, }) .then(res => { console.log(res.result.openId;) // 3 }) .catch(console.error)

获取手机号

获取用户手机需要调用事件授权

          
  • 1
<button class="quickLogin" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">

获取授权后将weRunData传送给云函数获取event对象

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
decryptPhoneNumber(e) { var that = this; wx.cloud .callFunction({ name: "getMobile", data: { weRunData: wx.cloud.CloudID(e.detail.cloudID), }, }) .then((res) => { //获取用户手机 let openid=res.result.openid let phoneNumber = res.result.event.weRunData.data.phoneNumber; console.log(phoneNumber) })
Snipaste_20201123_171453.jpg

tips:记得在小程序页面初始化使用云函数

          
  • 1
  • 2
  • 3
  • 4
  • 5
//云函数初始化 wx.cloud.init({ env: envid, //这个是设置里面的环境id traceUser: true })
---end---
(完)
Docker基本操作
一些基本操作,指令
vue3.2 Keepalive踩坑
vite-plugin-vue-setup-extend 插件给script标签赋值name属性,小问题花费我一天找答案
python Flask request 获取多文件
使用request.files.getlist('')
随便谈谈最近股市
全网都是AI了吧
谈谈债券,可转债,国债
债券到底是什么?可转债和债券的关系?可转债啥时卖?国债利率上升对股市,经济产生的影响?
2020我在干啥?
误删照片引发的随笔
等待你的评论