官方文档:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/template-message.html
一、获取fromId
注意:
1.form组件的 report-submit属性需要为true;
2.button组件 formType 属性为submit
wxml:
<form bindsubmit="reviewSubmit" report-submit='true'>
<button
formType="submit"
bindtap="{{reviewing ? '' : 'submitReview'}}"
>{{reviewing ? '已提交' : '提交审核'}}</button>
</form>
js:
reviewSubmit(e){
//获取formId
console.log('获取formId',e);
this.setData({ formId : e.detail.formId})
},
开发工具中模拟会有如下报错,需要用真机调试
报错: the formId is a mock one
然后将openId、formId发送给后端
二、node.js端
拿到后去请求acesstoken
其中appid和secret都是从小程序后台获取的
function getAccessTokenForTemplateMessage (formId,openId) {
let appId = "wxxxxe0";
let secret = "7xxxxxxa";
let options = {
method: 'GET',
url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secret}`,
};
request(options, (error, response, body) => {
if(error) {
console.log('error:',error);
} else {
let _data = JSON.parse(body);
sendTemplateMessage(_data.access_token,formId,openId)
}
});
}
获取access_token后发送模板消息
其中touser, template_id, form_id, access_token都是是必填
template_id也是从小程序后台获取
function sendTemplateMessage (access_token,formId,openId) {
let form = {
"touser": openId,
"template_id": "YuHdg2XyvXEK7pKSrJlEF7JlDyqltn3PPx42-x-fX40",
"form_id": formId };
request({
method: 'POST',
url: `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${access_token}`,
json: true,
headers: { "content-type": "application/json", },
body: form },
(error, response, body) => {
if(error) {
console.log('error: ', error);
} else {
console.log(' ---- 模板消息 body: ', body);
}
})
}
成功