1、首先,微信公眾平台開發前期准備,需要注冊一個微信公眾平台賬號。(參考微信公眾平台)
2、注冊完成后,會得到開發者ID,如下圖:

3、修改服務器配置,如下圖:

4、服務器配置完成后,點擊提交,微信服務器將發送GET請求到填寫的服務器地址URL上,GET請求攜帶四個參數:
| 參數 | 描述 |
|---|---|
| signature | 微信加密簽名,signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數。 |
| timestamp | 時間戳 |
| nonce | 隨機數 |
| echostr | 隨機字符串 |
開發者通過檢驗signature對請求進行校驗(下面有校驗方式)。若確認此次GET請求來自微信服務器,請原樣返回echostr參數內容,則接入生效,成為開發者成功,否則接入失敗。(具體說明閱讀微信開發者文檔)
5、服務器代碼部分:
Controller
/// <summary>
/// HttpGet請求
/// </summary>
/// <param name="signature">微信加密簽名,signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數</param>
/// <param name="timestamp">時間戳</param>
/// <param name="nonce">隨機數</param>
/// <param name="echostr">隨機字符串</param>
/// <returns></returns>
[HttpGet]
[ActionName("Index")]
public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
{
string token = string.Empty;//公眾平台上,開發者設置的Token;必須為英文或數字,長度為3-32字符
if (string.IsNullOrEmpty(token))
return Content("請在服務器設置Token!");
if (WeiXinBasic.CheckSignature(token, timestamp, nonce, signature) != 0)
return Content("參數設置錯誤!");
return Content(echostr);
}
Core
#region 驗證signature是否合法
/// <summary>
/// 驗證signature是否合法
/// </summary>
/// <param name="token">公眾平台上,開發者設置的Token</param>
/// <param name="timestamp">時間戳,對應URL參數的timestamp</param>
/// <param name="nonce">隨機串,對應URL參數的nonce</param>
/// <param name="signature">加密簽名,對應URL參數的signature</param>
/// <returns></returns>
public static int CheckSignature(string token, string timestamp, string nonce, string signature)
{
string hash = "";
int ret = 0;
ret = GenarateSinature(token, timestamp, nonce, signature, ref hash);
if (ret != 0)
return ret;
//System.Console.WriteLine(hash);
if (hash == signature)
return 0;
else
{
return 40001;//獲取access_token時AppSecret錯誤,或者access_token無效。請開發者認真比對AppSecret的正確性,或查看是否正在為恰當的公眾號調用接口
}
}
private static int GenarateSinature(string token, string timestamp, string nonce, string signature, ref string sMsgSignature)
{
ArrayList AL = new ArrayList();
AL.Add(token);
AL.Add(timestamp);
AL.Add(nonce);
AL.Sort(new DictionarySort());
string raw = "";
for (int i = 0; i < AL.Count; ++i)
{
raw += AL[i];
}
SHA1 sha;
ASCIIEncoding enc;
string hash = "";
try
{
sha = new SHA1CryptoServiceProvider();
enc = new ASCIIEncoding();
byte[] dataToHash = enc.GetBytes(raw);
byte[] dataHashed = sha.ComputeHash(dataToHash);
hash = BitConverter.ToString(dataHashed).Replace("-", "");
hash = hash.ToLower();
}
catch (Exception)
{
return 40003;//不合法的OpenID,請開發者確認OpenID(該用戶)是否已關注公眾號,或是否是其他公眾號的OpenID
}
sMsgSignature = hash;
return 0;
}
public class DictionarySort : System.Collections.IComparer
{
public int Compare(object oLeft, object oRight)
{
string sLeft = oLeft as string;
string sRight = oRight as string;
int iLeftLength = sLeft.Length;
int iRightLength = sRight.Length;
int index = 0;
while (index < iLeftLength && index < iRightLength)
{
if (sLeft[index] < sRight[index])
return -1;
else if (sLeft[index] > sRight[index])
return 1;
else
index++;
}
return iLeftLength - iRightLength;
}
}
#endregion
