1.在微信小程序平臺選擇模板json
2.在小程序裏面寫代碼發送小程序
wxml:微信小程序
<form bind:submit="testSubmit" report-submit="true">api
<button formType="submit">發送模板消息</button>微信
</form>session
js:微信開發
var formId = e.detail.formId;app
var access_token1 = '';工具
wx.request({this
url:'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret',
data: {
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "get",
success: function (res) {
console.log(res)
access_token = res.data.access_token;
console.log(res.data.access_token)
let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_token;
wx.login({
success: res => {
// 發送 res.code 到後臺換取 openId, sessionKey, unionId
var that = this;
// 能夠經過 wx.getSetting 先查詢一下用戶是否受權了 "scope.userInfo" 這個 scope
var code = res.code;//登陸憑證 code獲取openid只能使用一次
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=' + code + '&grant_type=authorization_code',
data: {},
header: {
'content-type': 'application/json'
},
success: function (res) {
var openid = res.data.openid //返回openid
console.log("openid是")
console.log(openid);
wx.request({
url: url,
data: {
'touser': openid,
'template_id': 'template_id',//微信品臺的小程序推送模板id
'form_id': formId,
'page': "pages/yhh/index/index",
'data': {
"keyword1": { "value": new Date().getDate, "color": "#173177" },
"keyword2": {
"value": '一個大西瓜',
"color": "#9b9b9b"
},
"keyword3": {
"value": '1000.00',
"color": "#9b9b9b"
},
}
},
method: 'POST',
success: function (res) {
console.log(res)
console.log("發送成功")
},
fail: function (err) {
console.log('request fail ', err);
},
})
}
})
}
})
}
注意的事項
formId是頁面表單發起模板推送的默認id 用e.detail.formId獲取 或者是支付的pre_id
須要openid access_token
在微信開發者工具是不能發送的,會報formId: "the formId is a mock one"錯 , 只能在開發者工具 用遠程調試機制 而後在手機端點擊 而後才能獲取formId,若是報openid 或者 access_token錯 則要注意 access_token每次獲取都不同 而且有時效性