同樣的
本案例也是採用大名鼎鼎的 Senparc 微信開發套件
廢話不多說,具體程式碼如下
using ShouJia.BO; using ShouJia.Common; using ShouJia.Debugger; using ShouJia.Facades; using ShouJia.Framework; using Senparc.Weixin.MP; using System; using System.Data; using System.Data.Common; using System.IO; using System.Security; using System.Security.Cryptography; using System.Text; using System.Web; namespace ShouJia.VXinWeb { /// <summary> /// WxAuth 的摘要描述 /// </summary> public class WxAuth : IHttpHandler { private string Token = string.Empty; private int GarageID; public void ProcessRequest(HttpContext c) { GarageID = int.Parse(CommonHelper.RequestParam("GarageID")); WebLogs.Debug( "API Auth Get GarageID", GarageID.ToString() ); Token = WeixinBehaviors.GetApiAuthToken(GarageID); WebLogs.Debug( "API Auth Get Token", Token ); string signature = CommonHelper.RequestParam("signature"); WebLogs.Debug( "API Auth Get signature", signature ); string timestamp = CommonHelper.RequestParam("timestamp"); WebLogs.Debug( "API Auth Get timestamp", timestamp ); string nonce = CommonHelper.RequestParam("nonce"); WebLogs.Debug( "API Auth Get nonce", nonce ); string echostr = CommonHelper.RequestParam("echostr"); WebLogs.Debug( "API Auth Get echostr", echostr ); if ( HttpContext.Current.Request.HttpMethod.ToUpper() == "GET" ) { // get method - 仅在微信后台填写URL验证时触发 if ( CheckSignature.Check( signature, timestamp, nonce, Token ) ) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } HttpContext.Current.Response.End(); } else { // post method - 当有用户想公众账号发送消息时触发 if ( !CheckSignature.Check( signature, timestamp, nonce, Token ) ) { WriteContent("参数错误!"); return; } using (Stream s = HttpContext.Current.Request.InputStream) { Byte[] postBytes = new Byte[s.Length]; s.Read(postBytes, 0, (Int32)s.Length); string postStr = Encoding.UTF8.GetString(postBytes); var h = new Tools.CustomMessageHandler(); h.ResponseXmlData(postStr); } } } private void WriteContent(string output_str) { HttpContext.Current.Response.Write(output_str); } public bool IsReusable { get { return false; } } } }
时间: 2024-10-07 11:56:03