1、創建雲函數
在雲開發中創建雲函數(sum,調用需要兩個參數:a、b):

2、invokeCloudFunction觸發雲函數
const request = require('request');
const APPID = "你的id";
const APPSECRET = "你的秘鑰,獲取APPID一樣差不多";
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);
})

3、注意事項
| 屬性 | 類型 | 默認值 | 必填 | 說明 |
|---|---|---|---|---|
| access_token | string | 是 | 接口調用憑證 | |
| env | string | 是 | 雲開發環境ID | |
| name | string | 是 | 雲函數名稱 | |
| POSTBODY | string | 是 | 雲函數的傳入參數,具體結構由開發者定義。 |
一開始根據官方文檔我使用postman請求,發現一個問題使用params帶參數請求,雲函數后台竟然接收不到參數

解決辦法:POSTBODY要寫標准的json格式,雙引號 否則接收不了

