微信小程序云云开发之云函数

写在前面

  • 无需自建服务器
  • 在云端运行的代码,微信私有协议天然鉴权,开发者只需编写自身业务逻辑代码
  • 基本上 所有得操作都可以在云函数上使用
  • 定时任务
  • 个人开发者函数个数有限制,所以尽量类似得函数写一起。

新建小程序

新建小程序得时候选择云开发模式

创建了第一个云开发小程序后,在使用云开发能力之前需要先开通云开发。在开发者工具工具栏左侧,点击 “云开发” 按钮即可打开云控制台、根据提示开通云开发、创建云环境。默认配额下可以创建两个环境,各个环境相互隔离,每个环境都包含独立的数据库实例、存储空间、云函数配置等资源。每个环境都有唯一的环境 ID 标识,初始创建的环境自动成为默认环境。

注:AppID 首次开通云环境后,需等待大约 10 分钟方可正常使用云 API,在此期间官方后台服务正在做准备服务,如尝试在小程序中调用云 API 则会报 cloud init error:{ errMsg: “invalid scope” } 的错误

选择之后默认会给你建一个 cloudfunctions 云函数文件夹 里面会有一些实例
下面这个是云函数 直接获取openid 在云函数中获取然后返回

初始化之后指定默认环境

1
2
3
4
5
6
7
8
9
10
11
// 在 app.js 文件中
// 环境不一样 云函数 都不一样 都需要单独上传
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
/**qaq-uau6p */
wx.cloud.init({
env: "cyq-dev-amyvi",
traceUser: true,
})
}

云函数登陆示例

云函数

1
2
3
4
5
6
7
8
9
10
11
12
13
// index.js
// 写好云函数之后直接右键上传并部署
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
// 这里获取到的 openId、 appId 和 unionId 是可信的,注意 unionId 仅在满足 unionId 获取条件时返回
let { OPENID, APPID, UNIONID } = cloud.getWXContext()

return {
OPENID,
APPID,
UNIONID,
}
}

登陆云函数调用

wx.cloud.callFunction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 代码中直接调用 对应相应得name 就是创建时候上传云函数名称 
// 使用函数 wx.cloud.callFunction
const loginFunction = (userInfoID) => {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'login',
data: {
userInfoData: wx.cloud.CloudID(userInfoID)
},
success: res => {
//返回 OPENID, APPID, UNIONID,
console.log(res)
},
fail: err => {
console.log(err)
}
})
})
}

获取微信运动步数示例

wx.getWeRunData

wx.getWeRunData

1
2
3
4
5
6
7
8
9
//首先获取运动步数 加密数据
wx.getWeRunData({
success (res) {
// 拿 encryptedData 到开发者后台解密开放数据
const encryptedData = res.encryptedData
// 或拿 cloudID 通过云调用直接获取开放数据
const cloudID = res.cloudID
}
})

