public EncryptMsg ( string sReplyMsg, string sTimeStamp, string sNonce, string &sEncryptMsg ) : int | ||
sReplyMsg | string | |
sTimeStamp | string | |
sNonce | string | |
sEncryptMsg | string | |
return | int |
/// <summary> /// 加密消息 /// </summary> /// <param name="token"></param> /// <param name="encodingAESKey"></param> /// <param name="corpId"></param> /// <param name="replyMsg"></param> /// <param name="timeStamp"></param> /// <param name="nonce"></param> /// <returns></returns> public static string EncryptMsg(string token, string encodingAESKey, string corpId, string replyMsg, string timeStamp, string nonce) { WXBizMsgCrypt crypt = new WXBizMsgCrypt(token, encodingAESKey, corpId); string encryptMsg = null; var result = crypt.EncryptMsg(replyMsg, timeStamp, nonce, ref encryptMsg); return encryptMsg; }
public ActionResult Post(string signature, string timestamp, string nonce, string echostr) { 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, timestamp, nonce, msg, ref decryptMsg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 //注意:本demo用log4net记录此信息,你可以用其他方法 LogWriter.Default.WriteError(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); var encryptMsg = string.Empty; #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, timestamp, nonce, ref encryptMsg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 LogWriter.Default.WriteError(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="appId"></param> /// <param name="sReplyMsg">企业号待回复用户的消息,xml格式的字符串</param> /// <param name="sTimeStamp">时间戳,可以自己生成,也可以用URL参数的timestamp</param> /// <param name="sNonce">随机串,可以自己生成,也可以用URL参数的nonce</param> /// <param name="sEncryptMsg">加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,</param> /// <returns>成功0,失败返回对应的错误码</returns> public static int EncryptMsg(string appId, string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg) { string sToken = "sewapower"; string sAppID = appId; string sEncodingAESKey = "Sd8AFrmKTlF2u5jbQl8vQEYJX57aALEz1OivuIUgD3r"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); return(wxcpt.EncryptMsg(sReplyMsg, sTimeStamp, sNonce, ref sEncryptMsg)); }
/// <summary> /// 调用。 /// </summary> /// <param name="context">处理上下文。</param> /// <returns>任务。</returns> public override Task Invoke(IHandlerContext context) { var responseMessage = context.GetResponseMessage(); if (responseMessage == null) { context.ResponseXml = string.Empty; } else { var requestMessage = context.GetRequestMessage(); //基本信息初始化。 responseMessage.CreateTime = DateTime.Now; responseMessage.FromUserName = requestMessage.ToUserName; responseMessage.ToUserName = requestMessage.FromUserName; var dependencyResolver = context.GetDependencyResolver(); var responseMessageFactory = dependencyResolver.GetService<IResponseMessageFactory>(); var content = responseMessageFactory.GetXmlByReponseMessage(responseMessage); #region Encrypt if (!string.IsNullOrWhiteSpace(content)) { var request = context.Request; var encryptType = request.QueryString["encrypt_type"]; if (encryptType != null) { var nonce = request.QueryString["nonce"]; var timestamp = request.QueryString["timestamp"]; var baseInfo = context.GetMessageHandlerBaseInfo(); var appId = baseInfo.AppId; var encodingAesKey = baseInfo.EncodingAesKey; var token = baseInfo.Token; var wxBizMsgCrypt = new WXBizMsgCrypt(token, encodingAesKey, appId); wxBizMsgCrypt.EncryptMsg(content, timestamp, nonce, ref content); } } #endregion Encrypt context.ResponseXml = content; } return Next.Invoke(context); }
/// <summary> /// 微信后台消息POST处理函数 /// </summary> /// <param name="id">微信公众号ID,系统可以托管多个公众号,用于区分各个公众号</param> /// <param name="msg_signature">微信后台发过来的签名参数,用于验证是否是微信服务器发的消息</param> /// <param name="timestamp">微信后台发过来的签名参数,用于验证是否是微信服务器发的消息</param> /// <param name="nonce">微信后台发过来的签名参数,用于验证是否是微信服务器发的消息</param> /// <param name="msg">微信POST请求中的消息主体内容,后台会自动用XMLFORMATER反序列化</param> /// <returns></returns> public HttpResponseMessage Post(string id, string msg_signature, string timestamp, string nonce) { try { var wx = WXManager.Current[id]; if (wx != null) { var wxcpt = new Tencent.WXBizMsgCrypt(wx.Token, wx.EncodingAESKey, wx.AppID); var content = Request.Content.ReadAsStringAsync().Result; string xml = ""; // 解析之后的明文 var ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content, ref xml); if (ret == 0) { var stream = new StringReader(xml); WXRequestMsg msg = new XmlSerializer(typeof(WXRequestMsg)).Deserialize(stream) as WXRequestMsg; if (msg != null) { var res = new WXRequestHandler(this.Request).HandleMsg(id, msg); if (res != null) { var response = Request.CreateResponse(); string sRespData = res.ToXML(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, timestamp, nonce, ref sEncryptMsg); if (ret == 0) { response.Content = new StringContent(sEncryptMsg); return(response); } } } } } } catch (Exception ex) { } return(Request.CreateResponse()); }
public void responseMsg(HttpContext context, XmlDocument xmlDoc) { string result = ""; string msgType = WXMsgUtil.GetFromXML(xmlDoc, "MsgType"); switch (msgType) { case "event": switch (WXMsgUtil.GetFromXML(xmlDoc, "Event")) { case "subscribe": //订阅 break; case "unsubscribe": //取消订阅 break; case "CLICK": DataTable dtMenuMsg = MenuMsgDal.GetMenuMsg(WXMsgUtil.GetFromXML(xmlDoc, "EventKey")); if (dtMenuMsg.Rows.Count > 0) { List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>(); foreach (DataRow dr in dtMenuMsg.Rows) { Dictionary<string, string> dict = new Dictionary<string, string>(); dict["Title"] = dr["Title"].ToString(); dict["Description"] = dr["Description"].ToString(); dict["PicUrl"] = dr["PicUrl"].ToString(); dict["Url"] = dr["Url"].ToString(); dictList.Add(dict); } result = WXMsgUtil.CreateNewsMsg(xmlDoc, dictList); } else { result = WXMsgUtil.CreateTextMsg(xmlDoc, "无此消息哦"); } break; default: break; } break; case "text": string text = WXMsgUtil.GetFromXML(xmlDoc, "Content"); //if (text == "合肥" || text == "合肥天气" || text == "合肥天气预报" // || text.ToLower() == "hf" || text.ToLower() == "hefei") //{ // result = WXMsgUtil.CreateNewsMsg(xmlDoc, WeatherUtil.GetWeatherInfo()); //} //else { result = WXMsgUtil.CreateNewsMsg(xmlDoc, Weather.GetForecastInfo(text)); //result = WXMsgUtil.CreateTextMsg(xmlDoc, WXMsgUtil.GetTulingMsg(text)); } break; default: break; } if (!string.IsNullOrWhiteSpace(sAppID)) //没有AppID则不加密(订阅号没有AppID) { //加密 WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sEncryptMsg = ""; //xml格式的密文 string timestamp = context.Request["timestamp"]; string nonce = context.Request["nonce"]; int ret = wxcpt.EncryptMsg(result, timestamp, nonce, ref sEncryptMsg); if (ret != 0) { //FileLogger.WriteErrorLog(context, "加密失败,错误码:" + ret); Log.WriteDebug("加密失败,错误码:" + ret); return; } context.Response.Write(sEncryptMsg); context.Response.Flush(); } else { context.Response.Write(result); context.Response.Flush(); } }