用c#開發微信(1)服務號的伺服器配置和企業號的回撥模式 - url接入
阿新 • • 發佈:2020-10-22
閱讀目錄
最近研究了下服務號的伺服器配置和企業號的回撥模式。真正實現完後,覺得很簡單,但一開始還是走了點彎路,所以寫了個web程式,只用改下配置檔案裡的引數就可以直接用了。下面介紹下詳細的用法以及實現步驟。
本文原文地址:用c#開發微信(1)服務號的伺服器配置和企業號的回撥模式 - url接入
一、用法
1. 下載web程式
http://yunpan.cn/cjeTSAKwUVmv9 訪問密碼 7ab3
2. 修改配置檔案web.config
<appSettings>
<!--微信的Token-->
<add key="WeixinToken" value="dd"/>
<add key="AppId" value="wxdbddd2bc"/>
<add key="AppSecret" value="82f7ddd88e196"/>
<!--企業號配置資訊-->
<add key="CorpToken" value="fddd"/>
<add key="CorpId" value="wx1156d982ddda8"/>
<add key="EncodingAESKey" value="aNvJOkGYddyGwf5Rg"/>
</appSettings>
3. 釋出到你的伺服器上
4. 服務號和企業號裡分別填上url及引數:
企業號:
服務號:
二、實現方法
1. 新建一個web程式
2. 新增二個ashx檔案(這裡不用aspx頁面,是為了更簡便),參考官方文件,實現校驗流程
服務號:
完整原始碼:
/// <summary>
/// 處理微信伺服器驗證訊息
/// </summary>
public void Auth()
{
string token = ConfigurationManager.AppSettings[Token].ToString();
string signature = HttpContext.Current.Request.QueryString["signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
string echostr = HttpContext.Current.Request.QueryString["echostr"];
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
{
//get method - 僅在微信後臺填寫URL驗證時觸發
if (CheckSignature(signature, timestamp, nonce, token))
{
WriteContent(echostr); //返回隨機字串則表示驗證通過
}
else
{
WriteContent("failed:" + signature + "," + GetSignature(timestamp, nonce, token) + "。" +
"如果你在瀏覽器中看到這句話,說明此地址可以被作為微信公眾賬號後臺的Url,請注意保持Token一致。");
}
HttpContext.Current.Response.End();
}
}
private void WriteContent(string str)
{
HttpContext.Current.Response.Output.Write(str);
}
/// <summary>
/// 檢查簽名是否正確
/// </summary>
/// <param name="signature"></param>
/// <param name="timestamp"></param>
/// <param name="nonce"></param>
/// <param name="token"></param>
/// <returns></returns>
public static bool CheckSignature(string signature, string timestamp, string nonce, string token)
{
return signature == GetSignature(timestamp, nonce, token);
}
/// <summary>
/// 返回正確的簽名
/// </summary>
/// <param name="timestamp"></param>
/// <param name="nonce"></param>
/// <param name="token"></param>
/// <returns></returns>
public static string GetSignature(string timestamp, string nonce, string token)
{
string[] arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
string arrString = string.Join("", arr);
System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
byte[] sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
StringBuilder enText = new StringBuilder();
foreach (var b in sha1Arr)
{
enText.AppendFormat("{0:x2}", b);
}
return enText.ToString();
}
官方接入文件:http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html
企業號:
完整原始碼:
public void ProcessRequest(HttpContext context)
{
string postString = string.Empty;
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
{
Auth();
}
}
/// <summary>
/// 成為開發者的第一步,驗證並相應伺服器的資料
/// </summary>
private void Auth()
{
string token = ConfigurationManager.AppSettings["CorpToken"];//從配置檔案獲取Token
string encodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"];//從配置檔案獲取EncodingAESKey
string corpId = ConfigurationManager.AppSettings["CorpId"];//從配置檔案獲取corpId
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);
}
官方接入文件:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%9B%9E%E8%B0%83%E6%A8%A1%E5%BC%8F
3. 配置檔案
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="*" path="MPService.ashx" type="Wechat.Config.MPService,Wechat.Config" validate="true"/>
<add verb="*" path="QYService.ashx" type="Wechat.Config.QYService,Wechat.Config" validate="true"/>
<add verb="*" path="TestAccountService.ashx" type="Wechat.Config.TestAccountService,Wechat.Config" validate="true"/>
</httpHandlers>
</system.web>
如果直接用Senparc.Weixin微信開發框架來實現,就更簡單了:
rotected void Page_Load(object sender, EventArgs e)
private readonly string Token = ConfigurationManager.AppSettings["token"];//與微信公眾賬號後臺的Token設定保持一致,區分大小寫。
string signature = Request["signature"];
string timestamp = Request["timestamp"];
string nonce = Request["nonce"];
string echostr = Request["echostr"];
if (Request.HttpMethod == "GET")
{
//get method - 僅在微信後臺填寫URL驗證時觸發
if (CheckSignature.Check(signature, timestamp, nonce, Token))
{
Response.Output.Write(echostr); //返回隨機字串則表示驗證通過
}
else
{
Response.Output.Write("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
"如果你在瀏覽器中看到這句話,說明此地址可以被作為微信公眾賬號後臺的Url,請注意保持Token一致。");
}
Response.End();
}
}
如果您覺得閱讀本文對您有幫助,請點一下“推薦”按鈕,您的“推薦”將是我最大的寫作動力!歡迎各位轉載,但必須在文章頁面明顯位置給出作者和原文連線,否則保留追究法律責任的權利。
轉載於:https://my.oschina.net/airship/blog/3004698