假設小程序雲服務已經創建雲函數sum並上傳部署到雲服務
// 雲函數入口文件 sum.js
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database
// 雲函數入口函數
exports.main = async (event, context) => {
return {
sum: event.a+ event.b
}
}
可看出雲函數sum所需要的參數爲形式爲 {a:1,b:2}
我本地使用NodeJs#Request
模塊訪問我的雲服務。
const request = require('request');
const APPID = "你的id";
const APPSECRET = "你的祕鑰";
const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`;
function invokecloudfunction(access_token) {
const FUNCTION_NAME = 'sum';
const ENV = '雲服務環境id';
const INVOKE_CLOUD_FUNCTION_URL = `https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=${access_token}&env=${ENV}&name=${FUNCTION_NAME}`;
return new Promise(function(resolve,reject) {
request.post({
url:INVOKE_CLOUD_FUNCTION_URL,
json: {
a:1,
b:2
}
}, function(err, httpResponse,body) {
if (err) {
reject(err);
} else {
resolve(body);
}
})});
}
// 獲取token
function getAccessToken() {
return new Promise(function(resolve,reject) {
request.get(URL, function(err, httpResponse, body) {
if (err) {
reject(err);
} else {
resolve(JSON.parse(body));
}
});
})
}
// 觸發雲函數
getAccessToken().then((_body)=> {
const {access_token} = _body;
return invokecloudfunction(access_token);
}).then(body => {
console.log(body);
}).catch(err => {
console.log(err);
})