為了方便把需要加載的參數寫在.config中
<!--企業號配置信息-->
<add key="CorpToken" value="Davis"/>
<add key="CorpId" value="wx29410ae4e8dfd0b2"/>
<add key="EncodingAESKey" value="CNphWFJxQXQuSDdgaUHGKfl79KsOxJKum144L6ziyuBvk"/>
其次在一般處理程序中編寫代碼如下:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Tencent;
namespace Wechat.Config
{
/// <summary>
/// Summary description for QYService
/// </summary>
public class QYService : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string postString = string.Empty;
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
{
Auth();
}
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 成為開發者的第一步,驗證並相應服務器的數據
/// </summary>
private void Auth()
{
#region 獲取關鍵參數
string token = ConfigurationManager.AppSettings["CorpToken"];//從配置文件獲取Token
if (string.IsNullOrEmpty(token))
{
//LogTextHelper.Error(string.Format("CorpToken 配置項沒有配置!"));
}
string encodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"];//從配置文件獲取EncodingAESKey
if (string.IsNullOrEmpty(encodingAESKey))
{
//LogTextHelper.Error(string.Format("EncodingAESKey 配置項沒有配置!"));
}
string corpId = ConfigurationManager.AppSettings["CorpId"];//從配置文件獲取corpId
if (string.IsNullOrEmpty(corpId))
{
//LogTextHelper.Error(string.Format("CorpId 配置項沒有配置!"));
}
#endregion
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企業號的 msg_signature
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
string decryptEchoString = "";
if (CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString))
{
if (!string.IsNullOrEmpty(decryptEchoString))
{
HttpContext.Current.Response.Write(decryptEchoString);
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// 驗證企業號簽名
/// </summary>
/// <param name="token">企業號配置的Token</param>
/// <param name="signature">簽名內容</param>
/// <param name="timestamp">時間戳</param>
/// <param name="nonce">nonce參數</param>
/// <param name="corpId">企業號ID標識</param>
/// <param name="encodingAESKey">加密鍵</param>
/// <param name="echostr">內容字符串</param>
/// <param name="retEchostr">返回的字符串</param>
/// <returns></returns>
public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
{
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr);
if (result != 0)
{
//LogTextHelper.Error("ERR: VerifyURL fail, ret: " + result);
return false;
}
return true;
//ret==0表示驗證成功,retEchostr參數表示明文,用戶需要將retEchostr作為get請求的返回參數,返回給企業號。
// HttpUtils.SetResponse(retEchostr);
}
}
}
然后在企業號回調函數中配置中輸入:
本文資源來源於網絡牛人,具體忘了。