/// <summary> /// 服务器接入验证 /// </summary> /// <returns></returns> public static StrResp CheckServerValid(WechatMsgConfig appConfig, WechatRequestPara reqBody) { var checkSignRes = WechatChatHelper.CheckSignature(appConfig.Token, reqBody.signature, reqBody.timestamp, reqBody.nonce, string.Empty); var resultRes = new StrResp().WithResp(checkSignRes); resultRes.data = resultRes.IsSuccess() ? reqBody.echostr : string.Empty; return(resultRes); }
/// <summary> /// 消息处理入口 /// </summary> /// <param name="appConfig"></param> /// <param name="reqBody">请求参数信息</param> /// <returns>消息结果,Data为响应微信数据,如果出错Message为错误信息</returns> public async Task <StrResp> Process(WechatMsgConfig appConfig, WechatRequestPara reqBody) { if (string.IsNullOrEmpty(reqBody.signature) || string.IsNullOrEmpty(reqBody.timestamp) || string.IsNullOrEmpty(reqBody.nonce) || appConfig == null) { return(new StrResp().WithResp(RespTypes.ParaError, "消息相关参数错误!")); } // 一. 检查是否是微信服务端首次地址Get请求验证 if (!string.IsNullOrEmpty(reqBody.echostr)) { return(CheckServerValid(appConfig, reqBody)); } if (string.IsNullOrEmpty(reqBody.body)) { return(new StrResp().WithResp(RespTypes.ParaError, "消息相关参数错误!")); } var checkRes = Prepare(appConfig, reqBody); if (!checkRes.IsSuccess()) { return(new StrResp().WithResp(checkRes)); } var contextRes = await Processing(appConfig.AppId, checkRes.data); if (!contextRes.IsSuccess()) { return(new StrResp().WithResp(contextRes)); } var resultString = contextRes.data.ReplyMsg.ToReplyXml(); if (appConfig.SecurityType != WechatSecurityType.None && !string.IsNullOrEmpty(contextRes.data.ReplyMsg.MsgType)) { return(WechatChatHelper.EncryptMsg(resultString, appConfig)); } return(new StrResp(resultString)); }
/// <summary> /// 核心执行 过程的 验签和解密 /// </summary> /// <returns>验证结果及相应的消息内容体 (如果加密模式,返回的是解密后的明文)</returns> private static StrResp Prepare(WechatMsgConfig appConfig, WechatRequestPara reqBody) { var isEncryptMsg = appConfig.SecurityType == WechatSecurityType.Safe; if (!isEncryptMsg) { var resCheck = WechatChatHelper.CheckSignature(appConfig.Token, reqBody.signature, reqBody.timestamp, reqBody.nonce, string.Empty); return(!resCheck.IsSuccess() ? new StrResp().WithResp(resCheck) : new StrResp(reqBody.body)); } if (string.IsNullOrEmpty(reqBody.msg_signature)) { return(new StrResp().WithResp(RespTypes.ParaError, "msg_signature 消息体验证签名参数为空!")); } var xmlDoc = WechatChatHelper.GetXmlDocment(reqBody.body); var encryStr = xmlDoc?.FirstChild["Encrypt"]?.InnerText; if (string.IsNullOrEmpty(encryStr)) { return(new StrResp().WithResp(RespTypes.OperateObjectNull, "安全接口的加密字段为空!")); } var cryptMsgCheck = WechatChatHelper.CheckSignature(appConfig.Token, reqBody.msg_signature, reqBody.timestamp, reqBody.nonce, encryStr); if (!cryptMsgCheck.IsSuccess()) { return(new StrResp().WithResp(cryptMsgCheck)); } var recMsgXml = Cryptography.AESDecrypt(encryStr, appConfig.EncodingAesKey); return(new StrResp(recMsgXml)); }