本文主要是介绍c#给微信公众号发送通知,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
//给微信公众号发送通知
[HttpGet]
public string SendWeChatMsg()
{
string OpenID = "";
//Appid
string appid = "";
//secret
string secret = "";
if (OpenID != "")
{
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "textml;charset=UTF-8";
string jsonData = "";
using (HttpWebResponse response1 = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response1.GetResponseStream(), Encoding.UTF8))
{
jsonData = sr.ReadToEnd();
sr.Close();
}
response1.Close();
}
if (jsonData != "")
{
string jsonString = jsonData;
JObject json = JObject.Parse(jsonString);
string access_token = json["access_token"].ToString();
string str = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
//json参数,传入对应的值
string jsonParam = "{\"touser\": \"" + OpenID + "\",\"template_id\": \"\",\"data\": {\"cols1\": { \"value\": \"\"}," +
"\"cols2\": { \"value\": \"\"}," +
"\"cols3\": { \"value\": \"\"}," +
"\"cols4\": { \"value\": \"\"}}}";
HttpWebRequest requests = (HttpWebRequest)WebRequest.Create(str);
requests.Method = "POST";
requests.Timeout = 20000;
requests.ContentType = "application/json;charset=UTF-8";
byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
int length = byteData.Length;
requests.ContentLength = length;
using (Stream writer = requests.GetRequestStream())
{
writer.Write(byteData, 0, length);
writer.Close();
}
string jsonStrings = string.Empty;
using (HttpWebResponse responses = (HttpWebResponse)requests.GetResponse())
{
using (Stream streams = responses.GetResponseStream())
{
using (StreamReader readers = new StreamReader(streams, System.Text.Encoding.UTF8))
{
jsonStrings = readers.ReadToEnd();
responses.Close();
streams.Close();
readers.Close();
}
}
}
}
}
return "";
}
这篇关于c#给微信公众号发送通知的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!