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 "";
}
标签:string,c#,微信,jsonData,发送,token,Close,using,requests 来源: https://blog.csdn.net/qq_43005276/article/details/118927739