小程序之发送模板消息

微信小程序基于微信的通知渠道,也提供了消息通知能力,即模板消息,但这种消息只有在提交表单和支付时才能进行。模板推送位置:服务通知。

 

步骤:

1.微信小程序后台配置模板(他会生成一个模板id,发送模板消息的时候要用的)注:总共可添加25个模板

2.获取ACCESS_TOKEN(凭证有效时间,单位:秒。目前是7200秒之内的值即2小时。)

wx.request({

url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET',

data: {},

method: 'GET',

success: function (res) {

// success

console.log('get AccessToken')

console.log(res.data.access_token)

},

fail: function () {

// fail

},

complete: function () {

// complete

}

})

将获取到的access_token进行保存,用来获取openid和提交模板消息。

3.获取OPENID

wx.request({

url: 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code',

data: {},

method: 'GET',

// header: {}, // 设置请求的 header

success: function (res) {

// success

console.log('get openid')

console.log(res.data.openid)

},

fail: function () {

// fail

},

complete: function () {

// complete

}

})

其中JSCODE为wx.login成功后返回的res.code。 

保存返回的openid。

4.获取模板ID

登录https://mp.weixin.qq.com/wxopen/tmplmsg?action=self_list&token=1588033132&lang=zh_CN获取模板,如果没有合适的模板,可以申请添加新模板,审核通过后即可使用。

5.提交模板消息(注:提交的from表单上必须加report-submit="true"

wx.request({

url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_token,

data: {

"touser": openid,

"template_id": templateid,

"form_id": e.detail.formId,

"data": {

"keyword1": {

"value": "w的博客",

"color": "#173177"

},

"keyword2": {

"value": "2017年01月22日 17:30",

"color": "#173177"

},

"keyword3": {

"value": "可乐加冰可乐",

"color": "#173177"

},

"keyword4": {

"value": "上海市徐汇区",

"color": "#173177"

}

},

"emphasis_keyword": "keyword1.DATA"

},

method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT

// header: {}, // 设置请求的 header

success: function (res) {

// success

console.log(res)

}

})

点击submit按钮后,就会在微信的服务器通知中受到对应的消息。

 

需要注意的地方:

1.一个from表单提交只能生成一个fromId,一个fromId只能使用一次,

想要发多个通知的话可以收集一些fromId持久化到数据库。

2.fromId的有效期是7天

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值