public void Proccess(IWeChatMsgToken token, string appid) { var xmlMsg = string.Empty; var crypt = new WXBizMsgCrypt(token, appid); var rtnVal = crypt.DecryptMsg(token, ref xmlMsg); if (rtnVal == 0) { Logger.InfoFormat("result:{0}", xmlMsg); var document = new XmlDocument(); document.LoadXml(xmlMsg); if (Enum.TryParse(document.SelectSingleNode("/xml/MsgType").InnerText, out WeChatMsgTypes msgType)) { using (var reader = new StringReader(xmlMsg)) { if (Enum.TryParse(document.SelectSingleNode("/xml/Event").InnerText, true, out WeChatEventTypes eventtype) == false) { eventtype = WeChatEventTypes.Nothing; } var message = xmlMsg.DeserializeFromXml(dictnoary[eventtype]) as IWeChatMsg; var invoking = GenernateWeChatProccesor(message); invoking(message, appid); } } } else { Logger.InfoFormat("解密错误:{0}", rtnVal); } }
//构造函数 // @param sToken: 公众平台上,开发者设置的Token // @param sEncodingAESKey: 公众平台上,开发者设置的EncodingAESKey // @param sAppID: 公众帐号的appid public WXBizMsgCrypt(IWeChatMsgToken token, string appid = "") { this.token = token; this.AppId = appid; //m_sToken = token.BizMsgToken; //m_sAppID = token.AppId; //m_sEncodingAESKey = token.EncodingAESKey; }
// 检验消息的真实性,并且获取解密后的明文 // @param sMsgSignature: 签名串,对应URL参数的msg_signature // @param sTimeStamp: 时间戳,对应URL参数的timestamp // @param sNonce: 随机串,对应URL参数的nonce // @param sPostData: 密文,对应POST请求的数据 // @param sMsg: 解密后的原文,当return返回0时有效 // @return: 成功0,失败返回对应的错误码 public int DecryptMsg(IWeChatMsgToken token, ref string sMsg) { if (token.EncodingAESKey.Length != 43) { return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey); } XmlDocument doc = new XmlDocument(); XmlNode root; string sEncryptMsg; try { doc.LoadXml(token.ReqMsg); root = doc.FirstChild; sEncryptMsg = root["Encrypt"].InnerText; } catch (Exception ex) { return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error); } //verify signature int ret = 0; ret = VerifySignature(token.BizMsgToken, token.TimeStamp, token.Nonce, sEncryptMsg, token.Signature); if (ret != 0) { return(ret); } //decrypt string cpid = ""; try { sMsg = Cryptography.AES_decrypt(sEncryptMsg, token.EncodingAESKey, ref cpid); } catch (FormatException) { return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error); } catch (Exception) { return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error); } //// P1 需要验证appid 是否在平台 appid中 //if (token.AppIds.Any(id => id.Equals(cpid)) == false) // return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateAppid_Error; //token.CurrentAppId = cpid; return(0); }