官方文檔只給出了PHP的示例代碼
開發者提交信息后,微信服務器將發送GET請求到填寫的URL上,GET請求攜帶四個參數:
參數 | 描述 |
---|---|
signature | 微信加密簽名,signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數。 |
timestamp | 時間戳 |
nonce | 隨機數 |
echostr | 隨機字符串 |
開發者通過檢驗signature對請求進行校驗(下面有校驗方式)。若確認此次GET請求來自微信服務器,請原樣返回echostr參數內容,則接入生效,成為開發者成功,否則接入失敗。
加密/校驗流程如下: 1. 將token、timestamp、nonce三個參數進行字典序排序 2. 將三個參數字符串拼接成一個字符串進行sha1加密 3. 開發者獲得加密后的字符串可與signature對比,標識該請求來源於微信
檢驗signature的PHP示例代碼:
private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } }
C#代碼示例如下:
string signature = "a948c4f99d23c1b6ef78204c1eb867166e2276e8";//context.Request.QueryString["signature"];
string timestamp = "1405665299";//context.Request.QueryString["timestamp"];
string nonce = "42752994";//context.Request.QueryString["nonce"];
string token = "Topevery";
List<string> list = new List<string>();
list.Add(token);
list.Add(timestamp);
list.Add(nonce);
list.Sort();
list.Sort();
string res = string.Join("", list.ToArray());
Byte[] data1ToHash = Encoding.ASCII.GetBytes(res);
byte[] hashvalue1 = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(data1ToHash);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashvalue1)
{
sb.Append(b.ToString("x2"));
}
//string s = BitConverter.ToString(hashvalue1).Replace("-", string.Empty).ToLower();
if (signature == sb.ToString())
{
Console.Write("OK");
}
else
{
Console.Write("NO");
}