本文實(shí)例講述了微信小程序實(shí)現(xiàn)發(fā)送模板消息功能。分享給大家供大家參考,具體如下:
一、獲取access_token
access_token是接口調(diào)用的憑證,目前有效期為兩個(gè)小時(shí),需要定時(shí)刷新,重復(fù)獲取將導(dǎo)致上次獲取的access_token失效。(注:不建議每次調(diào)用需要access_token的接口,都去重新獲取access_token,會導(dǎo)致失?。?/p>
獲取access_token的接口地址:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
返回參數(shù)格式:
{"access_token": "ACCESS_TOKEN", "expires_in": 7200}
二、發(fā)送模板消息
先在微信公眾平臺選用怒需要的模板id,例如
選用模板消息:
https://mp.weixin.qq.com/wxopen/tmplmsg?action=self_list&token=264012870&lang=zh_CN
選用的是購買成功的模板,關(guān)鍵字可以自己定義順序,如果不符合你的情況,還可以自定義關(guān)鍵字
選用好了之后,可以在我的模板中查看。然后將其模板id復(fù)制過來。
類似于這樣 : _CfGS7SqVyNPg9Op8OXzMp6aOl7X9rCkrRfiMcccms8
發(fā)送模板的消息接口地址:
https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN
參數(shù):
touser (必填) 接收者(用戶)的 openid
template_id (必填) 所需下發(fā)的模板消息的id
page (可選) 點(diǎn)擊模板卡片后的跳轉(zhuǎn)頁面,僅限本小程序內(nèi)的頁面。支持帶參數(shù),(示例index?foo=bar)。該字段不填則模板無跳轉(zhuǎn)。
form_id (必填) 表單提交場景下,為 submit 事件帶上的 formId;支付場景下,為本次支付的 prepay_id
data (必填) 模板內(nèi)容,不填則下發(fā)空模板
color (可選) 模板內(nèi)容字體的顏色,不填默認(rèn)黑色
emphasis_keyword (可選) 模板需要放大的關(guān)鍵詞,不填則默認(rèn)無放大
例如
html
<form bind:submit="testSubmit" report-submit="true"> <button formType="submit">發(fā)送模板消息</button> </form>
js
testSubmit:function(e){ var self= this; let _access_token = '5_E1pZJQzTC-lC0r-JJz9wVAZv5Zv22CNtmV_7C1T0sqC9TV7mGE4FTmDX2B0PVM4LaGtaTfXwzfJLnD7fDKTg8DOICJNkKBQgn_Ot2zYmBJyY1g1VXoBNdtwUE0QaP8_9tWlbR-Zq7L1OyrrPKCIjAEAOGM'; let url='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+_access_token; let _jsonData = { access_token: _access_token, touser: openid, template_id: '_CfGS7SqVyNPg9Op8OXzMp6aOl7X9rCkrRfiMcccms8', form_id: e.detail.formId, page: "pages/index/index", data: { "keyword1": { "value": "測試數(shù)據(jù)一", "color": "#173177" }, "keyword2": { "value": "測試數(shù)據(jù)二", "color": "#173177" }, "keyword3": { "value": "測試數(shù)據(jù)三", "color": "#173177" }, "keyword4": { "value": "測試數(shù)據(jù)四", "color": "#173177" }, } } wx.request({ url: url, data: data, method: method, success: function (res) { console.log(res) }, fail: function (err) { console.log('request fail ', err); }, complete: function (res) { console.log("request completed!"); } })
結(jié)果:
類似于這種
希望本文所述對大家微信小程序開發(fā)有所幫助。
新聞熱點(diǎn)
疑難解答