步驟一:獲取模板IDhtml
有兩個方法能夠獲取模版ID前端
步驟二:頁面的 <form/>
組件,屬性report-submit
爲true
時,能夠聲明爲需發模板消息,此時點擊按鈕提交表單能夠獲取formId
,用於發送模板消息。或者當用戶完成支付行爲,能夠獲取prepay_id
用於發送模板消息。chrome
步驟三:調用接口下發模板消息json
今天重要的說第三步怎麼實現,前面的步驟比較簡單就略過。api
----------------------------------------------------------------------------------------------------服務器
1. 獲取 access_token微信
後面會在發送模板消息的時候會用到access_token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
2. 發送模板消息app
接口地址:(ACCESS_TOKEN 需換成上文獲取到的 access_token)微信公衆平臺
https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN
注意說明:因爲微信如今不讓開發者直接在前端使用 https://api.weixin.qq.com 接口獲取數據,因此下面的操做都必須由服務器後臺來完成。
官方的POST參數:
{ "touser": "OPENID", "template_id": "TEMPLATE_ID", "page": "index", "form_id": "FORMID", "data": { "keyword1": { "value": "339208499", "color": "#173177" }, "keyword2": { "value": "2015年01月05日 12:30", "color": "#173177" }, "keyword3": { "value": "粵海喜來登酒店", "color": "#173177" } , "keyword4": { "value": "廣州市天河區天河路208號", "color": "#173177" } }, "emphasis_keyword": "keyword1.DATA" }
var l = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token; var tempData = new { touser = openid, template_id = "VErasH9Plzmyw9-PQjiggkBCa3hOU30qfvTaxD******",//這個是一、申請的模板消息id, page ="pages/index/index", form_id = formId, data = new { keyword1 = new { value = title, color = "#666666" }, keyword2 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), color = "#9b9b9b" }, keyword3 = new { value = Remarks, color = "#9b9b9b" } }, color = "#666666" }; X.Component.Tools.WebClient wc = new X.Component.Tools.WebClient(); var result = tempData.ToJson(); //Newtonsoft.Json.JsonConvert.SerializeObject(tempData); wc.Encoding = System.Text.Encoding.UTF8; var obj = wc.Post(l, result); //獲得返回的結果
注意 page路徑spa
最後返回的結果:
{ "data": { "success": true }, "statusCode": 200, "header": { "Server": "Microsoft-IIS/7.5", "Access-Control-Allow-Origin": "https://pubchem.ncbi.nlm.nih.gov", "Cache-Control": "private", "X-UA-Compatible": "chrome=1", "Date": "Thu, 28 Sep 2017 04:46:34 GMT", "X-AspNetMvc-Version": "4.0", "Content-Type": "application/json; charset=utf-8", "X-Powered-By": "ASP.NET", "X-AspNet-Version": "4.0.30319", "Content-Length": "16" }, "errMsg": "request:ok" }
效果截圖: