.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\"}}}

里面的函數是我定義的。 可以更換為自己的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM