最近公衆平臺的用戶提出了新需求,他們但願當收到新的郵件或者日程的時候,公衆平臺能主動推送一條提醒給用戶。看了看平臺提供的接口,彷佛只有【模板消息】能儘可能知足這一需求,但不得不說微信提供的實例太少,並且只有PHP的,不過摸索了一下仍是成功的實現了。json
首先是準備工做,須要申請開通【模板消息】功能,網上教程不少。而後申請經過以後,用戶能夠從現有的模板裏選擇15個使用,也能夠本身添加模板使用。這裏吐槽一下:申請添加新的模板時,微信出於保護用戶的目的禁止了一些「看起來會很頻繁」的消息類型,好比這圖裏的——api
明明是客戶的需求,結果微信認爲會引發用戶反感因此不經過 =L=微信
後臺代碼:app
/// <summary> /// 功能: 模板消息推送 /// </summary> /// <param name="data"></param> /// <returns></returns> public string ModelMessageSend(string data) { CancelView(); string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + AccessToken; string result = RequestPost(data, url); if (result.Contains("ok")) { return "OK"; } else { return "result"; } }
/// <summary> /// 功能: 模擬Post請求 /// </summary> /// <param name="postData">json</param> /// <param name="url">url</param> /// <returns></returns> public string RequestPost(string postData, string url) { byte[] data = Encoding.UTF8.GetBytes(postData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "Post"; request.ContentType = "application/json"; request.ContentLength = data.Length; request.KeepAlive = true; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); request.Abort(); response.Close(); reader.Dispose(); stream.Close(); stream.Dispose(); return content; }
而後是關於傳入的json數據須要注意,不能使用單引號!post
Ex:{\"touser\":\"oHWXst6bEayYb0m91RtdU4FzxfKY\",\"template_id\":\"Gyi3hZCDK6Y8CmAubONfxoHW7VADuwxz9mO_dObWsE0\",\"url\":\"http://www.baidu.com\",\"topcolor\":\"#FF0000\",\"data\":{\"first\": {\"value\":\"新的通知\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"吃飯!\",\"color\":\"#173177\"},\"keyword2\":{\"value\":\"2015.03.16中午\",\"color\":\"#173177\"},\"keyword3\":{\"value\":\"食堂\",\"color\":\"#173177\"},\"keyword4\":{\"value\":\"張三李四王二麻子\",\"color\":\"#173177\"},\"remark\":{\"value\":\"愛吃吃不吃滾\",\"color\":\"#173177\"}}}url
以前爲了省事使用了單引號,結果一直提示data格式錯誤,把單引號換成\"後就成功了……spa