小程序发送模板消息node.js

官方文档:
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端

文档:
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/template-message/templateMessage.send.html

拿到后去请求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);
        }
    })
  }

成功
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值