调用云函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 然后通过调用云函数 自动鉴权 解密运动步数
wx.getWeRunData({
success(res) {
const cloudID = res.cloudID
wx.cloud.callFunction({
name: 'openapi',
data: {
action: 'getWeRunAllData',
weRunData: wx.cloud.CloudID(cloudID),
}
}).then(res => {
// 将步数日期 时间戳转一波
res.result.map(data => {
let date = util.timeStampToTimeV0(data.timestamp);
data.date = (date.getMonth() + 1) + '.' + date.getDate()
})
that.setData({
stepInfoList: res.result
})
selectChart.changeData(res.result)
})
},
fail(res) {
wx.showModal({
title: '提示',
content: '未获得授权,获取步数失败',
showCancel: true,
confirmText: '去授权',
cancelText: '知道了',
success(res) {
if (res.confirm) {
wx.openSetting()
}
}
})
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
// 返回数据
{
"stepInfoList": [
{
"timestamp": 1445866601,
"step": 100
},
{
"timestamp": 1445876601,
"step": 120
}
]
}

云函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 云函数入口函数
exports.main = async (event, context) => {
switch (event.action) {
case 'getWeRunData': {
return getWeRunData(event)
}
case 'getWeRunAllData': {
return getWeRunAllData(event)
}
default: {
return
}
}
}

async function getWeRunAllData(event) {
// 这里自动将 cloudID 所带得数据解析
let stepInfoList = event.weRunData.data.stepInfoList
return stepInfoList
}
async function getWeRunData(event) {
let stepInfoList = event.weRunData.data.stepInfoList

return stepInfoList[stepInfoList.length -1]
}

发送通知模板示例

提示

  • 需要先在微信公共平台-模板库选取模板或者自己申请模板,配置模板->最后获取配置模板ID
  • 页面的 form 组件,属性 report-submit 为 true 时,可以声明为需要发送模板消息,此时点击按钮提交表单可以获取 formId,用于发送模板消息。或者当用户完成 支付行为,可以获取 prepay_id 用于发送模板消息。
  • 当用户在小程序内发生过提交表单行为且该表单声明为要发模板消息的,开发者需要向用户提供服务时,可允许开发者向用户在7天内推送有限条数的模板消息(1次提交表单可下发1条,多次提交下发条数独立,相互不影响) 根据微信文档,消息模板必须用户有过提交才能对他进行发消息提醒。而且七天内过期。
  • 云开发工具不能获取formid 必须在真机上。

获取 formID

1
2
3
4
// wxml 
<view class="weui-btn-area">
<button class="weui-btn" style="background-color:#1589eb;color:white" form-type="submit">打卡申请</button>
</view>
1
2
3
4
5
// 提交js
applyStep: function(e) {
// 获取formid 可以先保存起来
console.log(e.detail.formId)
},

云函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

// 这个是我自己选取得模板ID
const { INVITED, APPLY, AUTH } = {
AUTH: 'MxXKepCWK-yLzCXe5fWW177gE2GXWW-BmNDMw2*****'
}
// 云函数入口函数
exports.main = async (event, context) => {
switch (event.action) {
···
case 'auth': {
return sendAuth(event)
}
···
default: {
return
}
}
}

// 这个模板是发送审核后得结果
async function sendAuth(event) {
const sendResult = await cloud.openapi.templateMessage.send({
// openid
touser: event.touser,
// 模板id
templateId: AUTH,
// formid 必须是之前有过提交得交易或者付款交易 获得id
formId: event.formId,
// 跳转得页面
page: 'pages/Job/Job?JobId='+ event.JobId + '&uid=' + event.touser,
// 配置模板显示得字段
data: {
keyword1: {
value: event.inviteName,
},
keyword2: {
value: event.date,
},
keyword3: {
value: event.result,
},
keyword4: {
value: event.content,
},
}
})

return sendResult
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
wx.cloud.callFunction({
name: 'openapi',
data: {
action: 'auth',
formId: formId,
touser: touser,
JobId: JobId,
inviteName: inviteName,
date: util.formatDateTime(new Date()),
result: result,
content: this.data.applyTextarea
},
success: res => {
console.warn('[云函数] [openapi] templateMessage.send 调用成功:', res)
},
fail: err => {
console.error('[云函数] [openapi] templateMessage.send 调用失败:', err)
}
})

云函数-定时触发器

定时触发器

config.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 新建 config.json 在云函数文件夹中
{
// triggers 字段是触发器数组,目前仅支持一个触发器,即数组只能填写一个,不可添加多个
"triggers": [
{
// name: 触发器的名字,规则见下方说明
"name": "myTrigger",
// type: 触发器类型,目前仅支持 timer (即 定时触发器)
"type": "timer",
// config: 触发器配置,在定时触发器下,config 格式为 cron 表达式,规则见下方说明
"config": "0 0 2 1 * * *"
}
]
}
// 在云函数得文件夹右键 上传触发器就可以了 如果cron表达式写错了会提示,但是感觉有时候写对了也提示错误。
  • /5 * 表示每5秒触发一次
  • 0 0 2 1 * 表示在每月的1日的凌晨2点触发
  • 0 15 10 MON-FRI * 表示在周一到周五每天上午10:15触发
  • 0 0 10,14,16 表示在每天上午10点,下午2点,4点触发
  • 0 /30 9-17 * 表示在每天上午9点到下午5点内每半小时触发
  • 0 0 12 WED * 表示在每个星期三中午12点触发

云函数

1
2
3
4
5
6
7
8
9
10
11
12
13
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
// 可以根据业务 查询库里得任务啊等做业务操作
return await db.collection("Test").add({
data:{
timestamp: Date.parse(new Date())
}
})
}

小程序示例

小程序代码睿智小程序



扫码体验


Powered by Hexo

Copyright © 2016 - 2019 When I think of you, I smile. All Rights Reserved.

UV : | PV :