官方文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/openapi.html
支持接口:https://developers.weixin.qq.com/miniprogram/dev/api-backend/index.html
一、创建云函数并配置相应的权限
image.png{
"permissions": {
"openapi": [
"templateMessage.send"
]
}
}
image.png
必须配置相关的调用权限,否则无法正常调用
二、编写云函数
// 通过云调用,推送模板消息
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async(event, context) => {
var remark = event.remark;
var content = event.content;
var openid = event.openid;
var formid = event.formid;
var time = event.time;
var dealtime = event.dealtime;
try {
const result = await cloud.openapi.templateMessage.send({
touser: cloud.getWXContext().OPENID, // 通过 getWXContext 获取 OPENID
page: 'pages/index/index',
data: {
keyword1: {
value: time // 反馈时间
},
keyword2: {
value: remark // 反馈内容
},
keyword3: {
value: content // 答复内容
},
keyword4: {
value: dealtime // 答复时间
}
},
templateId: 'nY2VgW5stexOgdk73IHO7x6yah8gxHNpt--udckkzfY', // 模板消息ID
formId: formid, // 推送码
emphasisKeyword: ''
})
// result 结构
// { errCode: 0, errMsg: 'openapi.templateMessage.send:ok' }
return result
} catch (err) {
// 错误处理
// err.errCode !== 0
throw err
}
}
三、调用云函数
wx.cloud.callFunction({
name: 'pushmsg',
data: {
remark: remarktemp,
content: pushcontent,
openid: touser,
formid: formid,
time: that.data.time,
dealtime: new Date().format('yyyy-MM-dd hh:mm:ss')
},
success: res => {
console.log(res);
wx.showToast({
title: '发送成功!',
})
wx.cloud.callFunction({ // 【删除】已用formid
name: 'deleteOneFormId',
data: {
objectId: objectid
},
complete: res => {
console.log('删除成功', JSON.stringify(res));
}
})
},
error: err => {
console.log(err);
wx.showToast({
title: '发送失败!',
})
}
});
网友评论