public override XDocument Init(XDocument postDataDocument, object postData) { _postModel = postData as PostModel; var postDataStr = postDataDocument.ToString(); AfterDecryptData(postDataStr, _postModel); EncryptPostData = RequestMessageFactory.GetEncryptPostData(postDataStr); AfterGetData(EncryptPostData, _postModel); //解密:获得明文字符串 WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId); string msgXml = null; var result = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); /* msgXml * <xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName> * <FromUserName><![CDATA[001]]></FromUserName> * <CreateTime>1412585107</CreateTime> * <MsgType><![CDATA[text]]></MsgType> * <Content><![CDATA[你好]]></Content> * <MsgId>4299263624800632834</MsgId> * <AgentID>2</AgentID> * </xml> */ //判断result类型 if (result != 0) { //验证没有通过,取消执行 CancelExcute = true; return(null); } AfterDecryptData(msgXml, _postModel); var requestDocument = XDocument.Parse(msgXml); RequestMessage = RequestMessageFactory.GetRequestEntity(requestDocument); //记录上下文,Chat还是不记录吧,太多了 if (WeixinContextGlobal.UseWeixinContext && !(RequestMessage is RequestMessageChat)) { WeixinContext.InsertMessage(RequestMessage); } return(requestDocument); }
/// <summary> /// 初始化数据 /// </summary> /// <param name="postDataDocument"></param> /// <param name="postData"></param> /// <returns></returns> public override XDocument Init(XDocument postDataDocument, object postData = null) { //进行加密判断并处理 _postModel = postData as PostModel; var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value)) { //使用了加密 UsingEcryptMessage = true; EcryptRequestDocument = postDataDocument; 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); } if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value)) { //TODO:使用了兼容模式,进行验证即可 UsingCompatibilityModelEcryptMessage = true; } decryptDoc = XDocument.Parse(msgXml);//完成解密 } RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc); if (UsingEcryptMessage) { RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value; } //记录上下文 if (MessageContextGlobalConfig.UseMessageContext) { GlobalMessageContext.InsertMessage(RequestMessage); } return(decryptDoc); }
/// <summary> /// 用于解密从微信服务器中,发送过来的加密信息 /// </summary> /// <param name="data"></param> /// <returns></returns> public ResultReturn <string> DecryptMessage(string appId, string encryptMsg) { var config = _gateway.Get <MPConfiguration>(appId); var ret = WXBizMsgCrypt.DecryptMsg(encryptMsg, config.EncryptAESKey); if (ret.code == 0) { return(new SuccessResultReturn <string>(ret.msg)); } else { return(new FailResultReturn <string>("解密失败", ret.code)); } }
public bool Response(string msg, string sTimeStamp, string sNonce, string sMsgSignature, ref string responseMsg) { int errorCode = WxDecode.DecryptMsg(sMsgSignature, sTimeStamp, sNonce, msg, ref responseMsg); if (errorCode != 0) { string error = ErrorMessage.TranslateErrorCode(errorCode); return(false); } else { WxMessageRecXmlModel requestModec = InitMessageModel(responseMsg); return(ResponseModel(requestModec, ref responseMsg)); } }
public ActionResult Callback(string corpId, int agentId, string msg_signature, string timestamp, string nonce) { try { 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)]; //2.验证签名是否正确 if (SignHelper.Check(msg_signature, timestamp, nonce, token)) { LoggerFactory.GetLogger().Error("签名错误"); return(Content("签名错误")); } //3.获取加密消息 string postData = string.Empty; //读取post过来的xml文件流 using (StreamReader reader = new StreamReader(Request.InputStream)) { postData = reader.ReadToEnd(); reader.Close(); } string desMessage = string.Empty; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId); int decryptResult = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData, ref desMessage); if (decryptResult != 0) { return(Content("解密失败")); } //LoggerFactory.GetLogger().Error(string.Format("desMessage:{0}", desMessage)); //处理消息 var processor = new ReceiveMessageProcessor(desMessage); var response = processor.Process(); string encryptMsg; response.EncryptMessage(wxcpt, token, out encryptMsg); //LoggerFactory.GetLogger().Error(string.Format("encryptMsg:{0}", encryptMsg)); return(Content(encryptMsg)); } catch (Exception ex) { LoggerFactory.GetLogger().Error(ex, "处理消息出错了"); } return(Content("123")); }
/// <summary> /// 获得微信服务器post过来消息 /// </summary> /// <param name="_crypt"></param> /// <param name="_context"></param> /// <returns></returns> public string GetPostString(WXBizMsgCrypt _crypt, HttpContext _context) { string msg_signature = _context.Request.QueryString["msg_signature"]; string timestamp = _context.Request.QueryString["timestamp"]; string nonce = _context.Request.QueryString["nonce"]; StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream); string postString = reader.ReadToEnd(); string sMsg = string.Empty; int ret = _crypt.DecryptMsg(msg_signature, timestamp, nonce, postString, ref sMsg); if (ret != 0) { throw new WeiXinException("ERR: Decrypt fail, ret: " + ret); } return(sMsg); }
public ActionResult Index() { string signature = "6f5b6afb295b63792cb410c67037090cd3301332"; string timestamp = "1478407798"; string nonce = "277864450"; string Encrypt = "S+NEZo8UNKrJng3x/1usqmEnjDLIokcBYs3H4+HmJmSD69rqNIdYCgFIzjTkp4JKWSVGylxGWJ4GsFtaaf1nP63KqrSo2jCRfxXoGH6oMrp3LcBnYUFsQDeR4cX2aitKscxostDcAtT3gJrWKxgMmmzWvSm6yd7MW/8tRJmrXQZ8f9e6zLtrVTAndujCB8kSL1+ToQseVskqOZ85VbHb5cLh8PaGnc2myHmETvn75n2D9yNQS+rx771r7vcj6XhXRGb0x2oEbD5SBloejpu5AdTOuxGnGcEnUSLQQua99PIJbWx7bJbt3X8x/b/Coe3tEeFIeG/dj/K87n7Mg73wjDcLH9Xmhig3b7rKIEploNgDLPy5FLCZwjy/q0uAU8/xP+ev+BR6muX1HaqNeYSLL+VifSlGoxmum9+3Fcp0kP4PKQrjl06dle80lsV/0+3O2WiqdaD+XoHzKULFvSWl6Q=="; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(weixinService.token, weixinService.EncodingAESKey, weixinService.appid); int ret = 0; string sMsg = ""; ret = wxcpt.DecryptMsg(signature, timestamp, nonce, Encrypt, ref sMsg); return(View()); }
/// <summary> /// 初始化数据 /// </summary> /// <param name="postDataDocument"></param> /// <param name="postModel"></param> /// <returns></returns> public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel) { //进行加密判断并处理 _postModel = postModel as PostModel ?? new PostModel(); var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (_postModel != null && !_postModel.Token.IsNullOrWhiteSpace() && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value)) { //使用了加密 UsingEcryptMessage = true; EcryptRequestDocument = postDataDocument; 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); } if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value)) { //TODO:使用了兼容模式,进行验证即可 UsingCompatibilityModelEcryptMessage = true; } decryptDoc = XDocument.Parse(msgXml);//完成解密 } RequestMessage = RequestMessageFactory.GetRequestEntity(new TMC(), decryptDoc); if (UsingEcryptMessage) { RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value; } return(decryptDoc); //消息上下文记录将在 base.CommonInitialize() 中根据去重等条件判断后进行添加 }
public string VerifySuiteTicket(string id, string signature, string timestamp, string nonce, string stringInput) { if (!string.IsNullOrEmpty(id)) { var _config = this.GetConfig(id); if (_config != null) { string token = _config.Token; string aeskey = _config.EncodingAESKey; string corpid = _config.SuiteID; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, aeskey, corpid); string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(signature, timestamp, nonce, stringInput, ref sMsg); if (ret != 0) { return(string.Format("解析错误{0}", ret)); } _logger.Info(sMsg); var xDoc = XDocument.Parse(sMsg); var q = (from c in xDoc.Elements() select c).ToList(); var infoType = q.Elements("InfoType").First().Value; switch (infoType) { case "suite_ticket": var ComponentVerifyTicket = q.Elements("SuiteTicket").First().Value; //_logger.Info(sMsg); _cacheManager.GetCache(UserManageConsts.Third_Party_Ticket_Cache).Set(id, ComponentVerifyTicket, TimeSpan.FromMinutes(30)); //this.SetSuiteToken(corpid, _config.Secret, ComponentVerifyTicket); return("success"); case "unauthorized": return(string.Format("{0} 已取消授权", q.Elements("AuthorizerAppid").First().Value)); default: break; } } //int ret = 0; //string sEchoStr = ""; //ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); //return sEchoStr; } return("参数错误!"); }
public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel) { _postModel = postModel as PostModel ?? new PostModel(); UsingEcryptMessage = true;//Work中消息都是强制加密的 var postDataStr = postDataDocument.ToString(); EncryptPostData = RequestMessageFactory.GetEncryptPostData(postDataStr); //2、解密:获得明文字符串 WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId); string msgXml = null; var result = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); /* msgXml * <xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName> * <FromUserName><![CDATA[001]]></FromUserName> * <CreateTime>1412585107</CreateTime> * <MsgType><![CDATA[text]]></MsgType> * <Content><![CDATA[你好]]></Content> * <MsgId>4299263624800632834</MsgId> * <AgentID>2</AgentID> * </xml> */ //判断result类型 if (result != 0) { //验证没有通过,取消执行 CancelExcute = true; return(null); } var requestDocument = XDocument.Parse(msgXml); RequestMessage = RequestMessageFactory.GetRequestEntity(requestDocument); //记录上下文 if (RequestMessage.MsgType != RequestMsgType.Unknown && MessageContextGlobalConfig.UseMessageContext) { GlobalMessageContext.InsertMessage(RequestMessage); } return(requestDocument); }
private RequestMessage BuildRequest(PostUrlParameters urlParameters, Stream requestStream) { var inputData = new StreamReader(requestStream, Encoding.UTF8).ReadToEnd(); var request = inputData; if (_cryptor != null) { var decryptResult = _cryptor.DecryptMsg(urlParameters.msg_signature, urlParameters.timestamp, urlParameters.nonce, inputData, ref request); if (decryptResult != WXBizMsgCrypt.WXBizMsgCryptErrorCode.WXBizMsgCrypt_OK) { throw new MessageException($"解密失败: {decryptResult}"); } } OnRequestRead(request); return(RequestMessage.Parse(request)); }
public int DecryptContent(int tid, string msg_signature, string timestamp, string nonce, string content) { try { string token = _appConfiguration["CallBack:Token"]; string aeskey = _appConfiguration["CallBack:EncodingAESKey"]; string corpid = _appConfiguration["CallBack:CorpID"]; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, aeskey, corpid); string sMsg = ""; // 解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content, ref sMsg); var data = Converter(tid, sMsg); return(ret); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <bool> Handle(VerifyTicketPushCommand request, CancellationToken cancellationToken) { var msgCrypt = new WXBizMsgCrypt( _thirdPartyOptions.MessageVerifyToken, _thirdPartyOptions.MessageEncryptionAndDecryptionKey, _thirdPartyOptions.AppId); var xmlMessage = string.Empty; var decryptResult = msgCrypt.DecryptMsg( request.Msg_Signature, request.Timestamp, request.Nonce, request.EncryptData, ref xmlMessage); var verifyTicket = decryptResult == 0 ? xmlMessage.DeserializeXmlToObject <VerifyTicketModel>() : default; return(await _redisManager.AddAsync(EnumRedisDb.Db6, ThirdPartyConsts.CacheKeyOfVerifyTicket, verifyTicket, DateTimeOffset.Now.AddHours(10))); }
public string Handler(string requestBody, string timestamp, string nonce, string msgSignature) { string clearMessage = string.Empty; var encryptMessage = requestBody.XmlDeserialize <HandleMessageModelBase>(); if (string.IsNullOrEmpty(encryptMessage.Encrypt)) { throw new SmartWeChatException("密文为空"); } var crypt = new WXBizMsgCrypt(_options); int rtn = crypt.DecryptMsg(msgSignature, timestamp, nonce, requestBody, ref clearMessage); if (rtn != 0) { throw new SmartWeChatException("解密失败"); } return(Handler(clearMessage)); }
public static XDocument Init(PostModel postModel, XDocument postDataDocument) { //进行加密判断并处理 var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value)) { 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); if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value)) { } decryptDoc = XDocument.Parse(msgXml);//完成解密 } return decryptDoc; }
public string post(string name) { var msg_signature = Request.Query["msg_signature"]; var timestamp = Request.Query["timestamp"]; var nonce = Request.Query["nonce"]; try { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Config["CommpanyInfo:UrlVerificationToken"], Config["CommpanyInfo:EncodingAESKey"], Config["CommpanyInfo:CorpID"]); string msg = null; System.IO.StreamReader sr = new System.IO.StreamReader(Request.Body); var sPostData = sr.ReadToEnd(); sr.Close(); wxcpt.DecryptMsg(msg_signature, timestamp, nonce, sPostData, ref msg); PassiveMessage pm = new PassiveMessage(msg, timestamp, nonce, wxcpt); return(pm.GetXml()); } catch { throw; } }
/// <summary> /// 解密消息 /// </summary> /// <returns>返回解密之后的消息</returns> private string DecryptMessage(string content) { string msg = ""; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); XmlNode root = doc.FirstChild; string userName = root["ToUserName"].InnerText; AccountInfo account = AccountInfoCollection.GetAccountInfo(userName); if (account == null) { return(msg); } WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(account.Token, account.EncodingAESKey, account.AppId); string msg_signature = RequestEx.TryGetQueryString("msg_signature", "", request); string timestamp = RequestEx.TryGetQueryString("timestamp", "", request); string nonce = RequestEx.TryGetQueryString("nonce", "", request); wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content, ref msg); return(msg); }
public ActionResult Index(string msg_signature, string timestamp, string nonce) { string sReqData = StreamHelper.Read(Request.InputStream); WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(); string sMsg = ""; int ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, sReqData, ref sMsg); if (ret != 0) { LogService.Fatal("ERR: VerifyURL fail, ret: " + ret); } //LogService.Fatal("解密后的数据: " + sMsg); XDocument doc = XmlHelper.LoadXML(sMsg); RequestMsgType msgType = MsgTypeHelper.GetRequestMsgType(doc); switch (msgType) { case RequestMsgType.Event: RequestEventMessage message = (RequestEventMessage)XmlHelper.Deserialize <RequestEventMessage>(sMsg); //成员关注、取消关注企业号的事件 if (message != null && message.Event == "subscribe" || message.Event == "unsubscribe") { var userId = message.FromUserName; //关注状态: 1=已关注,2=已冻结,4=未关注 int status = message.Event == "subscribe" ? 1 : 4; int rows = EmployeeService.UpdateEmpStatus(userId, (byte)status); //LogService.Fatal("修改结果: " + rows); } break; } return(Content(sMsg)); }
public static XDocument Init(Stream inputStream, PostModel postModel) { XDocument edocument = XmlUtility.Convert(inputStream); if (postModel != null && edocument != null && edocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(edocument.Root.Element("Encrypt").Value)) { //解密XML信息 string postDataStr = edocument.ToString(); WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(postModel.Token, postModel.EncodingAESKey, postModel.AppId); string msgXml = null; int result = msgCrype.DecryptMsg(postModel.Msg_Signature, postModel.Timestamp, postModel.Nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { return null; } return XDocument.Parse(msgXml);//完成解密 } return edocument; }
/// <summary> /// 业务处理 /// </summary> /// <param name="postString"></param> private void Execute(string postString) { postString = @"<xml><ToUserName><![CDATA[wx74bb1fb7abf4b203]]></ToUserName> <Encrypt><![CDATA[mhY8AsexiiDpA7ilrwFrtDCY/opCpidX2eanBnPn/vZ0d4ck43K6+i2q7J7rdE+l78B44gwp/mr2YWGc4sSRyAPVq9hBoMT1Z9t9UgK3y94jQ1dfvi74b5zdKaAgPCg2xS5LwFJRgzUVuHNTsXkwh36Q90GhWArq6gRmX/K5RDDC24bqIqty4TVWcsf9kfCmSsjcG4BU5aXG2h/EYK5ErGkSHi5qsb650bZBPE68TnkQDbk/uvhKNJmRYj/rVMHX6wWHkjYy4KoHJGAWH8NWVvfKE8T9bJg0ku4bH6q+VKqi1tCTarR26pyzPpmvEqARILhqyNO1y/IJfx/bkjyhqtZvTZnjAdz827EvC2XcJkzGppkZdzbpNoILD93J4ty9S/SLBkj6TEhmKNXZssY3TrhJut6D6eOAcCIHJA4Vty0OjwIDuS8JPACORQUf+lh222pAnBeH3eoaq2EuIV35SA==]]></Encrypt> <AgentID><![CDATA[0]]></AgentID> </xml>"; //1.检验access_token new qyGetIp_list().Execute("qy"); TracingHelper.Info("qy检验access_token完毕"); string sMsg = ""; #region //2.AES解密 try { int ret = 0; ret = wxcpt.DecryptMsg(postString, ref sMsg); if (ret != 0) { System.Console.WriteLine("qy ERR: Decrypt Fail, ret: " + ret); return; } } catch (Exception ex) { TracingHelper.Error(ex, typeof(handlerTop), "qy 消息解密 : " + ex.Message); } #endregion //2.业务处理 qyService qy = new qyService(); string responseContent = qy.Execute(sMsg); TracingHelper.Info("qy业务处理完毕 " + responseContent); //3.返回微信服务器 HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); }
/// <summary> /// 解密信息 /// </summary> /// <param name="sMsgSignature"></param> /// <param name="sTimeStamp"></param> /// <param name="sNonce"></param> /// <param name="postStr"></param> /// <returns></returns> private string DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string postStr) { string strReuslt = postStr; try { if (isDES) { int ret = 0; ret = wxcpt.DecryptMsg(sMsgSignature, sTimeStamp, sNonce, postStr, ref strReuslt); log.Debug("CorpCore DecryptMsg Msg:" + strReuslt); if (ret != 0) { log.Info("CorpCore DecryptMsg failed"); } } return(strReuslt); } catch (Exception e) { log.Error("CorpCore DecryptMsg:", e); return(strReuslt); } }
private static XDocument Init(XDocument postDataDocument, PostModel _postModel) { //进行加密判断并处理 var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (postDataDocument.Root == null || (_postModel == null || postDataDocument.Root.Element("Encrypt") == null || string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt")?.Value)) ) { return(decryptDoc); } //使用了加密 string sToken = Config.ServerToken; string sAppID = Config.ServerAppID; string sEncodingAESKey = Config.ServerEncodingAESKey; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string msgXml = null; var result = wxcpt.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { //验证没有通过,取消执行 return(null); } decryptDoc = XDocument.Parse(msgXml);//完成解密 return(decryptDoc); }
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); }
static void Main(string[] args) { //string xmlData = "<xml><ToUserName><![CDATA[wwaaa6a2c1d43426a6]]></ToUserName><FromUserName><![CDATA[wenfeng.huang]]></FromUserName><CreateTime>1525662954</CreateTime><MsgType><![CDATA[event]]></MsgType><AgentID>1000005</AgentID><Event><![CDATA[click]]></Event><EventKey><![CDATA[Punch]]></EventKey></xml>"; //XmlDocument doc = new XmlDocument(); //doc.LoadXml(xmlData); //XmlNode root = doc.DocumentElement; //string UserID = root.SelectSingleNode("FromUserName").InnerText; //string CorpID = root.SelectSingleNode("ToUserName").InnerText; //Console.Write("FromUserName:"******"\nToUserName:"******"95f1f2a9de82ddde4b362787cba0a0e20bb9dd06"; string timestamp = "1525672167"; string nonce = "1524697125"; string sToken = "HON82gwUh3jIu"; string sCorpID = "wwaaa6a2c1d43426a6"; string sEncodingAESKey = "cBQP0uSzY26amPKGUjYMqoqsz7VHPU6HSOQkDGorVlM"; string en = "<xml><Encrypt><![CDATA[zLN3B+L7srIeHg5v8Q8w0RCqafmpHXLzWFn4OSozjGegiF2ndbkZbvZFbjvE1cGIEfw0n7mNULDPPKxWCTH11c+uKbCZLFnhEA1hzs/uL1OlboBZXy1kvVW5egOC/QMZF5SNqjh5lQHDollGdPTfzQfCzpvu940EAgAveF/nuEs=]]></Encrypt><MsgSignature><![CDATA[95f1f2a9de82ddde4b362787cba0a0e20bb9dd06]]></MsgSignature><TimeStamp><![CDATA[1525672167]]></TimeStamp><Nonce><![CDATA[1524697125]]></Nonce></xml>"; WXBizMsgCrypt wxcp = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string xmldata = string.Empty; wxcp.DecryptMsg(msg, timestamp, nonce, en, ref xmldata); Console.Write("xmldata:" + xmldata); Console.Read(); }
public ActionResult Post(PostModel postModel) { postModel.Token = WeixinConfig.Token; //postModel.EncodingAESKey = WeixinConfig.EncodingAESKey; postModel.AppId = WeixinConfig.AppID; var ent = ""; if (!BasicAPI.CheckSignature(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinConfig.Token, out ent)) { return(Content("参数错误!")); } var encryptMsg = string.Empty; 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, postModel.Timestamp, postModel.Nonce, msg, ref decryptMsg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 Log.Instence.LogWriteLine(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); #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, postModel.Timestamp, postModel.Nonce, ref encryptMsg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 Log.Instence.LogWriteLine(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="postDataDocument"></param> /// <param name="postData"></param> /// <returns></returns> public override XDocument Init(XDocument postDataDocument, object postData = null) { //进行加密判断并处理 _postModel = postData as PostModel; var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value)) { //使用了加密 UsingEcryptMessage = true; EcryptRequestDocument = postDataDocument; 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); } if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value)) { //TODO:使用了兼容模式,进行验证即可 UsingCompatibilityModelEcryptMessage = true; } decryptDoc = XDocument.Parse(msgXml);//完成解密 } RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc); if (UsingEcryptMessage) { RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value; } //TODO:分布式系统中本地的上下文会有同步问题,需要同步使用远程的储存 if (MessageContextGlobalConfig.UseMessageContext) { var omit = OmitRepeatedMessageFunc == null || OmitRepeatedMessageFunc(RequestMessage); lock (MessageContextGlobalConfig.OmitRepeatLock)//TODO:使用分布式锁 { #region 消息去重 if (omit && OmitRepeatedMessage && CurrentMessageContext.RequestMessages.Count > 0 //&& !(RequestMessage is RequestMessageEvent_Merchant_Order)批量订单的MsgId可能会相同 ) { //lastMessage必定有值(除非极端小的过期时间条件下,几乎不可能发生) var lastMessage = CurrentMessageContext.RequestMessages[CurrentMessageContext.RequestMessages.Count - 1]; if ( //使用MsgId去重 (lastMessage.MsgId != 0 && lastMessage.MsgId == RequestMessage.MsgId) || //使用CreateTime去重(OpenId对象已经是同一个) (lastMessage.MsgId == RequestMessage.MsgId && lastMessage.CreateTime == RequestMessage.CreateTime && lastMessage.MsgType == RequestMessage.MsgType) ) { MarkRepeatedMessage();//标记为已重复 } //判断特殊事件 if (!MessageIsRepeated && lastMessage is RequestMessageEventBase && RequestMessage is RequestMessageEventBase && (lastMessage as RequestMessageEventBase).Event == (RequestMessage as RequestMessageEventBase).Event ) { var lastEventMessage = lastMessage as RequestMessageEventBase; var currentEventMessage = RequestMessage as RequestMessageEventBase; switch (lastEventMessage.Event) { case Event.user_get_card: //领取事件推送 //文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025274 //问题反馈:https://github.com/JeffreySu/WeiXinMPSDK/issues/1106 var lastGetUserCardMessage = lastMessage as RequestMessageEvent_User_Get_Card; var currentGetUserCardMessage = RequestMessage as RequestMessageEvent_User_Get_Card; if (lastGetUserCardMessage.UserCardCode == currentGetUserCardMessage.UserCardCode && lastGetUserCardMessage.CardId == currentGetUserCardMessage.CardId) { MarkRepeatedMessage(); //标记为已重复 } break; default: break; } } } #endregion //在消息没有被去重的情况下记录上下文 if (!MessageIsRepeated) { GlobalMessageContext.InsertMessage(RequestMessage); } } } return(decryptDoc); }
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("跳转后"); } }
private void ResponseRequest(HttpContext context) { string sToken = "Token"; string sAppID = WebConfigurationManager.AppSettings["MASTERAPPID"]; string sEncodingAESKey = "ybusoyOcAwO9VlO16VY8eeE5pZWsfcrTr8vtOJeqRvj"; //WXBizMsgCrypt 这个类是腾讯提供的,下载地址是http://mp.weixin.qq.com/wiki/static/assets/a5a22f38cb60228cb32ab61d9e4c414b.zip //这里的构造函数我自己改写了,腾讯提供的构造函数需要提供三个参数的,具体请看微信提供的示例代码 WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sReqMsgSig = HttpContext.Current.Request.QueryString["msg_signature"]; string sReqTimeStamp = HttpContext.Current.Request.QueryString["timestamp"]; string sReqNonce = HttpContext.Current.Request.QueryString["nonce"]; string sReqData = GetPost(); //sReqMsgSig = "8e62a1c86769320cf82dc9f01e947b904db4c6ac"; //sReqTimeStamp = "1562813744"; //sReqNonce = "129684983"; //sReqData = "<xml>< AppId >< ![CDATA[wx77e59ec1c4a582e7]] ></ AppId >< Encrypt >< ![CDATA[CBI8yD8tbfgO8aFytLuyU / 1x + SK87QNwPFVGnebG + ZuZLynxwHlGbl49JxpiYkg5cK883EPfQkpEYChOhSLMP1DMI4T6F5NB9mmNtHtsyjeL93unOSBg26YlfHKjJI9juiB4WCQlcpYZdLNoAyaXYY + oczriNbdPKcYqBCmngzdWNOf2modI + MrGoNZqaLsJuP / A3GeoyHMEiBeJ4rB / 7bxEM + idXzjjGXn5ss4LAlCuzSR / SFBveu0jsKwiWHW / urFM8Afa6NMP6lG4h1M + B9DA3L9f7hD + BpAvL5s61unTiO27GqQONM8zfgH85YJqU44Dl1kIs4i8pdQOK7TK0g ==]] ></ Encrypt ></ xml > "; string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { } else { var xDoc = XDocument.Parse(sMsg); List <XElement> q = (from c in xDoc.Elements() select c).ToList(); var infoType = q.Elements("InfoType").First().Value; switch (infoType) { case "component_verify_ticket": var ticket = q.Elements("ComponentVerifyTicket").First().Value; HttpContext.Current.Response.Write("success"); ticket = ticket.Replace("ticket@@@", ""); //这里就是component_verify_ticket的值,保存起来就可以了,处理完成后在页面上输出success,通知微信服务器已经接收到ticket string data = "{\"component_appid\":\"" + WebConfigurationManager.AppSettings["MASTERAPPID"] + "\",\"component_appsecret\":\"" + WebConfigurationManager.AppSettings["MASTERSECRET"] + "\",\"component_verify_ticket\":\"" + ticket + "\"}"; var result = HttpClientHelper.PostResponse("https://api.weixin.qq.com/cgi-bin/component/api_component_token", data); JObject outputObj = JObject.Parse(result); var accesstoken = outputObj["component_access_token"].ToString(); SetCache("token", accesstoken, DateTime.Now.AddHours(2), System.Web.Caching.Cache.NoSlidingExpiration); //data = "{\"component_appid\":\"" + WebConfigurationManager.AppSettings["MASTERAPPID"] + "\"}"; //获取预授权码 //result = HttpClientHelper.PostResponse("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + accesstoken,data); //JObject authcode = JObject.Parse(result); //var code = authcode["pre_auth_code"].ToString(); //code = code.Replace("preauthcode@@@", ""); //data = "{\"component_appid\":\"" + WebConfigurationManager.AppSettings["MASTERAPPID"] + "\",\"authorization_code\":\"" + code + "\"}"; //获取接口调用凭据和授权信息 //result = HttpClientHelper.PostResponse("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + accesstoken, data); HttpContext.Current.Response.End(); break; case "unauthorized": //当用户取消授权的时候,微信服务器也会向这个页面发送信息,在这里做一下记录 HttpContext.Current.Response.End(); break; default: break; } } }
static void Main(string[] args) { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); /* 1. 对用户回复的数据进行解密。 * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息: * 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> </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></xml>"; string sMsg = ""; //解析之后的明文 int ret = 0; 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); /* * 2. 企业回复用户消息也需要加密和拼接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> * </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></xml>"; string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); System.Console.WriteLine("sEncryptMsg"); System.Console.WriteLine(sEncryptMsg); /*测试: * 将sEncryptMsg解密看看是否是原文 * */ XmlDocument doc = new XmlDocument(); 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; }
public void ProcessRequest(HttpContext context) { //添加自定义token string sToken = ""; //string sAppID = HttpContext.Current.Request.QueryString["appId"]; //sAppID = sAppID.Replace("/",""); string sAppID = WebConfigurationManager.AppSettings["MASTERAPPID"]; //添加43位预设密钥 string sEncodingAESKey = ""; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); //获取interfacetest页面的accesstoken var accesstoken = GetCache("token"); string sReqData = GetPost(); string respnseContent = ""; string sResponse = ""; //加密之后的回复文本 string sReqMsgSig = HttpContext.Current.Request.QueryString["msg_signature"]; string sReqTimeStamp = HttpContext.Current.Request.QueryString["timestamp"]; string sReqNonce = HttpContext.Current.Request.QueryString["nonce"]; string openid = HttpContext.Current.Request.QueryString["openid"]; string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); var xDoc = XDocument.Parse(sMsg); List <XElement> q = (from c in xDoc.Elements() select c).ToList(); var model = new { ToUserName = q.Elements("ToUserName").First().Value, FromUserName = q.Elements("FromUserName").First().Value, CreateTime = q.Elements("CreateTime").First().Value, MsgType = q.Elements("MsgType").First().Value, Content = ("" + q.Elements("Content").First().Value).Trim(), MsgId = q.Elements("MsgId").First().Value }; if (false == string.IsNullOrEmpty(model.Content)) { var textTpl = "<xml>" + "<ToUserName><![CDATA[{0}]]></ToUserName>" + "<FromUserName><![CDATA[{1}]]></FromUserName>" + "<CreateTime>{2}</CreateTime>" + "<MsgType><![CDATA[{3}]]></MsgType>" + "<Content><![CDATA[{4}]]></Content>" + "</xml>"; if (model.Content == "TESTCOMPONENT_MSG_TYPE_TEXT") { //回复普通消息 respnseContent = "TESTCOMPONENT_MSG_TYPE_TEXT_callback"; int enRet = wxcpt.EncryptMsg(string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", respnseContent), sReqTimeStamp, sReqNonce, ref sResponse); //sResponse = string.Format(textTpl, model.ToUserName, model.FromUserName, ConvertDateTimeInt(DateTime.Now), "text", respnseContent); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(sResponse); HttpContext.Current.Response.End(); } else { //回复API消息 HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(string.Empty);//回复空字符串 var auth = model.Content; auth = auth.Replace("QUERY_AUTH_CODE:queryauthcode@@@", ""); string data = "{\"component_appid\":\"" + WebConfigurationManager.AppSettings["MASTERAPPID"] + "\",\"authorization_code\":\"" + auth + "\"}"; var result = HttpClientHelper.PostResponse("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + accesstoken, data); JObject outputObj = JObject.Parse(result); var token = outputObj["authorization_info"]["authorizer_access_token"].ToString(); respnseContent = model.Content.Replace("QUERY_AUTH_CODE:", "") + "_from_api"; var data2 = "{\"touser\":\"" + openid + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + respnseContent + "\"}}"; var result2 = HttpClientHelper.PostResponse("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token, data2); HttpContext.Current.Response.End(); } } }
static void Main(string[] args) { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); /* 1. 对用户回复的数据进行解密。 * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息: * 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> * </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></xml>"; string sMsg = ""; //解析之后的明文 int ret = 0; 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); /* * 2. 企业回复用户消息也需要加密和拼接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> * </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></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; }