public static RequestMessage DeSerialize(Stream stream, string encrypttype, PublicAccount pi) { XmlDocument x = new XmlDocument(); x.Load(stream); logger.Trace("sourceXml"); logger.Trace(x.OuterXml); if (encrypttype == "raw") {//明文模式 直接反序列化 return DeSerialize(x.OuterXml); } else if (encrypttype == "aes") { using (StringReader sr = new StringReader(x.OuterXml)) { using (XmlReader xr = XmlReader.Create(sr)) { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(RequestMessage)); RequestMessage rm = xs.Deserialize(xr) as RequestMessage; MessageCryptor mc = new MessageCryptor(pi.MessageToken, pi.EncryptionKey, pi.AppId); string emessage = mc.Decrypt(rm.Encrypt); return DeSerialize(emessage); } } } else { throw new NotSupportedException(); } }
/// <summary> /// 同步消息处理 /// </summary> /// <param name="stream"></param> /// <returns></returns> public string ProcessRequest(string url, string HttpMethod, Stream stream) { if (!Inited) throw new WxException("MessageCenter 尚未注册监听器 无法处理消息"); if (SdkSetup.MessageTokenGetter == null) throw new ArgumentNullException("TokenGetter"); var urlParmteres = QueryString(url); PublicAccount pi = SdkSetup.MessageTokenGetter(urlParmteres); string token = pi.MessageToken; if (HttpMethod == "GET") { return GetValidate(urlParmteres, token); } else if (HttpMethod == "POST") { if (!PostValidate(urlParmteres, token)) { throw new WxException("Token错误"); } } else { throw new HttpException((int)System.Net.HttpStatusCode.MethodNotAllowed, "不支持的Http请求方式"); } string encrypttype = urlParmteres["encrypt_type"]; encrypttype = string.IsNullOrEmpty(encrypttype) ? "raw" : encrypttype.ToLower(); RequestMessage req = MessageSerializer.DeSerialize(stream, encrypttype, pi); IMessageListener listener = Activator.CreateInstance(ListererType) as IMessageListener; ResponseMessage rsp = null; try { rsp = listener.ProcessRequest(req); } catch (Exception e) { logger.Error(e); throw; } if (rsp == null) return string.Empty; listener.Dispose(); string rexml = rsp.ToXml(); if (encrypttype == "aes") { string timestamp = urlParmteres["timestamp"]; string nonce = urlParmteres["nonce"]; MessageCryptor mc = new MessageCryptor(pi.MessageToken, pi.EncryptionKey, pi.AppId); rexml = mc.Encrypt(rexml, timestamp, nonce); } return rexml; }