
以上是微信官方后台需要設置的,
以下是我們自己的程序頁面對接配置的一些設置:



字段說明:
平台名稱:看圖片,關注公眾號時顯示的歡迎關注(平台名稱)
APPID:這個必須和微信官網的一致
Appsecret:這個必須和微信官網的一致
Token:這個必須和微信官網的一致
授權域名:這個必須是微信官網設置的授權回調頁面地址是一樣的,
功能說明:這個就是關注公眾號時顯示的圖文消息下的那幾段話,
官方網址:這個就是點擊關注公眾號時顯示的圖文消息的跳轉地址
關注時的圖片:這個就是點擊關注公眾號時顯示的圖文消息的圖片
處理方法:把字段信息保存到本地數據庫,這里呢,我設置了兩個,如果你關注了微信測試號本地測試時使用另外一個,真正的項目就切換到另外一個
設置好以后,還沒有啟用這個配置,只需點擊一下設置默認(只是將狀態更改為1而已)即可,隨后,在頁面調用的時候,調用微信服務類
代碼如下:
/// <summary> /// 獲取微信公眾號的AppId /// </summary> public static string GetAppId() { //獲取使用中的微信配置信息 WeChatConfigService wcf = new WeChatConfigService(); WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse(); if (wcfInfo != null) { return wcfInfo.wechat_AppId.ToString(); } return null; ; } /// <summary> /// 獲取微信公眾號的AppSecret /// </summary> public static string GetAppSecret() { //獲取使用中的微信配置信息 WeChatConfigService wcf = new WeChatConfigService(); WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse(); if (wcfInfo != null) { return wcfInfo.wechat_AppSecret.ToString(); } return null; ; } /// <summary> /// 獲取本地設置的Token /// </summary> public static string GetToken() { //獲取使用中的微信配置信息 WeChatConfigService wcf = new WeChatConfigService(); WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse(); if (wcfInfo != null) { return wcfInfo.wechat_Token.ToString(); } return null; ; } /// <summary> /// 獲取網頁授權域名 /// </summary> public static string GetpostUrl() { //獲取使用中的微信配置信息 WeChatConfigService wcf = new WeChatConfigService(); WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse(); if (wcfInfo != null) { return wcfInfo.wechat_PostUrl.ToString(); } return null; ; } /// <summary> /// 獲取通行證 /// </summary> /// <returns></returns> public string GetAccessToken() { //獲取使用中的微信配置信息 WeChatConfigService wcf = new WeChatConfigService(); WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse(); string appid = ""; string secret = ""; if (wcfInfo != null) { //初始化微信配置信息 appid = wcfInfo.wechat_AppId.ToString(); secret = wcfInfo.wechat_AppSecret.ToString(); } string url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url_token); myRequest.Method = "GET"; HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); reader.Close(); return content; }
在項目的根目錄或者特定的文件夾內,創建一個ashx文件(一般處理程序文件),如圖
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string postString = string.Empty; if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { using (Stream stream = HttpContext.Current.Request.InputStream) { Byte[] postBytes = new Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); postString = Encoding.UTF8.GetString(postBytes); } if (!string.IsNullOrEmpty(postString)) { ResponseXML(postString);//返回給微信用戶信息 } ///加載自定義菜單
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("\"button\":[ ");
sb.Append("{ ");
sb.Append("\"name\":\"好好學習\",");
sb.Append("\"sub_button\":[");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"微學堂\", ");
sb.Append("\"key\":\"weixuetang\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"大咖說\", ");
sb.Append("\"key\":\"dakashuo\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"好書推薦\", ");
sb.Append("\"key\":\"haoshutuijian\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"講師風采\", ");
sb.Append("\"key\":\"jiangshifengcai\"");
sb.Append("}]");
sb.Append("},");
sb.Append("{");
sb.Append("\"name\":\"天天向上\", ");
sb.Append("\"sub_button\":[");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"看見\", ");
sb.Append("\"key\":\"kanjian\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"撩我\", ");
sb.Append("\"key\":\"liaowo\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"view\",");
sb.Append("\"name\":\"文化UP\", ");
sb.Append("\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeiXinServer.GetAppId().ToString()+"&redirect_uri=" + HttpUtility.UrlEncode(""+WeiXinServer.GetpostUrl().ToString()+"/wenhuaup/wenhua_home.aspx") + "&response_type=code&scope=snsapi_base&state=" + new Random().Next(1000, 200000).ToString() + "#wechat_redirect\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"蘿卜快來\", ");
sb.Append("\"key\":\"luobokuailai\"");
sb.Append("}]");
sb.Append("},");
sb.Append("{");
sb.Append("\"name\":\"員工自助\",");
sb.Append("\"sub_button\":[");
sb.Append("{ ");
sb.Append("\"type\":\"click\",");
sb.Append("\"name\":\"我的薪資\", ");
sb.Append("\"key\":\"mysalary\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"view\",");
sb.Append("\"name\":\"個人中心\", ");
sb.Append("\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinServer.GetAppId().ToString() + "&redirect_uri=" + HttpUtility.UrlEncode(""+WeiXinServer.GetpostUrl()+"/UserLogin.aspx") + "&response_type=code&scope=snsapi_base&state=" + new Random().Next(1000, 200000).ToString() + "#wechat_redirect\"");
sb.Append("},");
sb.Append("{ ");
sb.Append("\"type\":\"view\",");
sb.Append("\"name\":\"在線提問\", ");
sb.Append("\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinServer.GetAppId().ToString() + "&redirect_uri=" + HttpUtility.UrlEncode(""+WeiXinServer.GetpostUrl()+"/UserCenter/question/MyQuestion.aspx") + "&response_type=code&scope=snsapi_base&state=" + new Random().Next(1000, 200000).ToString() + "#wechat_redirect\"");
sb.Append("}]");
sb.Append("}]");
sb.Append("}");
//自定義菜單token的獲取 是用 下面的兩個參數 獲取的 不能直接用 公眾平台的token
string to = GetAccessToken();
//本人不喜歡 后台 json的操作 直接截取就可以了 得到的就是 token 或者 自己 獲取 json的token
to = to.Substring(17, to.Length - 37);
//加載菜單
string i = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + to, sb.ToString()); } else { Auth(); //微信接入的測試 } } /// <summary>
/// 獲取通行證
/// </summary>
/// <returns></returns>
public string GetAccessToken()
{
string url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinServer.GetAppId().ToString() + "&secret=" + WeiXinServer.GetAppSecret().ToString();
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url_token);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
return content;
}/// <summary> /// 加載菜單項 /// </summary> /// <param name="p"></param> /// <param name="postData"></param> /// <returns></returns> private string GetPage(string p, string postData) { 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(p) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "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; return string.Empty; } } /// <summary> /// 獲取參數進行認證 /// </summary> private void Auth() { string token = WeiXinServer.GetToken().ToString();//你申請的時候填寫的Token,必須和微信上的保持一致 string echoString = HttpContext.Current.Request.QueryString["echoStr"]; string signature = HttpContext.Current.Request.QueryString["signature"]; string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; if (CheckSignature(token, signature, timestamp, nonce)) { if (!string.IsNullOrEmpty(echoString)) { HttpContext.Current.Response.Write(echoString); HttpContext.Current.Response.End(); } } } /// <summary> /// 對微信傳入參數進行封裝到數組,拼接字符串,進行加密操作 /// </summary> /// <param name="token"></param> /// <param name="signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <returns></returns> private bool CheckSignature(string token, string signature, string timestamp, string nonce) { string[] ArrTmp = { token, timestamp, nonce };//將參數放進數組 Array.Sort(ArrTmp);//對數組進行排序 string tmpStr = string.Join("", ArrTmp);//將數組進行拼接 ///對拼接后的字符串進行加密操作 tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); //轉換成小寫形式 tmpStr = tmpStr.ToLower(); //比對成功返回 if (tmpStr == signature) { return true; } else { return false; } }
/// <summary>
/// 點擊關注平台后,主動發送給用戶關注后的消息推送
/// </summary>
/// <param name="requestXML"></param>
private void SendWelComeMsg(RequestXML requestXML)
{
String responseContent = String.Empty;
string newdate = DateTime.Now.Subtract(new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds.ToString();
string PUrlfileName = "";
string companyName = "";
string description = "";
string companywebsite = "";
//獲取使用中的微信配置信息
WeChatConfigService wcf = new WeChatConfigService();
WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
if (wcfInfo != null)
{
//初始化微信配置信息
PUrlfileName = WeiXinServer.GetpostUrl().ToString() + "/img/focus/" + wcfInfo.focus_Image.ToString();
companyName = wcfInfo.wechat_Name.ToString();
description = wcfInfo.description.ToString();
companywebsite = wcfInfo.company_website.ToString();
}
responseContent = string.Format(Message_News_Main, requestXML.FromUserName, requestXML.ToUserName, newdate, "1",
string.Format(Message_News_Item, "歡迎關注" + companyName, description, PUrlfileName, companywebsite));
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Write(responseContent);
}
