public HttpResponseMessage Get(string signature = "", string timestamp = "", string nonce = "", string echostr = "") { string querystr = string.Join("&", HttpContext.Current.Request.QueryString .AllKeys .Select(key => key + "=" + HttpContext.Current.Request.QueryString[key]).ToArray()); LogUtils.Log("[Get]:\r\n" + querystr); int ret = wxcpt.VerifyURL(signature, timestamp, nonce); if (ret != 0) { LogUtils.Log("Error: Verify failed: " + ret.ToString()); throw new WebResponseException(HttpStatusCode.InternalServerError, $"VerifyURL failed: {ret}"); } string resp_echostr = echostr; HttpResponseMessage resp = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent(resp_echostr, System.Text.Encoding.UTF8, "text/plain") }; return(resp); }
public string VerifyUrl(string id, string msg_signature, string timestamp, string nonce, string echostr) { if (!string.IsNullOrEmpty(id)) { var _config = this.GetConfig(id); string token = _config.Token; string aeskey = _config.EncodingAESKey; string corpid = _config.CropId; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, aeskey, corpid); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { return(ret.ToString()); } else { return(sEchoStr); } } else { return(""); } }
public int CheckSignature(string token, string encodingAESKey, string corpId, string signature, string timestamp, string nonce, string echostr, ref string retEchostr) { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId); int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr); return(result); }
public void valid(HttpContext context) { string sVerifyMsgSig = context.Request.QueryString["msg_signature"];//企业号的 msg_signature string sVerifyTimeStamp = context.Request.QueryString["timestamp"]; string sVerifyNonce = context.Request.QueryString["nonce"]; string sVerifyEchoStr = context.Request.QueryString["echoStr"]; int ret = 0; // int ret1 = 0; string sEchoStr = ""; // string sEchoStr1 = ""; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // WXBizMsgCrypt wxcpt1 = new WXBizMsgCrypt(sToken1, sEncodingAESKey1, sCorpID1); ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { context.Response.Write("ERR: VerifyURL fail, ret: " + ret); return; } if (!string.IsNullOrEmpty(sEchoStr)) { context.Response.Write(sEchoStr); context.Response.Flush(); //推送echostr,通过验证} } }
public string Get() { var msg_signature = Request.Query["msg_signature"]; var timestamp = Request.Query["timestamp"]; var nonce = Request.Query["nonce"]; var echostr = Request.Query["echostr"]; try { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Config["CommpanyInfo:UrlVerificationToken"], Config["CommpanyInfo:EncodingAESKey"], Config["CommpanyInfo:CorpID"]); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return(""); } return(sEchoStr); } catch { throw; } }
/// <summary> /// 验证url地址 /// </summary> /// <param name="_crypt"></param> /// <param name="_context"></param> public void VerifyURL(WXBizMsgCrypt _crypt, HttpContext _context) { string msg_signature = _context.Request.QueryString["msg_signature"]; string timestamp = _context.Request.QueryString["timestamp"]; string nonce = _context.Request.QueryString["nonce"]; string echostr = _context.Request.QueryString["echostr"]; //判断这四个参数是否为空。 if (!string.IsNullOrEmpty(echostr) && !string.IsNullOrEmpty(msg_signature) && !string.IsNullOrEmpty(nonce)) { string sReplyEchoStr = string.Empty; int result = _crypt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sReplyEchoStr); if (result == 0) { //验证成功 _context.Response.Write(sReplyEchoStr); } else { _context.Response.Write("您不是微信服务器,请您绕道前行!"); } } else { _context.Response.Write("您不是微信服务器,请您绕道前行!"); } }
static void Main(string[] args) { string sToken = "6GPQsoax9yeWXRmA4siFFeVyojAn3LY"; string sCorpID = "wwaaa6a2c1d43426a6"; string sEncodingAESKey = "jAV8dy8cM6BsAjiXsUsTZ4vpHbvKN58Q5LeVLTjgeHe"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = System.Web.HttpUtility.UrlDecode("HNYJRDpKj8Yq3wLw"); string sVerifyTimeStamp = System.Web.HttpUtility.UrlDecode("1524885497"); string sVerifyNonce = System.Web.HttpUtility.UrlDecode("c2b6ada60ed292cae21fab8d6c17da14a42f8c33"); string sVerifyEchoStr = System.Web.HttpUtility.UrlDecode("rhPpD8WyDZfAUQT%2F3Kr5b3EAApDfSncTowFNz06yB7HMGcFAwW%2BMk48U2eduOFLBJ2AW8uEuYBoANWl8LpInWA%3D%3D", Encoding.UTF8); int ret = 0; string sEchoStr = String.Empty; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); Console.WriteLine(ret); Console.WriteLine(sEchoStr); Console.Read(); } else { Console.WriteLine(sEchoStr); Console.Read(); } }
/// <summary> /// 成为开发者的第一步,验证并相应服务器的数据 企业号 /// </summary> private void AuthQY() { try { string msg_signature = HttpContext.Current.Request.QueryString["msg_signature"]; string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; string echostr = HttpContext.Current.Request.QueryString["echoStr"]; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { TracingHelper.Info("qy ERR: VerifyURL fail, ret: " + ret); return; } TracingHelper.Info("qy sEchoStrt: " + sEchoStr); HttpContext.Current.Response.Write(sEchoStr); HttpContext.Current.Response.End(); } catch (Exception ex) { TracingHelper.Error(ex, typeof(handlerTop), ex.Message); } }
public Task Get(string msg_signature, string timestamp, string nonce, string echostr) { _log.LogInformation("开始执行"); WeChatAuthInfo weChatAuthInfo = WeChatOperation.GetWeChatAuthInfo(EnumWeChatAppType.Food); WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(weChatAuthInfo.Token, weChatAuthInfo.EncodingAESKey, weChatAuthInfo.CorpId); string sVerifyMsgSig = HttpUtility.UrlDecode(msg_signature); //string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = HttpUtility.UrlDecode(timestamp); // string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = HttpUtility.UrlDecode(nonce); //string sVerifyNonce = "263014780"; string sVerifyEchoStr = HttpUtility.UrlDecode(echostr); //string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { _log.LogInformation(ret.ToString()); return(Task.CompletedTask); } _log.LogInformation(sEchoStr); Response.WriteAsync(sEchoStr); return(Task.CompletedTask); }
public HttpResponse Get([FromUri] UrldecodeModel model) { string sToken = "HON82gwUh3jIu"; string sCorpID = "wwaaa6a2c1d43426a6"; string sEncodingAESKey = "cBQP0uSzY26amPKGUjYMqoqsz7VHPU6HSOQkDGorVlM"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = HttpUtility.UrlDecode(model.msg_signature); string sVerifyTimeStamp = HttpUtility.UrlDecode(model.timestamp); string sVerifyNonce = HttpUtility.UrlDecode(model.nonce); string sVerifyEchoStr = HttpUtility.UrlDecode(model.echostr); int ret = 0; string sEchoStr = string.Empty; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(sEchoStr); HttpContext.Current.Response.End(); return(HttpContext.Current.Response); }
/// <summary> /// 验证企业号url有效性 /// </summary> /// <param name="channelId">渠道id</param> /// <param name="signature">从接收消息的URL中获取的msg_signature参数</param> /// <param name="timestamp">从接收消息的URL中获取的timestamp参数</param> /// <param name="nonce">从接收消息的URL中获取的nonce参数</param> /// <param name="echo">从接收消息的URL中获取的echostr参数。注意,此参数必须是urldecode后的值</param> /// <param name="replyEcho">解密后的明文消息内容,用于回包。注意,必须原样返回,不要做加引号或其它处理</param> /// <returns></returns> public static bool ValidateUrl(int channelId, string signature, string timestamp, string nonce, string echo, out string replyEcho) { replyEcho = string.Empty; WXBizMsgCrypt crypt = GetWXBizMsgCrypt(channelId); var result = crypt.VerifyURL(signature, timestamp, nonce, echo, ref replyEcho); return(echo.Equals(replyEcho)); }
/// <summary> /// 接入验证消息 /// </summary> /// <param name="arg"></param> /// <returns></returns> protected virtual object api_valid(LogicData arg) { SetContentType(GoResponseDataType.String); string echostr = ComFunc.nvl(arg["echostr"]); WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Weixin.Token, Weixin.EncodingAESKey, Weixin.AppID); string msg = ""; wxcpt.VerifyURL(Weixin.signature, Weixin.timestamp, Weixin.nonce, echostr, ref msg); return(msg); }
public string VerifyUrl(string msg_signature, string timestamp, string nonce, string echostr) { string token = _appConfiguration["CallBack:Token"]; string aeskey = _appConfiguration["CallBack:EncodingAESKey"]; string corpid = _appConfiguration["CallBack:CorpID"]; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, aeskey, corpid); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); return(sEchoStr); }
public void ProcessRequest(HttpContext context) { if (string.IsNullOrEmpty(context.Request.QueryString["echostr"])) { context.Response.End(); } #region --------验证URL WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WXToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = HttpUtility.UrlDecode(context.Request.QueryString["msg_signature"].ToString()); string sVerifyTimeStamp = HttpUtility.UrlDecode(context.Request.QueryString["timestamp"].ToString()); string sVerifyNonce = HttpUtility.UrlDecode(context.Request.QueryString["nonce"].ToString()); string sVerifyEchoStr = HttpUtility.UrlDecode(context.Request.QueryString["echostr"].ToString()); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); Log.WriteLog("\n" + sEchoStr); if (ret != 0) { Log.WriteLog("ERR: VerifyURL fail, ret: " + ret); return; } else { context.Response.Write(sEchoStr); context.Response.End(); } //return; #endregion if (WeiXin.CheckSignature(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, WXToken)) { try { var replyMsg = WeiXin.ReplyMsg().GetXML(); //这里可以记录日志 Log.WriteLog(replyMsg); context.Response.Write(replyMsg); } catch (Exception exp) { //记录异常 Log.WriteLog("error"); } } else { context.Response.Write(""); } }
/// <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); } //验证错误,这里可以分析具体的错误信息 return(null); }
/// <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); }
public ActionResult Index(string msg_signature, string timestamp, string nonce, string echostr) { string sReqData = StreamHelper.Read(Request.InputStream); LogService.Warn("GET解密前的数据: " + sReqData); WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(); string sEchoStr = ""; int ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { LogService.Fatal("ERR: VerifyURL fail, ret: " + ret); } return(Content(sEchoStr)); }
/// <summary> /// 用于验证URL有效性 /// </summary> /// <returns></returns> // GET: Weixin public ActionResult Callback(string corpId, int agentId, string msg_signature, string timestamp, string nonce, string echostr) { LoggerFactory.GetLogger().Debug(string.Format("&msg_signature={0}×tamp={1}&nonce={2}&echostr={3}", msg_signature, timestamp, nonce, echostr)); var token = ConfigurationManager.AppSettings[string.Format("Token-CorpId:{0}-AgentId:{1}", corpId, agentId)]; var encodingAESKey = ConfigurationManager.AppSettings[string.Format("EncodingAESKey-CorpId:{0}-AgentId:{1}", corpId, agentId)]; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { return(Content("ERR: VerifyURL fail, ret: " + ret)); } return(Content(sEchoStr)); }
/// <summary> /// 服务器验证 /// </summary> /// <param name="sTimeStamp"></param> /// <param name="sNonce"></param> /// <param name="sEchoStr"></param> /// <param name="sMsgSignature"></param> /// <returns></returns> public string CorpAuth(string sTimeStamp, string sNonce, string sEchoStr, string sMsgSignature) { string sReplyEchoStr = ""; try { int ret = 0; ret = wxcpt.VerifyURL(sMsgSignature, sTimeStamp, sNonce, sEchoStr, ref sReplyEchoStr); if (ret != 0) { log.Info(string.Format("CorpAuth failed:{0} ", ret)); } } catch (Exception e) { log.Error("CorpAuth error:" + sTimeStamp + "--" + sNonce + "--" + sEchoStr + "--" + sMsgSignature, e); } return(sReplyEchoStr); }
/// <summary> /// 企业号返回验证结果 /// </summary> /// <returns></returns> public string GetQYValidityResult() { QYValidityEntity validityEntity = Request2Entity(this._request, new QYValidityEntity()); if (validityEntity == null) { return(""); } WXQYConfigEntity qyConfig = XmlToEntity.GetQYConfig(); WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(qyConfig.Token, qyConfig.EncodingAESKey, qyConfig.CorpID); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(validityEntity.Msg_Signature, validityEntity.Timestamp, validityEntity.Nonce, validityEntity.echostr, ref sEchoStr); if (ret != 0) { //System.Console.WriteLine( "ERR: VerifyURL fail, ret: " + ret ); return(""); } return(sEchoStr); }
/// <summary> /// 验证URL /// </summary> /// <returns></returns> private string Valid() { if (wxcpt == null) { wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); } string sVerifyMsgSig = Request.QueryString["msg_signature"] == null ? "" : Request.QueryString["msg_signature"].ToString(); string sVerifyTimeStamp = Request.QueryString["timestamp"] == null ? "" : Request.QueryString["timestamp"].ToString(); string sVerifyNonce = Request.QueryString["nonce"] == null ? "" : Request.QueryString["nonce"].ToString(); string sVerifyEchoStr = Request.QueryString["echostr"] == null ? "" : Request.QueryString["echostr"].ToString(); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业号。 } return(sEchoStr); }
private string MathUrl() { string sCorpID = Request.QueryString["corpid"]; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(BonusHelper.AppConfig.sToken, BonusHelper.AppConfig.sEncodingAESKey2, sCorpID); string sVerifyMsgSig = Request.QueryString["msg_signature"]; string sVerifyTimeStamp = Request.QueryString["timestamp"]; string sVerifyNonce = Request.QueryString["nonce"]; string sVerifyEchoStr = Request.QueryString["echostr"]; 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(""); } if (!string.IsNullOrEmpty(sEchoStr)) { return(sEchoStr); } log.AppenLog("sEchoStr:" + sEchoStr); return(""); }
public void ProcessRequest(HttpContext context) { LogTxtHelper logTxtHelper = new LogTxtHelper(context.Server.MapPath(ConfigurationManager.AppSettings["logPath"].ToString())); WXBizMsgCrypt qywx = new WXBizMsgCrypt(tToken, tEncodingAESKey, tCorpID); context.Response.ContentType = "text/plain"; if (context.Request.HttpMethod.ToUpper() == "GET") { string tMsgSignature = context.Request.QueryString["msg_signature"].ToString(); string tTimeStamp = context.Request.QueryString["timestamp"].ToString(); string tNonce = context.Request.QueryString["nonce"].ToString(); string tEchoStr = context.Request.QueryString["echostr"].ToString(); string tRetEchoStr = ""; int errcode = qywx.VerifyURL(tMsgSignature, tTimeStamp, tNonce, tEchoStr, ref tRetEchoStr); if (errcode != 0) { File.WriteAllText(context.Server.MapPath("~/logs/") + "log.txt", "ErrCode:" + errcode + " - " + tRetEchoStr); } else { File.WriteAllText(context.Server.MapPath("~/logs/") + "log.txt", DateTime.Now.ToString()); context.Response.Write(tRetEchoStr); } } else if (context.Request.HttpMethod.ToUpper() == "POST") { logTxtHelper.Info("=================开始" + DateTime.Now.ToString() + "================="); Stream stream = context.Request.InputStream; logTxtHelper.Info("传入流Stream长度:"); logTxtHelper.Info(Convert.ToString(stream.Length)); byte[] streams = new byte[stream.Length]; stream.Read(streams, 0, (Int32)stream.Length); logTxtHelper.Info("读取stream到数组streams[]中"); string sReqData = Encoding.Default.GetString(streams); logTxtHelper.Info("转换streams[]为string格式:"); logTxtHelper.Info(sReqData); string sReqMsgSig = context.Request["msg_signature"]; string sReqTimeStamp = context.Request["timestamp"]; string sReqNonce = context.Request["nonce"]; string sMsg = ""; logTxtHelper.Info("相关POST参数如下:"); logTxtHelper.Info("sReqMsgSig - " + sReqMsgSig); logTxtHelper.Info("sReqTimeStamp - " + sReqTimeStamp); logTxtHelper.Info("sReqNonce - " + sReqNonce); int ret = qywx.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logTxtHelper.Info("ERR: Decrypt Fail, ret: " + ret); return; } logTxtHelper.Info("解密后密文内容:"); logTxtHelper.Info(sMsg); XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); XmlNode root = doc.FirstChild; string fromUrl = root["EventKey"].InnerText; logTxtHelper.Info("来源URL:" + fromUrl); StringBuilder sb = new StringBuilder(); sb.Append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx811b855e73c9b606&redirect_uri=http://weixin.tqlsgroup.com/sap/&response_type=code&scope=snsapi_base&state=test#wechat_redirect"); logTxtHelper.Info(sb.ToString()); logTxtHelper.Info("=================结束================="); //context.Response.Redirect(sb.ToString()); //logTxtHelper.Info("跳转后"); } }
/// <summary> /// Process the request from WeChat. /// This method can be called from inside a POST method on any Controller implementation. /// </summary> /// <param name="httpRequest">The HTTP request object, typically in a POST handler by a Controller.</param> /// <param name="httpResponse">The HTTP response object.</param> /// <param name="bot">The bot implementation.</param> /// <param name="secretInfo">The secret info provide by WeChat.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, SecretInfo secretInfo, CancellationToken cancellationToken = default(CancellationToken)) { _logger.LogInformation("Receive a new request from WeChat."); if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); } if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } if (bot == null) { throw new ArgumentNullException(nameof(bot)); } if (secretInfo == null) { throw new ArgumentNullException(nameof(secretInfo)); } if (false == string.IsNullOrEmpty(secretInfo.EchoString)) { var wXBizMsgCrypt = new WXBizMsgCrypt(_settings.Token, _settings.EncodingAesKey, _settings.CorpId); var replayEchoString = string.Empty; var code = wXBizMsgCrypt.VerifyURL(secretInfo.MessageSignature, secretInfo.Timestamp, secretInfo.Nonce, secretInfo.EchoString, ref replayEchoString); if (code != 0) { throw new UnauthorizedAccessException($"Signature verification failed. Code: {code}"); } // Return echo string when request is setting up the endpoint. if (!string.IsNullOrEmpty(replayEchoString)) { await httpResponse.WriteAsync(replayEchoString, cancellationToken).ConfigureAwait(false); return; } } // Directly return OK header to prevent WeChat from retrying. if (!_settings.PassiveResponseMode) { httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.ContentType = "text/event-stream"; await httpResponse.WriteAsync(string.Empty).ConfigureAwait(false); await httpResponse.Body.FlushAsync().ConfigureAwait(false); } try { var wechatRequest = GetRequestMessage(httpRequest.Body, secretInfo); var wechatResponse = await ProcessWeChatRequest( wechatRequest, bot.OnTurnAsync, cancellationToken).ConfigureAwait(false); // Reply WeChat(User) request have two ways, set response in http response or use background task to process the request async. if (_settings.PassiveResponseMode) { httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.ContentType = "text/xml"; var xmlString = WeChatMessageFactory.ConvertResponseToXml(wechatResponse); var response = string.Empty; var timestemp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(); var nonce = Guid.NewGuid().ToString("N"); new WXBizMsgCrypt(_settings.Token, _settings.EncodingAesKey, _settings.CorpId).EncryptMsg(xmlString, timestemp, nonce, ref response); await httpResponse.WriteAsync(response).ConfigureAwait(false); } } catch (Exception ex) { _logger.LogError(ex, "Process WeChat request failed."); throw; } }
static void Main(string[] args) { //公众平台上开发者设置的token, corpID, EncodingAESKey string sToken = "QDG6eK"; string sCorpID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); /* * 假定公众平台上开发者设置的Token * 1. 验证回调URL * 点击验证时,企业收到类似请求: * 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.先验证签名的正确性 2. 解密出echostr原文。 * 以上两步用verifyURL完成 */ //解析出url上的参数值如下: string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = "263014780"; 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); string input3 = System.Console.ReadLine(); return; } System.Console.WriteLine(sEchoStr); /* 2. 对用户回复的数据进行解密。 * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息: * POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6×tamp=1409659813&nonce=1372623149 HTTP/1.1 * Host: qy.weixin.qq.com * Content-Length: 613 * * <xml> * <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName> * <Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt> * <AgentID><![CDATA[218]]></AgentID> * </xml> */ string sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6"; string sReqTimeStamp = "1409659813"; string sReqNonce = "1372623149"; string sReqData = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>"; string sMsg = ""; //解析之后的明文 ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret); return; } System.Console.WriteLine(sMsg); /* * 3. 企业回复用户消息也需要加密和拼接xml字符串。 * 假设企业需要回复用户的消息为: * <xml> * <ToUserName><![CDATA[mycreate]]></ToUserName> * <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName> * <CreateTime>1348831860</CreateTime> * <MsgType><![CDATA[text]]></MsgType> * <Content><![CDATA[this is a test]]></Content> * <MsgId>1234567890123456</MsgId> * <AgentID>128</AgentID> * </xml> * 生成xml格式的加密消息过程为: */ string sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582测试一下中文的情况,消息长度是按字节来算的396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is这是一个中文测试 a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>"; string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); System.Console.WriteLine("sEncryptMsg"); System.Console.WriteLine(sEncryptMsg); /*测试: * 将sEncryptMsg解密看看是否是原文 * */ XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed(); doc.LoadXml(sEncryptMsg); XmlNode root = doc.FirstChild; string sig = root["MsgSignature"].InnerText; string enc = root["Encrypt"].InnerText; string timestamp = root["TimeStamp"].InnerText; string nonce = root["Nonce"].InnerText; string stmp = ""; ret = wxcpt.DecryptMsg(sig, timestamp, nonce, sEncryptMsg, ref stmp); System.Console.WriteLine("stemp"); System.Console.WriteLine(stmp + ret); return; }