第一次开发小程序,如有错误请多多指出。
消息模版发送说明:详细情况请看官方文档https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/template-message.html
发送模版连接的条件:
1. 支付
当用户在小程序内完成过支付行为,可允许开发者向用户在7天内推送有限条数的模板消息(1次支付可下发3条,多次支付下发条数独立,互相不影响)
2. 提交表单
当用户在小程序内发生过提交表单行为且该表单声明为要发模板消息的,开发者需要向用户提供服务时,可允许开发者向用户在7天内推送有限条数的模板消息(1次提交表单可下发1条,多次提交下发条数独立,相互不影响)
开始发送模版连接的步骤:
一、准备工作
首先,在微信公众平台开通消息推送功能,并添加消息模板。可以从模板库选择模板也可以创建一个模板,模板添加之后,模板ID我们接下来要用的。微信小程序官方文档为我们提供了指导 — 【发送模板消息】
发送模板消息需要用到accesstoken、formId和openID,模版ID。accesstoken就是微信调取APi凭证;formID就是表单ID,消息模板ID,openID我们最好在获取用户信息或用户登录时储存到全局变量里。
二、获取accesstoken
本屌通过查询网上的资料写出的获取accesstoken的方法
三、获取formid
注意“report-submit='true' ”一定要设置为true
<form bind:submit="testSubmit" report-submit="true">
<button formType="submit">发送模板消息</button>
</form>
js:
testSubmit: function (e) {
var formId=e.detail.formId,//表单提交ID
}
四、进行模板发送
//发送模版消息
testSubmit: function (e) {
var self = this;
let _access_token = //获取access_token
let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;
let _jsonData = {
// access_token: _access_token,
"touser": self.data.su_wx_openid,//接收人openID
"template_id": "xxxxx",//模版消息ID
"form_id": "xxxx",//表单提交ID
"page": "pages/index/index",//点击模版后跳转的页面
"data": {//模版内容
'keyword1': { 'value': "接单标题", 'color': '#173177' },
'keyword2': { 'value': '您的订单已有人报名,请注意查收', 'color': '#173177' },
}
}
wx.request({
url: url,
data: JSON.stringify(_jsonData),//注意要转成json形式
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded',
},
success: function (res) {
console.log(res)
console.log('成功!')
},
fail: function (err) {
console.log('request fail ', err);
},
complete: function (res) {
console.log("request completed!");
}
})
},
注意:
开发过程可能会遇到错误,官方全局返回码连接放到下面
参考文献:https://blog.csdn.net/fz250052/article/details/80459778
https://blog.csdn.net/fz250052/article/details/80459778
附上小程序全局返回码连接:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433747234