.net推送微信消息模板
1、获取access_token
public string GetAccess_Token() { string appid = WxPayConfig.APPID; string appsecret = WxPayConfig.APPSECRET; string access_token = ""; string token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret; string result = HttpService.Get(token_url); JsonData jd = JsonMapper.ToObject(result); access_token = (string)jd["access_token"]; return access_token; }
2、模版消息使用Post 推送
public string ModelMessageSend(string data) { string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + GetAccess_Token(); string result = HttpPost(url,data); if (result.Contains("ok")) { return "OK"; } else { return "消息推送失败,具体错误为:"+result; } }
3、HttpPost方法
public string HttpPost(string url,string postData) { 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; }
4、调用进行消息发送
ModelMessageSend(“此处为你的模版/在微信获取”);
例如:会员充值模版
{\"touser\":\"" + wxopenid + "\",\"template_id\":\"0YeXNaDr9KkmF55WdRj9_tRiRCjpV6x8eqTNR0FKNf8\",\"url\":\"\",\"topcolor\":\"#FF0000\",\"data\":{\"first\": {\"value\":\"" + strxm + ",您已成功充值\",\"color\":\"#000000\"},\"accountType\":{\"value\":\"会员卡号\",\"color\":\"#000000\"},\"account\":{\"value\":\"" + touser + "\",\"color\":\"#000000\"},\"amount\":{\"value\":\"" + je + "\",\"color\":\"#000000\"},\"result\":{\"value\":\"充值成功\",\"color\":\"#000000\"},\"remark\":{\"value\":\"" + qtnr + "\",\"color\":\"#000000\"}}}
里面的函数是我定义的。 可以更换为自己的。