一、c#微信公眾號開發----基本設定
參考微信官方檔案
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
開發→基本配置
公眾號開發資訊

注:1.記錄好開發者密碼,會在程式中驗證程序中使用到,
2.通過appid和appsecret呼叫access_token時,至有在ip白名單的ip才能成功呼叫,

服務器配置

若此處開啟服務器配置,設定的自動回復和自定義選單將全部失效,必須在程式中重寫相關方法,

點擊修改配置,token為隨意填寫的引數

我是用的是一般處理程式撰寫的微信介面token驗證,引數參考官方檔案,代碼如下:

開發者通過檢驗signature對請求進行校驗,若確認此次GET請求來自微信服務器,請原樣回傳echostr引數內容,則接入生效,成為開發者成功,否則接入失敗,加密/校驗流程如下:
1)將token、timestamp、nonce三個引數進行字典序排序
2)將三個引數字串拼接成一個字串進行sha1加密
3)開發者獲得加密后的字串可與signature對比,標識該請求來源于微信,
1 public void ProcessRequest(HttpContext context){ 2 //驗證token 3 string postString = string.Empty; 4 string token ="aabbcc"; //驗證token,隨意填寫 5 if(string.IsNullEmpty(token)){ 6 return ; 7 } 8 string echoString = HttpContext.Current.Request.QueryString["echoStr"]; 9 string signature = HttpContext.Current.Request.QueryString["sianature"]; 10 string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; 11 string nonce = HttpContext.Current.Request.QueryString["nonce"]; 12 if(CheckSignature(token,signature,timestamp,nonce)){ 13 if(!string.IsNullOrEmpty(echiString)){ 14 HttpContext.Current.Response.Write(echoString); 15 HttpContext.Current.Response.End(); 16 } 17 } 18 }
1 /// <summary> 2 /// 驗證微信簽名 3 /// </summary> 4 /// <param name="token">token</param> 5 /// <param name="signature">簽名</param> 6 /// <param name="timestamp">時間戳</param> 7 /// <param name="nonce">亂數</param> 8 /// <returns></returns> 9 public static bool CheckSignature(string token, 10 string signature, string timestamp, string nonce) 11 { 12 string[] ArrTmp = { token, timestamp, nonce }; 13 //字典排序 14 Array.Sort(ArrTmp); 15 //拼接 16 string tmpStr = string.Join("", ArrTmp); 17 //sha1驗證 18 tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); 19 //tmpStr = Membership.CreateUser(tmpStr, "SHA1"); 20 tmpStr = tmpStr.ToLower(); 21 22 if (tmpStr == signature) 23 { 24 return true; 25 } 26 else 27 { 28 return false; 29 } 30 }
將撰寫的代碼路徑,填寫到url里,前面填寫的“aabbcc”,此時token里填寫的也必須為“aabbcc”,
token必須保持一致,若不一致會彈出提示,


二、獲取timestamp/nonce/signature
timestamp時間戳
public static string timestamp(){
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
nonce亂數
public static string getNoncestr(){
Random random = new Random();
return Md5Util.GetMD5(random.Next(1000).ToString(),”GBK”).ToLower().Replace(“s”,”S”);
}
signature亂數
public static string Signature(string token, string timestamp, string nonce){
string[] ArrTmp = { token, timestamp, nonce };
//字典排序
Array.Sort(ArrTmp);
//拼接
string tmpStr = string.Join("", ArrTmp);
//sha1驗證
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
return tmpStr;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/105777.html
標籤:C#
