小程序 - 发送模板消息

209 阅读1分钟

模板消息-小程序

  1. 获取FORM_ID
  • 通过form表单获取formid,注:只有通过form表单和支付才能发送模板消息
    <form name='pushMsgFm' report-submit='true' bindsubmit='getFormID'> 
      <button size='mini' form-type="submit" class="zan-btn zan-btn--large zan-btn--danger payButton">获取 form_id</button>
  </form>
  1. 获取 access_token
  • 通过appid和secret获取,在小程序管理后台获取appid和secret
    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.APPID + '&secret=' + config.APPSECRET
  1. 获取openid
    const openid = function (callback = function () { }) {
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求 将code传给服务器
            wx.request({
              url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + config.APPID + '&secret=' + config.APPSECRET + '&js_code=' + res.code + '&grant_type=authorization_code',
              data: {},
              success: function (res) {
                console.log(res)
                callback(res)
              }
            })
          } else {
            console.log('获取用户登录态失败!' + res.errMsg)
          }
        }
      });
    }
  1. 发送模板消息
  • template_id: 模板id,在小程序后台获取,参数相对应即可
    const template = function (params = {}, callback = function () { }) {
      var data = {
        touser: params.openid,
        template_id: config.TEMPLATE_ID.msg,
        form_id: params.form_id,
        data: {
          "keyword1": {
            "value": "测试文字,通过",
            "color": "#4a4a4a"
          },
          "keyword2": {
            "value": new Date(),
            "color": "#9b9b9b"
          }
        },
        page: 'index',
        color: 'red', //颜色
        emphasis_keyword: 'keyword2.DATA' //需要着重显示的关键词
      }
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + params.access_token,
        method: 'POST',
        data: data,
        success: function (res) {
          console.log(res)
          callback(res)
        }
      })
    }
  • 以上涉及的接口https://api.weixin.qq.com在线上环境不允许访问