微信通过openID发送消息/后台post、get提交并接…
2018-06-22 06:19:46来源:未知 阅读 ()
控制器:下面是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>
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+S
下一篇:Cannot attach the file “MvcMovie.mdf” as database “aspnet
- Asp.Net MVC4通过id更新表单内容的思路详解 2020-03-19
- .NET下通过HttpListener实现简单的Http服务 2020-02-27
- .net微信服务号发送红包 2020-02-27
- .NET微信开发之PC 端微信扫码注册和登录功能实现 2020-02-23
- ASP.NET Core集成微信登录 2020-02-17
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash