protected void Page_Load(object sender, EventArgs e) { #region 是否为验证字符串 string sToken = "wangli83"; string sCorpID = "wx289bd60716320a43"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; if (Request.Params["echostr"] != null) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // string sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature"); string sVerifyMsgSig = Request.Params["msg_signature"]; // string sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp"); string sVerifyTimeStamp = Request.Params["timestamp"]; // string sVerifyNonce = HttpUtils.ParseUrl("nonce"); string sVerifyNonce = Request.Params["nonce"]; // string sVerifyEchoStr = HttpUtils.ParseUrl("echostr"); string sVerifyEchoStr = Request.Params["echostr"]; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); Response.Write(sEchoStr); Response.End(); } #endregion }
/// <summary> /// 加密消息 /// </summary> /// <param name="token"></param> /// <param name="encodingAESKey"></param> /// <param name="corpId"></param> /// <param name="replyMsg"></param> /// <param name="timeStamp"></param> /// <param name="nonce"></param> /// <returns></returns> public static string EncryptMsg(string token, string encodingAESKey, string corpId, string replyMsg, string timeStamp, string nonce) { WXBizMsgCrypt crypt = new WXBizMsgCrypt(token, encodingAESKey, corpId); string encryptMsg = null; var result = crypt.EncryptMsg(replyMsg, timeStamp, nonce, ref encryptMsg); return encryptMsg; }
/// <summary> /// ���á� /// </summary> /// <param name="context">���������ġ�</param> /// <returns>����</returns> public override Task Invoke(IHandlerContext context) { var request = context.Request; var dependencyResolver = context.GetDependencyResolver(); var requestMessageFactory = dependencyResolver.GetService<IRequestMessageFactory>(); var content = Encoding.UTF8.GetString(request.InputStream.ReadBytes()); #region Decrypt var encryptType = request.QueryString["encrypt_type"]; if (encryptType != null) { var nonce = request.QueryString["nonce"]; var signature = request.QueryString["msg_signature"]; var timestamp = request.QueryString["timestamp"]; var baseInfo = context.GetMessageHandlerBaseInfo(); var appId = baseInfo.AppId; var encodingAesKey = baseInfo.EncodingAesKey; var token = baseInfo.Token; var wxBizMsgCrypt = new WXBizMsgCrypt(token, encodingAesKey, appId); wxBizMsgCrypt.DecryptMsg(signature, timestamp, nonce, content, ref content); } #endregion Decrypt context.SetRequestMessage(requestMessageFactory.CreateRequestMessage(content)); return Next.Invoke(context); }
public ActionResult Post(string signature, string timestamp, string nonce, string echostr) { WeixinMessage message = null; var safeMode = Request.QueryString.Get("encrypt_type") == "aes"; using (var streamReader = new StreamReader(Request.InputStream)) { var decryptMsg = string.Empty; var msg = streamReader.ReadToEnd(); #region 解密 if (safeMode) { var msg_signature = Request.QueryString.Get("msg_signature"); var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID); var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decryptMsg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 //注意:本demo用log4net记录此信息,你可以用其他方法 LogWriter.Default.WriteError(string.Format("decrypt message return {0}, request body {1}", ret, msg)); } } else { decryptMsg = msg; } #endregion message = AcceptMessageAPI.Parse(decryptMsg); } var response = new WeixinExecutor().Execute(message); var encryptMsg = string.Empty; #region 加密 if (safeMode) { var msg_signature = Request.QueryString.Get("msg_signature"); var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID); var ret = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref encryptMsg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 LogWriter.Default.WriteError(string.Format("encrypt message return {0}, response body {1}", ret, response)); } } else { encryptMsg = response; } #endregion return new ContentResult { Content = encryptMsg, ContentType = "text/xml", ContentEncoding = System.Text.UTF8Encoding.UTF8 }; }
/// <summary> /// 将企业号回复用户的消息加密打包 /// </summary> /// <param name="appId"></param> /// <param name="sReplyMsg">企业号待回复用户的消息,xml格式的字符串</param> /// <param name="sTimeStamp">时间戳,可以自己生成,也可以用URL参数的timestamp</param> /// <param name="sNonce">随机串,可以自己生成,也可以用URL参数的nonce</param> /// <param name="sEncryptMsg">加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,</param> /// <returns>成功0,失败返回对应的错误码</returns> public static int EncryptMsg(string appId, string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg) { string sToken = "sewapower"; string sAppID = appId; string sEncodingAESKey = "Sd8AFrmKTlF2u5jbQl8vQEYJX57aALEz1OivuIUgD3r"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); return(wxcpt.EncryptMsg(sReplyMsg, sTimeStamp, sNonce, ref sEncryptMsg)); }
/// <summary> /// 调用。 /// </summary> /// <param name="context">处理上下文。</param> /// <returns>任务。</returns> public override Task Invoke(IHandlerContext context) { var responseMessage = context.GetResponseMessage(); if (responseMessage == null) { context.ResponseXml = string.Empty; } else { var requestMessage = context.GetRequestMessage(); //基本信息初始化。 responseMessage.CreateTime = DateTime.Now; responseMessage.FromUserName = requestMessage.ToUserName; responseMessage.ToUserName = requestMessage.FromUserName; var dependencyResolver = context.GetDependencyResolver(); var responseMessageFactory = dependencyResolver.GetService<IResponseMessageFactory>(); var content = responseMessageFactory.GetXmlByReponseMessage(responseMessage); #region Encrypt if (!string.IsNullOrWhiteSpace(content)) { var request = context.Request; var encryptType = request.QueryString["encrypt_type"]; if (encryptType != null) { var nonce = request.QueryString["nonce"]; var timestamp = request.QueryString["timestamp"]; var baseInfo = context.GetMessageHandlerBaseInfo(); var appId = baseInfo.AppId; var encodingAesKey = baseInfo.EncodingAesKey; var token = baseInfo.Token; var wxBizMsgCrypt = new WXBizMsgCrypt(token, encodingAesKey, appId); wxBizMsgCrypt.EncryptMsg(content, timestamp, nonce, ref content); } } #endregion Encrypt context.ResponseXml = content; } return Next.Invoke(context); }
/// <summary> /// 检查签名 /// </summary> /// <param name="token"></param> /// <param name="encodingAESKey"></param> /// <param name="corpId"></param> /// <param name="msgSignature">签名串,对应URL参数的msg_signature</param> /// <param name="timeStamp">时间戳,对应URL参数的timestamp</param> /// <param name="nonce">随机串,对应URL参数的nonce</param> /// <param name="echoStr">随机串,对应URL参数的echostr</param> /// <returns></returns> public static string VerifyURL(string token, string encodingAESKey, string corpId, string msgSignature, string timeStamp, string nonce, string echoStr) { WXBizMsgCrypt crypt = new WXBizMsgCrypt(token, encodingAESKey, corpId); string replyEchoStr = null; var result = crypt.VerifyURL(msgSignature, timeStamp, nonce, echoStr, ref replyEchoStr); if (result == 0) { //验证成功,比较随机字符串 return replyEchoStr; } else { //验证错误,这里可以分析具体的错误信息 return null; } }
public HttpResponseMessage WeChatServiceValidation(string id, string msg_signature, string timestamp, string nonce, string echostr) { var wx = WXManager.Current[id]; if (wx != null) { var wxcpt = new Tencent.WXBizMsgCrypt(wx.Token, wx.EncodingAESKey, wx.AppID); string sEchoStr = ""; var ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret == 0) { var response = Request.CreateResponse(); response.Content = new StringContent(sEchoStr); return(response); } } return(Request.CreateResponse(HttpStatusCode.BadRequest)); }
/// <summary> /// 微信后台消息POST处理函数 /// </summary> /// <param name="id">微信公众号ID,系统可以托管多个公众号,用于区分各个公众号</param> /// <param name="msg_signature">微信后台发过来的签名参数,用于验证是否是微信服务器发的消息</param> /// <param name="timestamp">微信后台发过来的签名参数,用于验证是否是微信服务器发的消息</param> /// <param name="nonce">微信后台发过来的签名参数,用于验证是否是微信服务器发的消息</param> /// <param name="msg">微信POST请求中的消息主体内容,后台会自动用XMLFORMATER反序列化</param> /// <returns></returns> public HttpResponseMessage Post(string id, string msg_signature, string timestamp, string nonce) { try { var wx = WXManager.Current[id]; if (wx != null) { var wxcpt = new Tencent.WXBizMsgCrypt(wx.Token, wx.EncodingAESKey, wx.AppID); var content = Request.Content.ReadAsStringAsync().Result; string xml = ""; // 解析之后的明文 var ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content, ref xml); if (ret == 0) { var stream = new StringReader(xml); WXRequestMsg msg = new XmlSerializer(typeof(WXRequestMsg)).Deserialize(stream) as WXRequestMsg; if (msg != null) { var res = new WXRequestHandler(this.Request).HandleMsg(id, msg); if (res != null) { var response = Request.CreateResponse(); string sRespData = res.ToXML(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, timestamp, nonce, ref sEncryptMsg); if (ret == 0) { response.Content = new StringContent(sEncryptMsg); return(response); } } } } } } catch (Exception ex) { } return(Request.CreateResponse()); }
public XDocument Init() { //解密XML信息 var postDataStr = EcryptRequestDocument.ToString(); WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId); string msgXml = null; var result = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { //验证没有通过,取消执行 CancelExcute = true; return null; } RequestDocument = XDocument.Parse(msgXml);//完成解密 RequestMessage = RequestMessageFactory.GetRequestEntity(RequestDocument); //((RequestMessageBase)RequestMessage).FillEntityWithXml(RequestDocument); return RequestDocument; }
public void ProcessRequest(HttpContext context) { Log.WriteDebug("ProcessRequest start"); try { Stream stream = context.Request.InputStream; byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); string postXmlStr = System.Text.Encoding.UTF8.GetString(byteArray); Log.WriteDebug("1"); if (!string.IsNullOrEmpty(postXmlStr)) { Log.WriteDebug("IsNullOrEmpty"); XmlDocument doc = new XmlDocument(); doc.LoadXml(postXmlStr); if (string.IsNullOrWhiteSpace(sToken)) { Log.WriteDebug("string.IsNullOrWhiteSpace(sToken)"); DataTable dt = ConfigDal.GetConfig(WXMsgUtil.GetFromXML(doc, "ToUserName")); DataRow dr = dt.Rows[0]; sToken = dr["Token"].ToString(); sAppID = dr["AppID"].ToString(); sEncodingAESKey = dr["EncodingAESKey"].ToString(); Log.WriteDebug(sToken + "\r\n" + sAppID + "\r\n" + sEncodingAESKey + "\r\n"); } Log.WriteDebug("2"); if (!string.IsNullOrWhiteSpace(sAppID)) //没有AppID则不解密(订阅号没有AppID) { Log.WriteDebug("!string.IsNullOrWhiteSpace(sAppID)"); //解密 WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string signature = context.Request["msg_signature"]; string timestamp = context.Request["timestamp"]; string nonce = context.Request["nonce"]; Log.WriteDebug(signature + "\r\n" + timestamp + "\r\n" + nonce + "\r\n"); string stmp = ""; int ret = wxcpt.DecryptMsg(signature, timestamp, nonce, postXmlStr, ref stmp); if (ret == 0) { doc = new XmlDocument(); doc.LoadXml(stmp); try { Log.WriteDebug("3"); responseMsg(context, doc); } catch (Exception ex) { //FileLogger.WriteErrorLog(context, ex.Message); Log.WriteError(ex.Message); } } else { //FileLogger.WriteErrorLog(context, "解密失败,错误码:" + ret); Log.WriteError("解密失败,错误码:" + ret); } } else { Log.WriteDebug("responseMsg(context, doc);"); responseMsg(context, doc); } } else { Log.WriteError("valid(context);"); valid(context); } } catch (Exception ex) { //FileLogger.WriteErrorLog(context, ex.Message); Log.WriteError("ProcessRequest" + context.ToString() + ex.Message); } }
public void responseMsg(HttpContext context, XmlDocument xmlDoc) { string result = ""; string msgType = WXMsgUtil.GetFromXML(xmlDoc, "MsgType"); switch (msgType) { case "event": switch (WXMsgUtil.GetFromXML(xmlDoc, "Event")) { case "subscribe": //订阅 break; case "unsubscribe": //取消订阅 break; case "CLICK": DataTable dtMenuMsg = MenuMsgDal.GetMenuMsg(WXMsgUtil.GetFromXML(xmlDoc, "EventKey")); if (dtMenuMsg.Rows.Count > 0) { List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>(); foreach (DataRow dr in dtMenuMsg.Rows) { Dictionary<string, string> dict = new Dictionary<string, string>(); dict["Title"] = dr["Title"].ToString(); dict["Description"] = dr["Description"].ToString(); dict["PicUrl"] = dr["PicUrl"].ToString(); dict["Url"] = dr["Url"].ToString(); dictList.Add(dict); } result = WXMsgUtil.CreateNewsMsg(xmlDoc, dictList); } else { result = WXMsgUtil.CreateTextMsg(xmlDoc, "无此消息哦"); } break; default: break; } break; case "text": string text = WXMsgUtil.GetFromXML(xmlDoc, "Content"); //if (text == "合肥" || text == "合肥天气" || text == "合肥天气预报" // || text.ToLower() == "hf" || text.ToLower() == "hefei") //{ // result = WXMsgUtil.CreateNewsMsg(xmlDoc, WeatherUtil.GetWeatherInfo()); //} //else { result = WXMsgUtil.CreateNewsMsg(xmlDoc, Weather.GetForecastInfo(text)); //result = WXMsgUtil.CreateTextMsg(xmlDoc, WXMsgUtil.GetTulingMsg(text)); } break; default: break; } if (!string.IsNullOrWhiteSpace(sAppID)) //没有AppID则不加密(订阅号没有AppID) { //加密 WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sEncryptMsg = ""; //xml格式的密文 string timestamp = context.Request["timestamp"]; string nonce = context.Request["nonce"]; int ret = wxcpt.EncryptMsg(result, timestamp, nonce, ref sEncryptMsg); if (ret != 0) { //FileLogger.WriteErrorLog(context, "加密失败,错误码:" + ret); Log.WriteDebug("加密失败,错误码:" + ret); return; } context.Response.Write(sEncryptMsg); context.Response.Flush(); } else { context.Response.Write(result); context.Response.Flush(); } }
public XDocument Init() { //解密XML信息 var postDataStr = EcryptRequestDocument.ToString(); WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId); string msgXml = null; var result = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { //验证没有通过,取消执行 CancelExcute = true; return null; } RequestDocument = XDocument.Parse(msgXml);//完成解密 RequestMessage = RequestMessageFactory.GetRequestEntity(RequestDocument); //转成实体 RequestMessageBase requestMessage = null; RequestInfoType infoType; try { infoType = InfoTypeHelper.GetRequestInfoType(RequestDocument); switch (infoType) { case RequestInfoType.component_verify_ticket: requestMessage = new RequestMessageComponentVerifyTicket(); break; case RequestInfoType.unauthorized: requestMessage = new RequestMessageUnauthorized(); break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception ex) { //此处可以记录日志 throw; } requestMessage.FillEntityWithXml(RequestDocument); RequestMessage = requestMessage; return RequestDocument; }
protected void Page_Load(object sender, EventArgs e) { //Response.Write(echostr); //公众平台上开发者设置的token, corpID, EncodingAESKey //string sToken = "QDG6eK"; string sToken = ConfigurationManager.AppSettings["wx_Token"].ToString(); //string sCorpID = "wxdb0c8553d3bf3ad5"; string sCorpID = ConfigurationManager.AppSettings["wx_CorpID"].ToString(); //string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; string sEncodingAESKey = ConfigurationManager.AppSettings["wx_EncodingAESKey"].ToString(); //string wx_corpsecret = "Mte0XxwwFPy9qbcztpE9CCsbuApg6eeSmljzghtax1H7wg2jFbSH_w3h-TbeXJjq"; string wx_corpsecret = ConfigurationManager.AppSettings["wx_corpsecret"].ToString(); string wx_agentid = ConfigurationManager.AppSettings["wx_agentid"].ToString(); if (Request["sendmsgf"] != null) { //发送微信消息 if (Request["sendmsgf"].ToString() == "test") { WebClient client = new WebClient(); //获取access_token string content = client.DownloadString("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + sCorpID + "&corpsecret=" + wx_corpsecret + ""); string access_token = content.Split(',')[0].Split(':')[1].Replace("\"", "").Replace(" ", ""); string msg_json = "{"; msg_json = msg_json + "\"touser\": \"[[UserID]]\","; //msg_json = msg_json + "\"toparty\": \"PartyID1|PartyID2\","; //msg_json = msg_json + "\"totag\": \"TagID1|TagID2\","; msg_json = msg_json + "\"msgtype\": \"text\","; msg_json = msg_json + "\"agentid\": " + wx_agentid + ","; msg_json = msg_json + "\"text\": {\"content\": \"[[MsgContent]]\"},"; msg_json = msg_json + "\"safe\":\"0\"}"; msg_json = msg_json.Replace("[[UserID]]", "gotodk"); msg_json = msg_json.Replace("[[MsgContent]]", "测试消息22"); string restr = PostWebRequest("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token, msg_json, Encoding.UTF8); Response.Write(restr); } if (Request["sendmsgf"].ToString() == "send") { WebClient client = new WebClient(); //获取access_token string content = client.DownloadString("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + sCorpID + "&corpsecret=" + wx_corpsecret + ""); string access_token = content.Split(',')[0].Split(':')[1].Replace("\"", "").Replace(" ", ""); string msg_json = "{"; msg_json = msg_json + "\"touser\": \"[[UserID]]\","; //msg_json = msg_json + "\"toparty\": \"PartyID1|PartyID2\","; //msg_json = msg_json + "\"totag\": \"TagID1|TagID2\","; msg_json = msg_json + "\"msgtype\": \"text\","; msg_json = msg_json + "\"agentid\": " + wx_agentid + ","; msg_json = msg_json + "\"text\": {\"content\": \"[[MsgContent]]\"},"; msg_json = msg_json + "\"safe\":\"0\"}"; //连接数据库,获取要发送的消息列表,获取的同时要更新成微信已发送,不管是否发送成功。 string restr = "微信消息发送结果:"; DataSet dsmsg = new DataSet(); object[] re_dsi_wx = IPC.Call("获取待发送微信消息的提醒", new object[] { "所有未发送" }); if (re_dsi_wx[0].ToString() == "ok") { //这个就是得到远程方法真正的返回值,不同类型的,自行进行强制转换即可。 dsmsg = (DataSet)(re_dsi_wx[1]); if (dsmsg.Tables["返回值单条"].Rows[0]["执行结果"].ToString() == "ok") { for (int i = 0; i < dsmsg.Tables["待发数据"].Rows.Count; i++) { string msg_json_init = msg_json; msg_json_init = msg_json_init.Replace("[[UserID]]", dsmsg.Tables["待发数据"].Rows[i]["Uloginname"].ToString()); msg_json_init = msg_json_init.Replace("[[MsgContent]]", dsmsg.Tables["待发数据"].Rows[i]["msgtitle"].ToString()); restr = restr + Environment.NewLine + "---" + PostWebRequest("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token, msg_json_init, Encoding.UTF8); } } } else { string err = "调用错误" + re_dsi_wx[1].ToString(); Response.Write(err); return; } Response.Write(restr); } } if (Request["code"] != null) { try { string code = Request["code"].ToString(); //Response.Write(code); WebClient client = new WebClient(); //获取access_token string content = client.DownloadString("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + sCorpID + "&corpsecret=" + wx_corpsecret + ""); string access_token = content.Split(',')[0].Split(':')[1].Replace("\"", "").Replace(" ", ""); //Response.Write(access_token); //client.Encoding = Encoding.UTF8; string address = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + access_token + "&code=" + code; //Response.Redirect(address); string endstr = client.DownloadString(address); Response.Write(endstr); HTMLAnalyzeClass HAC = new HTMLAnalyzeClass(); string wxusername = HAC.My_Cut_Str(endstr, "UserId\":\"", "\"", 1, false)[0].ToString(); //尝试找到对应账号和密码,如果找到,自动跳转到自动登录界面 string jm = ""; object[] re_dsi_wx = IPC.Call("获取微信自动登录参数", new object[] { wxusername }); if (re_dsi_wx[0].ToString() == "ok") { //这个就是得到远程方法真正的返回值,不同类型的,自行进行强制转换即可。 jm = re_dsi_wx[1].ToString(); } else { string err = "调用错误" + re_dsi_wx[1].ToString(); jm = ""; } //string zhanghao = wxusername; //string mima = "48d757d7d2c387c0f25d7bece01768dd"; //string jm = zhanghao+"|"+ mima; Response.Redirect("/adminht/login.aspx?aulgogo=1&aulcscs=" + jm + ""); //Response.Write(wxusername); } catch (Exception ex) { Response.Write(ex.ToString()); } } //仅用于验证 if (Request["echostr"] != null) { string msg_signature = Request["msg_signature"].ToString(); string timestamp = Request["timestamp"].ToString(); string nonce = Request["nonce"].ToString(); string echostr = Request["echostr"].ToString(); /* * ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业号会向验证url发送一个get请求 * 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及公众平台推送过来的随机加密字符串(echostr), * 这一步注意作URL解码。 * 2.验证消息体签名的正确性 * 3.解密出echostr原文,将原文当作Get请求的response,返回给公众平台 * 第2,3步可以用公众平台提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = msg_signature; //string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = timestamp; //string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = nonce; //string sVerifyNonce = "263014780"; string sVerifyEchoStr = echostr; //string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业号。 Response.Write(sEchoStr); } }