// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() // 云函数入口函数 exports.main = async (event, context) => { console.log(event) switch (event.action) { case 'requestSubscribeMessage': { return requestSubscribeMessage(event) } case 'sendSubscribeMessage': { return sendSubscribeMessage(event) } case 'getWXACode': { return getWXACode(event) } case 'getOpenData': { return getOpenData(event) } default: { return } } } async function requestSubscribeMessage(event) { // 此处为模板 ID,开发者需要到小程序管理后台 - 订阅消息 - 公共模板库中添加模板, // 然后在我的模板中找到对应模板的 ID,填入此处 return '请到管理后台申请模板 ID 然后在此替换' // 如 'N_J6F05_bjhqd6zh2h1LHJ9TAv9IpkCiAJEpSw0PrmQ' } async function sendSubscribeMessage(event) { const { OPENID } = cloud.getWXContext() const { templateId } = event const sendResult = await cloud.openapi.subscribeMessage.send({ touser: OPENID, templateId, miniprogram_state: 'developer', page: 'pages/openapi/openapi', // 此处字段应修改为所申请模板所要求的字段 data: { thing1: { value: '咖啡', }, time3: { value: '2020-01-01 00:00', }, } }) return sendResult } async function getWXACode(event) { let {path} = event; const wxacodeResult = await cloud.openapi.wxacode.get({ path }) const fileExtensionMatches = wxacodeResult.contentType.match(/\/([^\/]+)/) const fileExtension = (fileExtensionMatches && fileExtensionMatches[1]) || 'jpg' const uploadResult = await cloud.uploadFile({ cloudPath: `images/wxacode/${path.replace(/[\/?&]/g,"_")}.${fileExtension}`, fileContent: wxacodeResult.buffer, }) if (!uploadResult.fileID) { throw new Error(`upload failed with empty fileID and storage server status code ${uploadResult.statusCode}`) } return uploadResult.fileID } async function getOpenData(event) { return cloud.getOpenData({ list: event.openData.list, }) }