控制器:下麵是post發送消息(微信不支持從前臺發送數據,之前試過,報錯,需要跨域,跨域的問題解決後還不行,最後發現之後後端提交 WXApi類: #region 驗證Token是否過期 /// /// 驗證Token是否過期 /// public static bool TokenExpired(s... ...
控制器:下麵是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>