控制器:下面是post发送消息(微信不支持从前台发送数据,之前试过,报错,需要跨域,跨域的问题解决后还不行,最后发现之后后端提交
WXApi类:
#region 验证Token是否过期
/// <summary>
/// 验证Token是否过期
///</summary>
public static bool TokenExpired(
string access_token)
{
string jsonStr = HttpRequestUtil.RequestUrl(
string.Format(
"https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token));
if (Tools.GetJsonValue(jsonStr,
"errcode") ==
"42001")
{
return true;
}
return false;
}
#endregion
#region 获取Token
/// <summary>
/// 获取Token
/// </summary>
public static string GetToken(
string appid,
string secret)
{
string strJson = HttpRequestUtil.RequestUrl(
string.Format(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
return Tools.GetJsonValue(strJson,
"access_token");
}
#endregion
Tools类:
#region 获取Json字符串某节点的值
/// <summary>
/// /// 获取Json字符串某节点的值
/// /// </summary>
public static string GetJsonValue(
string jsonStr,
string key)
{
string result =
string.Empty;
if (!
string.IsNullOrEmpty(jsonStr))
{
key =
"\"" + key.Trim(
'"') +
"\"";
int index = jsonStr.IndexOf(key) + key.Length +
1;
if (index > key.Length +
1)
{
//先截逗号,若是最后一个,截“}”号,取最小值
int end = jsonStr.IndexOf(
',', index);
if (end == -
1)
{
end = jsonStr.IndexOf(
'}', index);
}
result = jsonStr.Substring(index, end -
index);
result = result.Trim(
new char[] {
'"',
' ',
'\'' });
//过滤引号或空格
}
}
return result;
}
#endregion
HttpRequestUtil类:
#region 请求Url,不发送数据
/// <summary>
/// 请求Url,不发送数据
/// </summary>
public static string RequestUrl(
string url)
{
return RequestUrl(url,
"POST");
}
#endregion
#region 请求Url,不发送数据
/// <summary>
/// 请求Url,不发送数据
/// </summary>
public static string RequestUrl(
string url,
string method)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url)
as HttpWebRequest;
CookieContainer cookieContainer =
new CookieContainer();
request.CookieContainer =
cookieContainer;
request.AllowAutoRedirect =
true;
request.Method =
method;
request.ContentType =
"text/html";
//request.GetRequestStream()
//request.
request.Headers.Add(
"charset",
"utf-8");
//发送请求并获取相应回应数据
Stream postStream =
request.GetRequestStream();
//postStream.Write(,0,bytearra)
HttpWebResponse response = request.GetResponse()
as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
//Stream responseStream =
StreamReader sr =
new StreamReader(response.GetResponseStream(), Encoding.UTF8);
//返回结果网页(html)代码
string content =
sr.ReadToEnd();
return content;
}
#endregion
下面是会返回错误44002的:原因是post数据未发送(没有提交数据),也是控制器中:
#region 请求Url,不发送数据
/// <summary>
/// 请求Url,不发送数据
/// </summary>
public static string RequestUrl(
string url)
{
return RequestUrl(url,
"POST");
}
#endregion
#region 请求Url,不发送数据
/// <summary>
/// 请求Url,不发送数据
/// </summary>
public static string RequestUrl(
string url,
string method)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url)
as HttpWebRequest;
CookieContainer cookieContainer =
new CookieContainer();
request.CookieContainer =
cookieContainer;
request.AllowAutoRedirect =
true;
request.Method =
method;
request.ContentType =
"textml";
request.Headers.Add("charset",
"utf-8");
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse()
as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream =
response.GetResponseStream();
StreamReader sr =
new StreamReader(responseStream, Encoding.UTF8);
//返回结果网页(html)代码
string content =
sr.ReadToEnd();
return content;
}
#endregion
)
#region
public string send(
string openida,
string senddata)
{
string posturl =
"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WXApi.GetToken(appID, appsecret);
//发送地址
string postData =
"{\"touser\":\"" + openida +
"\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + senddata +
"\"}}";
//发送消息的字符串 openida为openid,senddata为发送内容
return GetPage(posturl, postData);
//以post的形式发送出去
}
#endregion
#region
public string GetPage(
string posturl,
string postData)
///向微信服务器发送post请求(主要是发送消息)
{
Stream outstream =
null;
Stream instream =
null;
StreamReader sr =
null;
HttpWebResponse response =
null;
HttpWebRequest request =
null;
Encoding encoding =
Encoding.UTF8;
byte[] data =
encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl)
as HttpWebRequest;
CookieContainer cookieContainer =
new CookieContainer();
request.CookieContainer =
cookieContainer;
request.AllowAutoRedirect =
true;
request.Method =
"POST";
//post的形式
request.ContentType =
"application/x-www-form-urlencoded";
request.ContentLength =
data.Length;
outstream =
request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse()
as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream =
response.GetResponseStream();
sr =
new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content =
sr.ReadToEnd();
string err =
string.Empty;
return content;
}
catch (Exception ex)
{
string err =
ex.Message;
//Response.Write(err);
//return string.Empty;
return err;
}
}
#endregion
获取AppID和:appsecret ,(在控制器上面写上)
public static readonly string appID = ConfigurationManager.AppSettings[
"appID"];
public static readonly string appsecret = ConfigurationManager.AppSettings[
"appsecret"];
web.config中需要写入下面信息:
<appSettings>
<add key=
"appID" value=
"wxf39b0be4b27f0016" />
<add key=
"appsecret" value=
"667b57fe3f9126b4c0960b1300c858db" />
</appSettings>
转载于:https://www.cnblogs.com/SeNaiTes/p/8684689.html