/// <summary> /// 实例化微信消息管理实例,并指明操作的公众号 /// </summary> /// <param name="connectWeChat">微信接入基本操作对象</param> /// <param name="idOrAppId">公众号的AppId</param> public MessageLinkUp(IConnectLinkUp connectWeChat, string idOrAppId) { connect = connectWeChat; connect.Initialize(idOrAppId); weChatConfig = connect.WeChatConfig; wxcpt = new Tencent.WXBizMsgCrypt(weChatConfig.Token, weChatConfig.EncodingAESKey, weChatConfig.AppID); }
private static XDocument Init(XDocument postDataDocument, PostModel _postModel) { //进行加密判断并处理 var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value)) { //使用了加密 string sToken = Config.ServerToken; string sAppID = Config.ServerAppID; string sEncodingAESKey = Config.ServerEncodingAESKey; Tencent.WXBizMsgCrypt wxcpt = new Tencent.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 void CheckUrl(HttpContext context) { //公众平台上开发者设置的token, corpID, EncodingAESKey string sToken = ConfigurationManager.AppSettings["Token"].ToString(); string sCorpID = ConfigurationManager.AppSettings["CorpID"].ToString(); string sEncodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"].ToString(); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = context.Request.QueryString["msg_signature"]; string sVerifyTimeStamp = context.Request.QueryString["timestamp"]; string sVerifyNonce = context.Request.QueryString["nonce"]; string sVerifyEchoStr = context.Request.QueryString["echostr"]; int ret = 0; string sEchoStr = ""; try { ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { context.Response.Write("ERR: VerifyURL fail, ret: " + ret); } else { context.Response.Write(sEchoStr); } } catch { context.Response.Write("error: " + ret); } }
/// <summary> /// 初始化并设置微信公众号 /// </summary> /// <param name="idOrAppId">公众号的Id(itfc...)或微信的AppId(wx...)</param> /// <returns>返回微信接入实例本身</returns> public MessageLinkUp Initialize(string idOrAppId) { connect.Initialize(idOrAppId); weChatConfig = connect.WeChatConfig; wxcpt = new Tencent.WXBizMsgCrypt(weChatConfig.Token, weChatConfig.EncodingAESKey, weChatConfig.AppID); return(this); }
/// <summary> /// 返回XML格式的响应消息 /// </summary> /// <param name="encryptType">消息加密类型</param> /// <returns>返回XML格式的响应消息</returns> public string ToXml(MessageEncryptTypeEnum encryptType) { int WXBizMsgCrypt_OK = 0; //得到未加密的XML响应消息 string xml = ToXml(); //如果需要加密,加密消息 if (encryptType == MessageEncryptTypeEnum.aes) { int timeStamp = Utility.ToWeixinTime(CreateTime); Random random = new Random(); string nonce = random.Next().ToString(); AccountInfo account = AccountInfoCollection.GetAccountInfo(FromUserName); if (account != null) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(account.Token, account.EncodingAESKey, account.AppId); string xmlEncrypt = ""; //加密消息 if (wxcpt.EncryptMsg(xml, timeStamp.ToString(), nonce, ref xmlEncrypt) == WXBizMsgCrypt_OK) { return(xmlEncrypt); } } } return(xml); }
public async Task <string> ReviceMessag(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, string baiduAiToken, string baiduImagetoken, string weixinToken) { string encryptMsg = ""; _context.WxOfficialPlatformLoginRecord.Add(new WxOfficialPlatformLoginRecord() { CreateTime = DateTime.Now, Nonce = sNonce, Timestamp = sTimeStamp, Signature = sMsgSignature, PostData = sPostData }); _context.SaveChanges(); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); // int ret = 0; string sMsg = sPostData; //解析之后的明文 //ret = wxcpt.DecryptMsg(sMsgSignature, sTimeStamp, sNonce, sPostData, ref sMsg); Console.WriteLine("sMsg:" + sMsg); if (!string.IsNullOrEmpty(sMsg)) { //封装请求类 WxXmlModel wxXmlModel = WeChatXml.LoadXmlModel(sMsg); Console.WriteLine(wxXmlModel); switch (wxXmlModel.MsgType) { case "text": //文本 encryptMsg = WxTextAnalytical(wxXmlModel, baiduAiToken); break; case "image": //图片 encryptMsg = WxImageAnalytical(wxXmlModel, baiduImagetoken, weixinToken); break; case "voice": encryptMsg = WxVoiceAnalytical(wxXmlModel, baiduAiToken, null); break; default: break; } } //try //{ // //加密回复消息 // wxcpt.EncryptMsg(respMessage, sTimeStamp, sNonce,ref encryptMsg); // Console.WriteLine("encryptMsg:" + encryptMsg); //} //catch (Exception e) //{ // _logger.LogError(e, ""); //} return(encryptMsg); }
static void Main(string[] args) { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "sewapower"; string sAppID = "wx1939f9ee65384f14"; string sEncodingAESKey = "Sd8AFrmKTlF2u5jbQl8vQEYJX57aALEz1OivuIUgD3r"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sReqMsgSig = "c4a5de44f8cfead9f0344023c176204a6283d903"; string sReqTimeStamp = "1552468390"; string sReqNonce = "570040320"; string sReqData = @"<xml> <ToUserName><![CDATA[gh_f0a63a0b8dee]]></ToUserName> <Encrypt><![CDATA[Vu7zu+d43fi2wi35UFAhY5UbNult7drtKnAuWkgEOVSTC+LO9EdsGUBpqsrY44YE6QfPmQ75kg2k2eRyDTQRB57lRHXdLGMuuJqCCSzgh7k7e+UvvqQ69EwPZBhBv1Td63RCgGPl9UYtSOP4AhWWFHWN1Yw5NOTQVid8pPkWYC3fPymUJ5cRadAoqvOpwIpsYxqBnmv7vVg48x/VyXcEH+/Yj9LiLkVIKFkZBriMeMD9tOthvxX65eSIh5AOtYEBnVHepy3WpEOQSlQ9jSgJVY3uXN9s6IYGLoPntpIW29jAFlHeNHw1l7dmP29wPvd6QOEQtg1XnYfazpdqU2MLWHtBw9PHAFEKaJvhdoVC0/zyPbRUGeNnBMKagtEekGdthM44PQub5mUFC/PjgEj1g4ej2ELwq1RuJvbGnG+R097JIufz76T50ckeDc2QTxVGfJZgKMk//lwjF58PfYfZrA==]]></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); string sRespData = "<xml><ToUserName><![CDATA[o4jhJ6DQSJP6m8RsJ_Qt6Iexh48I]]></ToUserName><FromUserName><![CDATA[gh_f0a63a0b8dee]]></FromUserName><CreateTime>1552468390</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[TESTCOMPONENT_MSG_TYPE_TEXT_callback]]></Content></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; }
protected string EncryptMsg(string msg) { Random rand = new Random(); var sReqNonce = rand.Next(99999999).ToString(); var sReqTimeStamp = GetTimeStamp(); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(GetToken(), GetEncodingAESKey(), GetAppID()); string sEncryptMsg = ""; //xml格式的密文 wxcpt.EncryptMsg(msg, sReqTimeStamp, sReqNonce, ref sEncryptMsg); return(sEncryptMsg); }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { //公众平台上开发者设置的token, corpID, EncodingAESKey string sToken = "OnlineServiceHandler"; string sCorpID = "wx31204de5a3ae758e"; string sEncodingAESKey = "rEsvuhPLljasjaUdx7nbcXvAEwishtl2KuvEQQ3J8F3"; logger.Info(context.Request.Url.AbsoluteUri); /* ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业号会向验证url发送一个get请求 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及公众平台推送过来的随机加密字符串(echostr), 这一步注意作URL解码。 2.验证消息体签名的正确性 3.解密出echostr原文,将原文当作Get请求的response,返回给公众平台 第2,3步可以用公众平台提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; context.Request.ContentEncoding = System.Text.Encoding.UTF8; string sVerifyMsgSig = queryStrings["msg_signature"]; string sVerifyTimeStamp = queryStrings["timestamp"]; string sVerifyNonce = queryStrings["nonce"]; string sVerifyEchoStr = queryStrings["echostr"]; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); logger.Info("sVerifyMsgSig=" + sVerifyMsgSig); logger.Info("sVerifyTimeStamp=" + sVerifyTimeStamp); logger.Info("sVerifyNonce=" + sVerifyNonce); logger.Info("sVerifyEchoStr=" + sVerifyEchoStr); logger.Info("sEchoStr=" + sEchoStr); logger.Info("ret=" + ret); if (ret != 0) { logger.Info("ERR: VerifyURL fail, ret: " + ret); System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业号。 context.Response.Write(sEchoStr); // HttpUtils.SetResponse(sEchoStr); }
//範例一:驗證回調URL public long Get(String msg_signature, String timestamp, String nonce, String echostr) { //企业微信后台开发者设置的token, corpID, EncodingAESKey string sToken = "5WQvoxc7HKzxSWKCc3O"; string sCorpID = "wwb2491d1e47ba94f8"; string sEncodingAESKey = "4CyeXxKsWzkYMxepDmdUHzNYHQoJ6QbAFPVN8OvUG4p"; //string sToken = "QDG6eK"; //string sCorpID = "wx5823bf96d3bd56c7"; //string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; /* * ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业微信会向验证url发送一个get请求 * 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及企业微信推送过来的随机加密字符串(echostr), * 这一步注意作URL解码。 * 2.验证消息体签名的正确性 * 3.解密出echostr原文,将原文当作Get请求的response,返回给企业微信 * 第2,3步可以用企业微信提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // string sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature"); //string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyMsgSig = msg_signature; // string sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp"); //string sVerifyTimeStamp = "1409659589"; string sVerifyTimeStamp = timestamp; // string sVerifyNonce = HttpUtils.ParseUrl("nonce"); //string sVerifyNonce = "263014780"; string sVerifyNonce = nonce; // string sVerifyEchoStr = HttpUtils.ParseUrl("echostr"); //string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; string sVerifyEchoStr = echostr; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); //return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业微信。 // HttpUtils.SetResponse(sEchoStr); //return sEchoStr; return(Convert.ToInt64(sEchoStr)); }
public string DecryptMessage(string msgSignature, string timeStamp, string nonce, string data) { string msg = ""; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(_config.Token, _config.EncodingAESKey, _config.ComponentAppId); int ret = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, data, ref msg); if (ret != 0) { throw new Exception($"{nameof(WxApiClient)}.{nameof(DecryptMessage)} ERR: Decrypt fail, ret: {ret}"); } return(msg); }
protected string DecryptMsg(string msg) { var Request = System.Web.HttpContext.Current.Request; string signature = Request.QueryString["msg_signature"];//企业号的 msg_signature string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(GetToken(), GetEncodingAESKey(), GetAppID()); string smag = ""; wxcpt.DecryptMsg(signature, timestamp, nonce, msg, ref smag); return(smag); }
/// <summary> /// 消息加密 /// </summary> /// <param name="msg"></param> /// <param name="timeStamp"></param> /// <param name="nonce"></param> /// <returns></returns> public string EncryptMsg(string msg, string timeStamp, string nonce) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(Token, AESKey, ComponentAppId); string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.EncryptMsg(msg, timeStamp, nonce, ref sMsg); if (ret != 0) { return("fail"); } msg = sMsg; return(msg); }
public void TestEncryptMsg() { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); /* * 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 sReqTimeStamp = "1409659813"; string sReqNonce = "1372623149"; 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格式的密文 int ret = 0; 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); }
/// <summary> /// 消息解密 /// </summary> /// <param name="sign">签名串</param> /// <param name="timeStamp">时间戳</param> /// <param name="nonce">随机串</param> /// <param name="data">密文</param> /// <param name="msg">明文</param> /// <returns></returns> public bool DecryptMsg(string sign, string timeStamp, string nonce, string data, out string msg) { msg = ""; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(Token, AESKey, ComponentAppId); string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sign, timeStamp, nonce, data, ref sMsg); if (ret != 0) { return(false); } msg = sMsg; return(true); }
public override void handleGETRequest(HttpProcessor p) { Console.WriteLine("request: {0}", p.http_url); //企业微信后台开发者设置的token, corpID, EncodingAESKey /* * ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业微信会向验证url发送一个get请求 * 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及企业微信推送过来的随机加密字符串(echostr), * 这一步注意作URL解码。 * 2.验证消息体签名的正确性 * 3.解密出echostr原文,将原文当作Get请求的response,返回给企业微信 * 第2,3步可以用企业微信提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string all_str = p.http_url; all_str = all_str.Substring(all_str.IndexOf("?") + 1); string[] parm = all_str.Split('&'); // string sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature"); string sVerifyMsgSig = HttpUtility.UrlDecode(parm[0].Substring(parm[0].IndexOf("=") + 1)); // string sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp"); string sVerifyTimeStamp = HttpUtility.UrlDecode(parm[1].Substring(parm[1].IndexOf("=") + 1)); // string sVerifyNonce = HttpUtils.ParseUrl("nonce"); string sVerifyNonce = HttpUtility.UrlDecode(parm[2].Substring(parm[2].IndexOf("=") + 1)); // string sVerifyEchoStr = HttpUtils.ParseUrl("echostr"); string sVerifyEchoStr = HttpUtility.UrlDecode(parm[3].Substring(parm[3].IndexOf("=") + 1)); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业微信。 // HttpUtils.SetResponse(sEchoStr); p.writeSuccess(); p.outputStream.WriteLine(sEchoStr); }
public void wxCall() { HttpRequestBase Request = HttpContext.Request; string sToken = "0359i"; string sAppID = "wx3822e482594a911e"; string sEncodingAESKey = "yF94w3TeWPAqCQNUaqByFD39KrLHc2exOLh6RZGXNhU"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sReqMsgSig = Request["msg_signature"]; string sReqTimeStamp = Request["timestamp"]; string sReqNonce = Request["nonce"]; string sReqData = CommFun.ReadRequest(HttpContext.Request); string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); Util.LogHelper.Info(sMsg); }
/// <summary> /// 验证企业号签名 /// </summary> /// <param name="token">企业号配置的Token</param> /// <param name="signature">签名内容</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">nonce参数</param> /// <param name="corpId">企业号ID标识</param> /// <param name="encodingAESKey">加密键</param> /// <param name="echostr">内容字符串</param> /// <param name="retEchostr">返回的字符串</param> /// <returns></returns> public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(token, encodingAESKey, corpId); int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr); if (result != 0) { //LogTextHelper.Error("ERR: VerifyURL fail, ret: " + result); return(false); } return(true); //ret==0表示验证成功,retEchostr参数表示明文,用户需要将retEchostr作为get请求的返回参数,返回给企业号。 // HttpUtils.SetResponse(retEchostr); }
/// <summary> /// 解密消息 /// </summary> /// <returns>返回解密之后的消息</returns> public 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); } Tencent.WXBizMsgCrypt wxcpt = new Tencent.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); }
protected virtual string Auth() { var Request = System.Web.HttpContext.Current.Request; if (HasEncryption()) { string echoString = Request.QueryString["echoStr"]; string signature = Request.QueryString["msg_signature"];//企业号的 msg_signature string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(GetToken(), GetEncodingAESKey(), GetAppID()); string decryptEchoString = ""; wxcpt.VerifyURL(signature, timestamp, nonce, echoString, ref decryptEchoString); return(decryptEchoString); } else { string echoStr = Request.QueryString["echoStr"]; return(echoStr); } }
//驗證回調URL public long Get(String msg_signature, String timestamp, String nonce, String echostr) { //企业微信后台开发者设置的token, corpID, EncodingAESKey string sToken = "5WQvoxc7HKzxSWKCc3O"; string sCorpID = "wwb2491d1e47ba94f8"; string sEncodingAESKey = "4CyeXxKsWzkYMxepDmdUHzNYHQoJ6QbAFPVN8OvUG4p"; /* * ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业微信会向验证url发送一个get请求 * 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及企业微信推送过来的随机加密字符串(echostr), * 这一步注意作URL解码。 * 2.验证消息体签名的正确性 * 3.解密出echostr原文,将原文当作Get请求的response,返回给企业微信 * 第2,3步可以用企业微信提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = msg_signature; string sVerifyTimeStamp = timestamp; string sVerifyNonce = nonce; string sVerifyEchoStr = echostr; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { return(ret); } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业微信。 return(Convert.ToInt64(sEchoStr)); }
public void TestDecryptMsg() { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.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); Assert.AreEqual(0, ret); if (ret != 0) { System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret); return; } System.Console.WriteLine(sMsg); }
//public String Post2(String msg_signature, String timestamp, String nonce, [FromBody]string xml) public String Post2(String msg_signature, String timestamp, String nonce) { //企业微信后台开发者设置的token, corpID, EncodingAESKey string sToken = "5WQvoxc7HKzxSWKCc3O"; string sCorpID = "wwb2491d1e47ba94f8"; string sEncodingAESKey = "4CyeXxKsWzkYMxepDmdUHzNYHQoJ6QbAFPVN8OvUG4p"; //string sToken = "QDG6eK"; //string sCorpID = "wx5823bf96d3bd56c7"; //string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; /* * ------------使用示例二:对用户回复的消息解密--------------- * 用户回复消息或者点击事件响应时,企业会收到回调消息,此消息是经过企业微信加密之后的密文以post形式发送给企业,密文格式请参考官方文档 * 假设企业收到企业微信的回调消息如下: * 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> * <AgentID><![CDATA[218]]></AgentID> * </xml> * * 企业收到post请求之后应该 1.解析出url上的参数,包括消息体签名(msg_signature),时间戳(timestamp)以及随机数字串(nonce) * 2.验证消息体签名的正确性。 * 3.将post请求的数据进行xml解析,并将<Encrypt>标签的内容进行解密,解密出来的明文即是用户回复消息的明文,明文格式请参考官方文档 * 第2,3步可以用企业微信提供的库函数DecryptMsg来实现。 */ StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream, Encoding.UTF8); XmlDocument xdoc = new XmlDocument(); xdoc.Load(sr); sr.Close(); sr.Dispose(); //string sToUserName = doc.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText; //string sAgentID = doc.SelectSingleNode("xml").SelectSingleNode("AgentID").InnerText; //string sXML = xdoc.InnerXml; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // string sReqMsgSig = HttpUtils.ParseUrl("msg_signature"); //string sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6"; string sReqMsgSig = msg_signature; // string sReqTimeStamp = HttpUtils.ParseUrl("timestamp"); //string sReqTimeStamp = "1409659813"; string sReqTimeStamp = timestamp; // string sReqNonce = HttpUtils.ParseUrl("nonce"); //string sReqNonce = "1372623149"; string sReqNonce = nonce; // Post请求的密文数据 // string sReqData = HttpUtils.PostData(); //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><AgentID><![CDATA[218]]></AgentID></xml>"; string sReqData = xdoc.InnerXml; string sError = ""; string sMsg = ""; // 解析之后的明文 string sRespData_p1 = "<xml><ToUserName><![CDATA[YuYuYi]]></ToUserName><FromUserName><![CDATA[wwb2491d1e47ba94f8]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA["; string sRespData_p3 = "]]></Content><MsgId>1234567890123456</MsgId><AgentID>1000002</AgentID></xml>"; string sRespData_p2 = ""; string sRespData = ""; // 需要发送的明文 string sEncryptMsg = ""; //xml格式的密文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { //System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); //return; sRespData_p2 = "ERR: 解密失敗, ret: " + ret; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); return(sEncryptMsg); } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 // TODO: 对明文的处理 // For example: string content = ""; string event_type = ""; string event_key = ""; XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); XmlNode root = doc.FirstChild; string msgtype = root["MsgType"].InnerText; switch (msgtype) { case "text": content = root["Content"].InnerText; sRespData_p2 = "您輸入: " + content; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; case "event": event_type = root["Event"].InnerText; switch (event_type) { case "click": event_key = root["EventKey"].InnerText; switch (event_key) { case "menu_hit": sRespData_p2 = "您按了點擊測試鈕"; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; case "menu_contact": string sConnString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["WebAPI"].ConnectionString; SqlConnection mConn = new SqlConnection(sConnString); mConn.Open(); string sSQL = @"select * from Contract"; SqlCommand mCommand = new SqlCommand(sSQL, mConn); SqlDataReader mDataReader = mCommand.ExecuteReader(); while (mDataReader.Read()) { } sRespData = "<xml><ToUserName><![CDATA[YuYuYi]]></ToUserName><FromUserName><![CDATA[wwb2491d1e47ba94f8]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[title1]]></Title><Description><![CDATA[description1]]></Description><PicUrl><![CDATA[picurl]]></PicUrl><Url><![CDATA[url]]></Url></item></Articles></xml>"; break; default: sRespData_p2 = "您按了某個鈕"; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; } break; case "scancode_push": event_key = root["EventKey"].InnerText; if (event_key == "menu_push") { //掃描後回傳xml //< ScanCodeInfo > //< ScanType >< ![CDATA[qrcode]] ></ ScanType > //< ScanResult >< ![CDATA[1]] ></ ScanResult > //</ ScanCodeInfo > sRespData_p2 = root["ScanCodeInfo"].ChildNodes.Item(1).InnerText; sRespData_p2 = "您的掃描值: " + sRespData_p2; //sRespData_p2 = sRespData_p2.Replace("qrcode", ""); //if (string.IsNullOrEmpty(sRespData_p2)) //{ // sRespData_p2 = "沒抓到掃描值"; //} sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; } break; case "scancode_waitmsg": event_key = root["EventKey"].InnerText; switch (event_key) { case "menu_push2": //掃描後回傳xml //< ScanCodeInfo > //< ScanType >< ![CDATA[qrcode]] ></ ScanType > //< ScanResult >< ![CDATA[1]] ></ ScanResult > //</ ScanCodeInfo > sRespData_p2 = root["ScanCodeInfo"].ChildNodes.Item(1).InnerText; sRespData_p2 = "您的掃描值: " + sRespData_p2; //sRespData_p2 = sRespData_p2.Replace("qrcode", ""); //if (string.IsNullOrEmpty(sRespData_p2)) //{ // sRespData_p2 = "沒抓到掃描值"; //} sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; case "menu_assets": //連線字串 string connStr2 = @"Data Source=TOPPROD;Persist Security Info=True;User ID=formal_tw;Password=formal_tw;Unicode=True"; string s_faj06 = ""; //品名 string s_faj19 = ""; //保管人 string s_faj20 = ""; //保管部門 sRespData_p2 = root["ScanCodeInfo"].ChildNodes.Item(1).InnerText; using (OracleConnection conn = new OracleConnection(connStr2)) { conn.Open(); string sql = @"select faj02,faj022,faj06,gem02,gen02 from faj_file,gem_file,gen_file where faj20=gem01(+) and faj19=gen01(+) and faj02 = '" + sRespData_p2 + "' "; OracleCommand cmd = new OracleCommand(sql, conn); OracleDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { if (!dr.IsDBNull(dr.GetOrdinal("faj06"))) { s_faj06 = dr.GetString(dr.GetOrdinal("faj06")); } if (!dr.IsDBNull(dr.GetOrdinal("gem02"))) { s_faj20 = dr.GetString(dr.GetOrdinal("gem02")); } if (!dr.IsDBNull(dr.GetOrdinal("gen02"))) { s_faj19 = dr.GetString(dr.GetOrdinal("gen02")); } sRespData_p2 = "財產編號:" + dr.GetString(dr.GetOrdinal("faj02")) + "\n附號:" + dr.GetString(dr.GetOrdinal("faj022")) + "\n品名:" + s_faj06 + "\n保管部門:" + s_faj20 + "\n保管人:" + s_faj19; } conn.Close(); } sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; } break; case "pic_sysphoto": //拍照後回傳xml //< ScanCodeInfo > //< Count >1</ Count > //< PicList > //<item> //<PicMd5Sum><![CDATA[1b5f7c23b5bf75682a53e7b6d163e185]]></PicMd5Sum> //</item> //</ PicList > //</ ScanCodeInfo > event_key = root["EventKey"].InnerText; if (event_key == "menu_photo") { sRespData_p2 = root["ScanCodeInfo"].ChildNodes.Item(0).InnerText; sRespData_p2 = "您傳送的拍照數量: " + sRespData_p2; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; } break; case "location_select": /* * 定位後回傳xml * <SendLocationInfo> * <Location_X><![CDATA[23]]></Location_X> * <Location_Y><![CDATA[113]]></Location_Y> * <Scale><![CDATA[15]]></Scale> * <Label><![CDATA[ 广州市海珠区客村艺苑路 106号]]></Label> * <Poiname><![CDATA[]]></Poiname> * </SendLocationInfo> */ event_key = root["EventKey"].InnerText; if (event_key == "menu_gps") { string sLoc_X = root["SendLocationInfo"].ChildNodes.Item(0).InnerText; string sLoc_Y = root["SendLocationInfo"].ChildNodes.Item(1).InnerText; string sScale = root["SendLocationInfo"].ChildNodes.Item(2).InnerText; string sLabel = root["SendLocationInfo"].ChildNodes.Item(3).InnerText; string sPOI = root["SendLocationInfo"].ChildNodes.Item(4).InnerText; sRespData_p2 = "座標X:" + sLoc_X + " 座標Y:" + sLoc_Y + " 精度:" + sScale + " 位置名稱:" + sLabel; if (string.IsNullOrEmpty(sPOI) == false) { sRespData_p2 = sRespData_p2 + " POI:" + sPOI; } sRespData_p2 = "您的GPS定位: " + sRespData_p2; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; } break; case "LOCATION": string sLatitude = root["Latitude"].InnerText; string sLongitude = root["Longitude"].InnerText; string sPrecision = root["Precision"].InnerText; sRespData_p2 = "緯度:" + sLatitude + " 經度:" + sLongitude + " 精確度:" + sPrecision; sRespData_p2 = "您的GPS定位: " + sRespData_p2; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; case "pic_photo_or_album": /* * <SendPicsInfo> * <Count>1</Count> * <PicList> * <item> * <PicMd5Sum><![CDATA[5a75aaca956d97be686719218f275c6b]]></PicMd5Sum> * </item> * </PicList> * </SendPicsInfo> */ event_key = root["EventKey"].InnerText; if (event_key == "menu_pic") { sRespData_p2 = root["SendPicsInfo"].ChildNodes.Item(0).InnerText; sRespData_p2 = "您傳送的照片數量: " + sRespData_p2; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; } break; case "pic_weixin": /* * <SendPicsInfo> * <Count>1</Count> * <PicList> * <item> * <PicMd5Sum><![CDATA[5a75aaca956d97be686719218f275c6b]]></PicMd5Sum> * </item> * </PicList> * </SendPicsInfo> */ event_key = root["EventKey"].InnerText; if (event_key == "menu_wx_pic") { sRespData_p2 = root["SendPicsInfo"].ChildNodes.Item(0).InnerText; sRespData_p2 = "您傳送的微信照片數量: " + sRespData_p2; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; } break; case "enter_agent": sRespData_p2 = "您好,歡迎來到宏致電子"; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; case "subscribe": //關注 sRespData_p2 = "您好,已接收關注,感謝您關注宏致電子"; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; case "unsubscribe": //取消關注 sRespData_p2 = "您好,已取消關注,感謝您曾經關注宏致電子"; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; } break; default: sRespData_p2 = "還未定義的MsgType"; sRespData = sRespData_p1 + sRespData_p2 + sRespData_p3; break; } //content= sMsg.Replace(">","").Substring(0,48); //content = sMsg.Replace(">", ""); /* * ------------使用示例三:企业回复用户消息的加密--------------- * 企业被动回复用户的消息也需要进行加密,并且拼接成密文格式的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> * <AgentID>128</AgentID> * </xml> * * 为了将此段明文回复给用户,企业应: 1.自己生成时间时间戳(timestamp),随机数字串(nonce)以便生成消息体签名,也可以直接用从企业微信的post url上解析出的对应值。 * 2.将明文加密得到密文。 3.用密文,步骤1生成的timestamp,nonce和企业在企业微信设定的token生成消息体签名。 4.将密文,消息体签名,时间戳,随机数字串拼接成xml格式的字符串,发送给企业。 * 以上2,3,4步可以用企业微信提供的库函数EncryptMsg来实现。 */ //content = xdoc.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText; if (string.IsNullOrEmpty(content)) { content = "vnull"; } // 需要发送的明文 //string sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>"; //string sRespData = "<xml><ToUserName><![CDATA[YuYuYi]]></ToUserName><FromUserName><![CDATA[wwb2491d1e47ba94f8]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[您剛剛說:『" + content+"』 ]]></Content><MsgId>1234567890123456</MsgId><AgentID>1000002</AgentID></xml>"; //string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); //return; sError = "ERR: 加密失敗, ret: " + ret; } //if (string.IsNullOrEmpty(sError)) //{ } //else{ // sRespData = "<xml><ToUserName><![CDATA[YuYuYi]]></ToUserName><FromUserName><![CDATA[wwb2491d1e47ba94f8]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Error " + sError + " ]]></Content><MsgId>1234567890123456</MsgId><AgentID>1000002</AgentID></xml>"; // ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); //} // TODO: // 加密成功,企业需要将加密之后的sEncryptMsg返回 // HttpUtils.SetResponse(sEncryptMsg); return(sEncryptMsg); }
static void Test(string[] args) { //公众平台上开发者设置的token, corpID, EncodingAESKey string sToken = "QDG6eK"; string sCorpID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; /* ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业号会向验证url发送一个get请求 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及公众平台推送过来的随机加密字符串(echostr), 这一步注意作URL解码。 2.验证消息体签名的正确性 3.解密出echostr原文,将原文当作Get请求的response,返回给公众平台 第2,3步可以用公众平台提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // string sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature"); string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; // string sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp"); string sVerifyTimeStamp = "1409659589"; // string sVerifyNonce = HttpUtils.ParseUrl("nonce"); string sVerifyNonce = "263014780"; // string sVerifyEchoStr = HttpUtils.ParseUrl("echostr"); string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret ); return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业号。 // HttpUtils.SetResponse(sEchoStr); /* ------------使用示例二:对用户回复的消息解密--------------- 用户回复消息或者点击事件响应时,企业会收到回调消息,此消息是经过公众平台加密之后的密文以post形式发送给企业,密文格式请参考官方文档 假设企业收到公众平台的回调消息如下: 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> <AgentID><![CDATA[218]]></AgentID> </xml> 企业收到post请求之后应该 1.解析出url上的参数,包括消息体签名(msg_signature),时间戳(timestamp)以及随机数字串(nonce) 2.验证消息体签名的正确性。 3.将post请求的数据进行xml解析,并将<Encrypt>标签的内容进行解密,解密出来的明文即是用户回复消息的明文,明文格式请参考官方文档 第2,3步可以用公众平台提供的库函数DecryptMsg来实现。 */ // string sReqMsgSig = HttpUtils.ParseUrl("msg_signature"); string sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6"; // string sReqTimeStamp = HttpUtils.ParseUrl("timestamp"); string sReqTimeStamp = "1409659813"; // string sReqNonce = HttpUtils.ParseUrl("nonce"); string sReqNonce = "1372623149"; // Post请求的密文数据 // string sReqData = HttpUtils.PostData(); 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><AgentID><![CDATA[218]]></AgentID></xml>"; string sMsg = ""; // 解析之后的明文 ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 // TODO: 对明文的处理 // For example: XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); XmlNode root = doc.FirstChild; string content = root["Content"].InnerText; System.Console.WriteLine(content); // ... // ... /* ------------使用示例三:企业回复用户消息的加密--------------- 企业被动回复用户的消息也需要进行加密,并且拼接成密文格式的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> <AgentID>128</AgentID> </xml> 为了将此段明文回复给用户,企业应: 1.自己生成时间时间戳(timestamp),随机数字串(nonce)以便生成消息体签名,也可以直接用从公众平台的post url上解析出的对应值。 2.将明文加密得到密文。 3.用密文,步骤1生成的timestamp,nonce和企业在公众平台设定的token生成消息体签名。 4.将密文,消息体签名,时间戳,随机数字串拼接成xml格式的字符串,发送给企业。 以上2,3,4步可以用公众平台提供的库函数EncryptMsg来实现。 */ // 需要发送的明文 string sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>"; string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); if( ret!=0 ) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } // TODO: // 加密成功,企业需要将加密之后的sEncryptMsg返回 // HttpUtils.SetResponse(sEncryptMsg); return; }
/// <summary> /// 获取接收消息实体 /// </summary> /// <param name="sstream">post过来的数据流</param> /// <param name="sSignature">签名串</param> /// <param name="sTimeStamp">时间戳</param> /// <param name="sNonce">随机串</param> /// <returns></returns> public ReceiveMsg GetMsgObj(Stream sstream, string sSignature, string sTimeStamp, string sNonce) { using (Stream stream = sstream) { Byte[] postBytes = new Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); var postString = Encoding.UTF8.GetString(postBytes); if (!string.IsNullOrEmpty(postString)) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(this._token, this._encodingAESKey, this._corpID); var resMsg = string.Empty; var res = wxcpt.DecryptMsg(sSignature, sTimeStamp, sNonce, postString, ref resMsg); if (res == 0) { return ReceiveMsg.GetMsgObj(resMsg); } else { LogHelper.AppendLog("获取接收消息实体: " + res); } } } return null; }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); string sToken = "ServiceComplainHandler"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx4fe8b74e01fffcbb"; string sEncodingAESKey = "1cKOgDDDPDBp2yveG55gootenlqivqTcX2K0wz804x5"; // string sToken = Properties.Settings.Default.Wechat_AgentFee_Token;//"AgentFee"; // string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; // string sEncodingAESKey = Properties.Settings.Default.Wechat_AgentFee_EncodingAESKey;// "he8dYrZ5gLbDrDhfHVJkea1AfmHgRZQJq47kuKpQrSO"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); // 需要发送的明文 String actionType = wechatMessage.EventKey; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); // string sRespData = "<MsgId>1234567890123456</MsgId>"; logger.Info("EventKey: " + wechatMessage.EventKey); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Complain; wechatQueryLog.subSystem = "投诉协查"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } if (agentWechatAccount != null && !String.IsNullOrEmpty(agentWechatAccount.status) && !agentWechatAccount.status.Equals("Y")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "对不起,你的账号已被停用,请联系联通工作人员!\n\n"); } else if (agentWechatAccount == null) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "用户不存在,请联系联通工作人员!\n\n"); } else { String agentNo = agentWechatAccount.branchNo; if (String.IsNullOrEmpty(agentNo)) { agentNo = agentWechatAccount.agentNo; } AgentContactDao agentContactDao = new ChinaUnion_DataAccess.AgentContactDao(); switch (actionType) { case "ContactPerson": logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "没有找到对应的联系人,请直接与上海联通确认!\n\n"); break; } } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); }
public void Notice() { /* <xml><AppId><![CDATA[wx3822e482594a911e]]></AppId> <CreateTime>1456903904</CreateTime> <InfoType><![CDATA[component_verify_ticket]]></InfoType> <ComponentVerifyTicket><![CDATA[ticket@@@Iv_fUfslI38h5WzYWsa6s1nvVyw8NI8ZxumDTw7nIa0WmE0y9yp0UFU3XLo7CuVKtUvSbwG2eG7-W1EirYHSvA]]></ComponentVerifyTicket> </xml> */ wx_openInfo wx_open = wx_openInfoService.instance().Single(new Guid(System.Configuration.ConfigurationManager.AppSettings["openID"])); HttpRequestBase Request = HttpContext.Request; string sToken = wx_open.open_sToken; string sAppID = wx_open.open_sAppID; string sAppSecret = wx_open.open_sAppSecret; string sEncodingAESKey = wx_open.open_sEncodingAESKey; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sReqMsgSig = Request["msg_signature"]; string sReqTimeStamp = Request["timestamp"]; string sReqNonce = Request["nonce"]; string sReqData = ReadRequest(HttpContext.Request); string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (!string.IsNullOrEmpty(sMsg)) { XElement element = XElement.Parse(sMsg); if (_queue == null) { _queue = new List<queue>(); } else if (_queue.Count >= 50) { _queue = _queue.Where(q => { return q.CreateTime.AddSeconds(20) > DateTime.Now; }).ToList();//保留20秒内未响应的消息 } if (_queue.FirstOrDefault(m => { return m.time == element.Element("CreateTime").Value.ToLower().ToString() && m.FromUserName == element.Element("InfoType").Value.ToLower().ToString(); }) == null) { _queue.Add(new queue { CreateTime = DateTime.Now, FromUserName = element.Element("InfoType").Value.ToLower().ToString(), time = element.Element("CreateTime").Value.ToLower().ToString() }); } else { return; } #region 处理事件 string type = element.Element("InfoType").Value.ToString().ToUpper(); switch (type) { case "COMPONENT_VERIFY_TICKET"://推送component_verify_ticket协议,每隔10分钟定时推送 Util.LogHelper.Info("推送component_verify_ticket协议--start【"); string ticket = element.Element("ComponentVerifyTicket").Value.ToString(); //更新ticket if (wx_open.open_ticket != ticket) { wx_open.open_ticket = ticket; Util.LogHelper.Info("更新ticket:" + ticket); } else { Util.LogHelper.Info("ticket无需更新:" + ticket); } //更新open_access_token var result = ComponentApi.GetComponentAccessToken(sAppID, sAppSecret, ticket); if (result.errcode == ReturnCode.请求成功) { if (wx_open.open_access_token != result.component_access_token) { wx_open.open_access_token = result.component_access_token; wx_open.access_token_expires_in = result.expires_in; Util.LogHelper.Info("更新open_access_token:" + result.component_access_token); } else { Util.LogHelper.Info("open_access_token无需更新:" + result.component_access_token); } } else { Util.LogHelper.Info("更新open_access_token错误:" + result.errcode.ToString()); } //更新open_pre_auth_cod var coderesult = ComponentApi.GetPreAuthCode(sAppID, result.component_access_token); if (coderesult.errcode == ReturnCode.请求成功) { if (wx_open.open_pre_auth_code != coderesult.pre_auth_code) { wx_open.open_pre_auth_code = coderesult.pre_auth_code; wx_open.pre_auth_code_wxpires_in = coderesult.expires_in; Util.LogHelper.Info("更新open_pre_auth_code:" + coderesult.pre_auth_code); } else { Util.LogHelper.Info("open_pre_auth_code无需更新:" + coderesult.pre_auth_code); } } else { Util.LogHelper.Info("更新open_pre_auth_code错误:" + coderesult.errcode.ToString()); } wx_open.ModifyTime = DateTime.Now; //保存到数据库 if (wx_openInfoService.instance().Update(wx_open) == 1) { Util.LogHelper.Info("推送component_verify_ticket协议--成功--end】"); } else { Util.LogHelper.Info("推送component_verify_ticket协议--失败--end】"); } //if (wx_open.open_ticket != ticket) //{ // wx_open.open_ticket = ticket; // Util.LogHelper.Info("更新ticket:" + ticket); // var result = ComponentApi.GetComponentAccessToken(sAppID, sAppSecret, ticket); // if (result.errcode == Entity.Weixin.ReturnCode.请求成功) // { // wx_open.open_access_token = result.component_access_token; // wx_open.expires_in = result.expires_in; // Util.LogHelper.Info("更新open_access_token" + result.component_access_token); // var coderesult = ComponentApi.GetPreAuthCode(sAppID, result.component_access_token); // if (coderesult.errcode == Entity.Weixin.ReturnCode.请求成功) // { // wx_open.open_pre_auth_code = coderesult.pre_auth_code; // Util.LogHelper.Info("更新open_pre_auth_code" + coderesult.pre_auth_code); // if (wx_openInfoService.instance().Update(wx_open) == 1) // { // Util.LogHelper.Info("推送component_verify_ticket协议--成功--end"); // } // else { // Util.LogHelper.Info("推送component_verify_ticket协议--失败--end"); // } // } // } //} //else { // Util.LogHelper.Info("推送component_verify_ticket协议--不需更新--end"); //} break; case "UNAUTHORIZED"://取消授权通知 string appid = element.Element("AuthorizerAppid").Value; Util.LogHelper.Info(appid + "取消授权--start"); var entity = wx_userweixinService.instance().SingleByAppId(appid); if (entity != null) { entity.DR = true; if (wx_userweixinService.instance().Update(entity) == 1) Util.LogHelper.Info(appid + "取消授权--成功--start"); else Util.LogHelper.Info(appid + "取消授权--失败--start"); } break; case "AUTHORIZED"://授权成功通知 string au_appid = element.Element("AuthorizerAppid").Value.ToString(); Util.LogHelper.Info(au_appid + "授权--start"); var au_entity = wx_userweixinService.instance().SingleByAppId(au_appid); if (au_entity != null) { au_entity.DR = false; Util.LogHelper.Info(au_appid + "授权--更新--start"); if (wx_userweixinService.instance().Update(au_entity) == 1) Util.LogHelper.Info(au_appid + "授权--成功--start"); else Util.LogHelper.Info(au_appid + "授权--失败--start"); } else { Util.LogHelper.Info(au_appid + "数据库没有数据"); } /*<xml> <AppId>第三方平台appid</AppId> <CreateTime>1413192760</CreateTime> <InfoType>authorized</InfoType> <AuthorizerAppid>公众号appid</AuthorizerAppid> <AuthorizationCode>授权码(code)</AuthorizationCode> <AuthorizationCodeExpiredTime>过期时间</AuthorizationCodeExpiredTime> </xml>*/ break; case "UPDATEAUTHORIZED"://授权更新通知 /* <xml> <AppId>第三方平台appid</AppId> <CreateTime>1413192760</CreateTime> <InfoType>updateauthorized</InfoType> <AuthorizerAppid>公众号appid</AuthorizerAppid> <AuthorizationCode>授权码(code)</AuthorizationCode> <AuthorizationCodeExpiredTime>过期时间</AuthorizationCodeExpiredTime> </xml>*/ break; default: break; } #endregion } }
/// <summary> /// 通过判断事件类型进行消息的回复 /// </summary> /// <param name="ReqTime"></param> /// <param name="ReqNonce"></param> /// <param name="Msg"></param> /// <param name="choose"></param> public void Reply_Msg(string ReqTime, string ReqNonce, string Msg, string choose) { string sToken = "D2op9SR8HV4U5vVL7p1bKFm2fjLdXV8"; string sCorpID = "wx4fbb38c93e921603"; string sEncodingAESKey = "vQrIN6MevZ2RJekY79C0RC19Fe4KNcvI6UM4IQvGeWq"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sReqTimeStamp = ReqTime; string sReqNonce = ReqNonce; string respdata = ""; if (Choose_MsgType == "event")//事件处理 { if (Choose_Event == "click")//菜单点击事件的回复 { if (choose == "Soft_01") { respdata = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName>" + "<FromUserName><![CDATA[!]]></FromUserName>" + "<CreateTime>1348831860</CreateTime>" + "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[软件工程]]></Content>" + "<MsgId>1234567890123456</MsgId>" + "<AgentID>128</AgentID></xml>"; } if (choose == "Math_01") { /* ServiceApi a = new ServiceApi(); a.Text_Service(); string text; StreamReader sr = new StreamReader(@"E:\程序库\Text_Service.txt"); text = sr.ReadToEnd(); sr.Close(); */ DB db = new DB(); respdata = db.GetTextMenuXmlPage(); } if (choose == "Electrical_01") { if (Choose_FromUserName == "BB") { DB db = new DB(); respdata = db.GetAppointUserXmlPage("BB"); } if (Choose_FromUserName == "Keybord") { DB db = new DB(); respdata = db.GetAppointUserXmlPage("Keybord"); } if (Choose_FromUserName == "Panda") { DB db = new DB(); respdata = db.GetAppointUserXmlPage("Panda"); } } if (choose == "China_01") { respdata = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName>" + "<FromUserName><![CDATA[wx582396d3bd56c7]]></FromUserName>" + "<CreateTime>1348831860</CreateTime>" + "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[汉语言文学]]></Content>" + "<MsgId>1234567890123456</MsgId>" + "<AgentID>128</AgentID></xml>"; } } } if (Choose_MsgType == "text")//文本消息的回复 { /* StreamReader sr = new StreamReader(@"E:\程序库\repData_video.txt"); RepData = sr.ReadLine(); sr.Close(); respdata = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName>"+ "<FromUserName><![CDATA[wx582396d3bd56c7]]></FromUserName>"+ "<CreateTime>1357290913</CreateTime><MsgType><![CDATA[video]]></MsgType>"+ "<Video><MediaId>"+ "<![CDATA["+RepData+"]]>"+ "</MediaId>"+ "<Title><![CDATA[细节]]></Title><Description><![CDATA[习大大]]></Description></Video></xml>"; */ if (Choose_FromUserName == "BB") { ServiceApi sap = new ServiceApi(); respdata = sap.GetFunctionXmlPage("BB", Choose_Text); } if (Choose_FromUserName == "Keybord") { ServiceApi sap = new ServiceApi(); respdata = sap.GetFunctionXmlPage("Keybord", Choose_Text); } if (Choose_FromUserName == "Panda") { ServiceApi sap = new ServiceApi(); respdata = sap.GetFunctionXmlPage("Panda", Choose_Text); } } if (Choose_MsgType == "image")//图片消息的回复 { /* StreamReader sr = new StreamReader(@"E:\程序库\repData_image.txt"); RepData = sr.ReadLine(); sr.Close(); */ DB db = new DB(); RepData = db.GetImageMedia("BB"); respdata = "<xml><ToUserName><![CDATA[wx4fbb38c93e921603]]></ToUserName>" + "<FromUserName><![CDATA[Keybord]]></FromUserName>" + "<CreateTime>1348831860</CreateTime><MsgType><![CDATA[image]]></MsgType>" + "<Image><MediaId>" + "<![CDATA[" + RepData + "]]>" + "</MediaId></Image></xml>"; } if (Choose_MsgType == "voice")//语音消息的回复 { /* StreamReader sr = new StreamReader(@"E:\程序库\repData_voice.txt"); RepData = sr.ReadLine(); sr.Close(); */ DB db = new DB(); RepData = db.GetVoideMedia("User");//调用函数获得音频MediaID respdata = "<xml><ToUserName><![CDATA[wx4fbb38c93e921603]]></ToUserName>" + "<FromUserName><![CDATA[Keybord]]></FromUserName>" + "<CreateTime>1357290913</CreateTime><MsgType><![CDATA[voice]]></MsgType>" + "<Voice><MediaId>" + "<![CDATA[" + RepData + "]]>" + "</MediaId></Voice></xml>"; } string sEncryptMsg = ""; //xml格式的密文 int ret = 0; ret = wxcpt.EncryptMsg(respdata, sReqTimeStamp, sReqNonce, ref sEncryptMsg); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } // TODO: // 加密成功,企业需要将加密之后的sEncryptMsg返回 //HttpUtils.SetResponse(sEncryptMsg); return; }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); //string sToken = "AgentFee"; //string sCorpID = "wx4fe8b74e01fffcbb"; //string sEncodingAESKey = "gvGJnhpjeljcKzvfe8B8vnmMBBLkJFuzUYSjsGcDQFE"; string sToken = Properties.Settings.Default.Wechat_ErrorCode_Token;// "ErrorCode"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; string sEncodingAESKey = Properties.Settings.Default.Wechat_ErrorCode_EncodingAESKey;// "VcEu5ijaEa6xVklONE9APWJgfvh1UhGjXGKAdeHWAWQ"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Error; wechatQueryLog.subSystem = "报错处理"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } try { if (String.IsNullOrEmpty(wechatMessage.Content)) { wechatMessage.Content = "help"; } switch (wechatMessage.Content.ToLower()) { case "help": case "?": case "?": sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "请输入错误关键字查询错误详细说明,例如:输入\"系统异常\"查询包含\"系统异常\"的错误信息"); break; default: AgentErrorCodeDao agentErrorCodeDao = new AgentErrorCodeDao(); int maxArticleCnt = 10; IList<AgentErrorCode> agentErrorCodeList = agentErrorCodeDao.GetList(wechatMessage.Content); if (agentErrorCodeList != null && agentErrorCodeList.Count > 0) { sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>"); if (agentErrorCodeList.Count > maxArticleCnt) { sb.AppendFormat("<ArticleCount>{0}</ArticleCount>", maxArticleCnt); } else if (agentErrorCodeList.Count <= 10 && agentErrorCodeList.Count > 0) { sb.AppendFormat("<ArticleCount>{0}</ArticleCount>", agentErrorCodeList.Count); } sb.AppendFormat("<Articles>"); int count = 0; foreach (AgentErrorCode agentErrorCode in agentErrorCodeList) { count++; if (count > maxArticleCnt) { break; } String dir = context.Server.MapPath("~/") + @"\ErrorImages\"; logger.Info("Path=" + dir + agentErrorCode.seq + ".jpg"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } String path = dir + agentErrorCode.seq + ".jpg"; if (!File.Exists(path) || !File.GetCreationTime(path).ToString("yyyy-MM-dd").Equals(DateTime.Now.ToString("yyyy-MM-dd"))) { if (agentErrorCode.errorImg != null) { logger.Info("path=" + path); System.IO.File.WriteAllBytes(path, agentErrorCode.errorImg); } else { logger.Info("path=no image"); } } sb.AppendFormat("<item>"); sb.Append("<Title>").AppendFormat("{0}报错查询结果", agentErrorCode.keyword).Append("</Title>"); // String errorCondition = wechatMessage.Content.Substring("error:".Length); StringBuilder sbDesc = new StringBuilder(); //sbDesc.AppendFormat("本月佣金告知单({0})", feeMonth); sbDesc.AppendFormat("问题描述:\n{0}\n\n", agentErrorCode.errorDesc); sbDesc.AppendFormat("处理方法:\n{0}\n\n", agentErrorCode.solution); sbDesc.AppendFormat("联系人员:{0}\n\n", agentErrorCode.contactName); sbDesc.AppendFormat("备注:\n{0}\n", agentErrorCode.comment); sb.Append("<Description>").AppendFormat("<![CDATA[{0}]]>", sbDesc.ToString()).Append("</Description>"); sb.Append("<PicUrl>").AppendFormat("<![CDATA[{0}{1}{2}]]>", "http://"+Properties.Settings.Default.Host+"/Wechat/ErrorImages/", agentErrorCode.seq, ".jpg").Append("</PicUrl>"); //logger.Info("path=" + "http://"http://"+Properties.Settings.Default.Host+"/Wechat/ErrorCodeQuery.aspx?keyword=" + context.Server.UrlEncode(agentErrorCode.keyword)); sb.Append("<Url>").AppendFormat("<![CDATA[{0}{1}{2}]]>", "http://" + Properties.Settings.Default.Host + "/Wechat/ErrorCodeQuery.aspx?keyword=", context.Server.UrlEncode(agentErrorCode.keyword), "&userId=" + wechatMessage.FromUserName).Append("</Url>"); // sb.Append("<Url>").AppendFormat("<![CDATA[{0}]]>", url1).Append("</Url>"); sb.AppendFormat("</item>"); // logger.Info(sb.ToString()); } sb.AppendFormat("</Articles>"); } else { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "没有找到与" + wechatMessage.Content+"相关的错误详细信息,请更改查询条件或者与联通相关人员确认。"); } break; } } catch (Exception ex) { logger.Info(ex.Message); } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); // TODO: // 加密成功,企业需要将加密之后的sEncryptMsg返回 // HttpUtils.SetResponse(sEncryptMsg); }
public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) { Console.WriteLine("POST request: {0}", p.http_url); string data = inputData.ReadToEnd(); /* * Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); * ------------使用示例二:对用户回复的消息解密-------------- - * 用户回复消息或者点击事件响应时,企业会收到回调消息,此消息是经过企业微信加密之后的密文以post形式发送给企业,密文格式请参考官方文档 * 假设企业收到企业微信的回调消息如下: * * POST / cgi - bin / wxpush ? msg_signature = 477715d11cdb4164915debcba66cb864d751f3e6 & timestamp = 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 > * * < AgentID >< ![CDATA[218]] ></ AgentID > * * </ xml > * * 企业收到post请求之后应该 1.解析出url上的参数,包括消息体签名(msg_signature),时间戳(timestamp)以及随机数字串(nonce) * * 2.验证消息体签名的正确性。 * 3.将post请求的数据进行xml解析,并将<Encrypt> 标签的内容进行解密,解密出来的明文即是用户回复消息的明文,明文格式请参考官方文档 * 第2,3步可以用企业微信提供的库函数DecryptMsg来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string all_str = p.http_url; all_str = all_str.Substring(all_str.IndexOf("?") + 1); string[] parm = all_str.Split('&'); // string sReqMsgSig = HttpUtils.ParseUrl("msg_signature"); string sReqMsgSig = HttpUtility.UrlDecode(parm[0].Substring(parm[0].IndexOf("=") + 1)); // string sReqTimeStamp = HttpUtils.ParseUrl("timestamp"); string sReqTimeStamp = HttpUtility.UrlDecode(parm[1].Substring(parm[1].IndexOf("=") + 1)); // string sReqNonce = HttpUtils.ParseUrl("nonce"); string sReqNonce = HttpUtility.UrlDecode(parm[2].Substring(parm[2].IndexOf("=") + 1)); // Post请求的密文数据 // string sReqData = HttpUtils.PostData(); string sReqData = data; string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } Console.Write(sMsg); p.writeSuccess(); // ret==0表示解密成功,sMsg表示解密之后的明文xml串 // TODO: 对明文的处理 // For example: XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); XmlNode root = doc.FirstChild; bool message_stat = false; if (root["MsgType"].InnerText == "text" && !message_stat) { string content = root["Content"].InnerText; string content_from = root["FromUserName"].InnerText; if (content.IndexOf("今天") > -1 && content.IndexOf("应班") > -1 && (content.IndexOf("?") > -1 || content.IndexOf("?") > -1)) { SqlConnection conn = new SqlConnection(); conn.ConnectionString = "server=192.168.8.18;database=my_data;user=sa;pwd=VA4X1abfy76pY"; conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select * from qywx_xxkpb where (pb=DATEDIFF(day,'2020-03-26',getdate())+1 and DATEPART(HOUR,getdate())>=8) or (pb=DATEDIFF(day,'2020-03-26',getdate()) and DATEPART(HOUR,getdate())<8)"; SqlDataReader read1 = cmd.ExecuteReader(); read1.Read(); string huifu = ""; if (read1["userid"].ToString() == content_from) { huifu = "问啥问?就是你!"; } else { huifu = "今天是" + read1["name"].ToString() + "应班"; } ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send(content_from, "", "", huifu, "0"); message_stat = true; } if (qt.Count > 0 && !message_stat) { //foreach (var i in qt) qt.RemoveAll(x => { if (DateTime.Now.Subtract(x.lasttime).TotalSeconds > 180) { return(true); } else { return(false); } }); for (int i = 0; i < qt.Count; i++) { if (content_from == qt[i].user_id) { if (qt[i].title == "yingbanstat1") { if ((content.Trim().Length == 10) || (content.Trim() == "今天") || (content.Trim() == "明天") || (content.Trim() == "后天") || (content.Trim() == "昨天")) { if (content.Trim() == "今天") { content = DateTime.Now.ToString("yyyy-MM-dd"); } if (content.Trim() == "明天") { content = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); } if (content.Trim() == "后天") { content = DateTime.Now.AddDays(2).ToString("yyyy-MM-dd"); } if (content.Trim() == "昨天") { content = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); } SqlConnection conn = new SqlConnection(); conn.ConnectionString = "server=192.168.8.18;database=my_data;user=sa;pwd=VA4X1abfy76pY"; conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("select * from qywx_xxkpb where (pb=DATEDIFF(day,'2020-03-26','{0}')%6+1 )", content); try { SqlDataReader read1 = cmd.ExecuteReader(); read1.Read(); string huifu = ""; if (read1["userid"].ToString() == content_from) { huifu = "问啥问?就是你!"; } else { huifu = content + "是" + read1["name"].ToString() + "应班"; } ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send(content_from, "", "", huifu, "0"); message_stat = true; } catch (Exception) { return; } finally { conn.Close(); } qt.Remove(qt[i]); break; } else { ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send(content_from, "", "", "请注意输入日期格式例如:(2020-01-01)", "0"); } } if (qt[i].title == "txl_qry") { SqlConnection conn = new SqlConnection(); conn.ConnectionString = "server=192.168.8.18;database=my_data;user=sa;pwd=VA4X1abfy76pY"; conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; string sqltext = ""; if (content.IndexOf("姓名") == 0 || content.IndexOf("单位") == 0 || content.IndexOf("标签") == 0) { if (content.IndexOf("姓名") == 0) { sqltext = string.Format(" name like '%{0}%' ", content.Substring(3)); } if (content.IndexOf("单位") == 0) { sqltext = string.Format(" unit like '%{0}%' ", content.Substring(3)); } if (content.IndexOf("标签") == 0) { sqltext = string.Format(" label like '%{0}%' ", content.Substring(3)); } cmd.CommandText = string.Format("select * from qywx_phone where {0}", sqltext); SqlDataReader rder = cmd.ExecuteReader(); ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); if (!rder.HasRows) { h1.App_send(content_from, "", "", "未查询相关通讯录!", "0"); } else { string jg = ""; while (rder.Read()) { jg = jg + string.Format("姓名:{0}; 单位:{1}; 电话:{2}({3}) \n", rder["name"].ToString(), rder["unit"].ToString(), rder["phone"].ToString(), rder["label"].ToString()); } h1.App_send(content_from, "", "", jg, "0"); } qt.Remove(qt[i]); break; } else { ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send(content_from, "", "", "请注意输入查询格式如:(姓名@小明)", "0"); } } } } } if (content == "小明小明") { ConsoleApplication1.Http_send_cardmessage msg = new ConsoleApplication1.Http_send_cardmessage(); msg.title = "闹啥呢?"; msg.description = "请谨慎选择!!!"; msg.task_id = "ASK" + Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString(); msg.btn = new ConsoleApplication1.Http_send_cardmessage.Message_btn[2]; msg.btn[0] = new ConsoleApplication1.Http_send_cardmessage.Message_btn(); msg.btn[0].key = "btn0"; msg.btn[0].name = "查询应班情况"; msg.btn[0].replace_name = "查询应班情况"; msg.btn[0].btncolor = ConsoleApplication1.Http_send_cardmessage.Message_btn.color.blue; msg.btn[0].bold = true; msg.btn[1] = new ConsoleApplication1.Http_send_cardmessage.Message_btn(); msg.btn[1].key = "btn1"; msg.btn[1].name = "通讯录查询"; msg.btn[1].replace_name = "通讯录查询"; msg.btn[1].btncolor = ConsoleApplication1.Http_send_cardmessage.Message_btn.color.blue; msg.btn[1].bold = true; ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send_card(content_from, "", "", msg); } } else { if (root["MsgType"].InnerText == "event") { if (root["EventKey"].InnerText == "btn0") { ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send(root["FromUserName"].InnerText, "", "", "请问查几号应班情况?请输入日期(yyyy-mm-dd)", "0"); for (int i = 0; i < qt.Count; i++) { if (qt[i].user_id == root["FromUserName"].InnerText) { qt.Remove(qt[i]); break; } } Question tmp = new Question(); tmp.title = "yingbanstat1"; tmp.user_id = root["FromUserName"].InnerText; tmp.lasttime = DateTime.Now; qt.Add(tmp); } if (root["EventKey"].InnerText == "btn1") { ConsoleApplication1.Http_send h1 = new ConsoleApplication1.Http_send(); h1.App_send(root["FromUserName"].InnerText, "", "", "请输入查询类容?格式(姓名@XXX\\单位@XXX\\标签@XXX)", "0"); for (int i = 0; i < qt.Count; i++) { if (qt[i].user_id == root["FromUserName"].InnerText) { qt.Remove(qt[i]); break; } } Question tmp = new Question(); tmp.title = "txl_qry"; tmp.user_id = root["FromUserName"].InnerText; tmp.lasttime = DateTime.Now; qt.Add(tmp); } } } }
static void Main(string[] args) { //企业微信后台开发者设置的token, corpID, EncodingAESKey string sToken = "QDG6eK"; string sCorpID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; /* * ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业微信会向验证url发送一个get请求 * 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及企业微信推送过来的随机加密字符串(echostr), * 这一步注意作URL解码。 * 2.验证消息体签名的正确性 * 3.解密出echostr原文,将原文当作Get请求的response,返回给企业微信 * 第2,3步可以用企业微信提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // string sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature"); string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; // string sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp"); string sVerifyTimeStamp = "1409659589"; // string sVerifyNonce = HttpUtils.ParseUrl("nonce"); string sVerifyNonce = "263014780"; // string sVerifyEchoStr = HttpUtils.ParseUrl("echostr"); string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业微信。 // HttpUtils.SetResponse(sEchoStr); /* * ------------使用示例二:对用户回复的消息解密--------------- * 用户回复消息或者点击事件响应时,企业会收到回调消息,此消息是经过企业微信加密之后的密文以post形式发送给企业,密文格式请参考官方文档 * 假设企业收到企业微信的回调消息如下: * 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> * <AgentID><![CDATA[218]]></AgentID> * </xml> * * 企业收到post请求之后应该 1.解析出url上的参数,包括消息体签名(msg_signature),时间戳(timestamp)以及随机数字串(nonce) * 2.验证消息体签名的正确性。 * 3.将post请求的数据进行xml解析,并将<Encrypt>标签的内容进行解密,解密出来的明文即是用户回复消息的明文,明文格式请参考官方文档 * 第2,3步可以用企业微信提供的库函数DecryptMsg来实现。 */ // string sReqMsgSig = HttpUtils.ParseUrl("msg_signature"); string sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6"; // string sReqTimeStamp = HttpUtils.ParseUrl("timestamp"); string sReqTimeStamp = "1409659813"; // string sReqNonce = HttpUtils.ParseUrl("nonce"); string sReqNonce = "1372623149"; // Post请求的密文数据 // string sReqData = HttpUtils.PostData(); // <xml> // <ToUserName><![CDATA[ww7f78b8efd38dc961]]></ToUserName> // <Encrypt><![CDATA[+SBHr/1G0C+ggjFOzw0Eol/1GKvkk3F3qecELKH5UFJoRs76YWTIn8KtGWjvdi1fHqBQS94q01UYsVmDj8Nx4Kjy18Jd6DwOmpyh10IYnXDjfdpMWKTYzbHq7BUCv4B3u2kd6MOb0gQJMPjj8tg2aoFYdds2KSNLzybuHgxFhYi8VeJIE/DhdmudgdVGAxVV1J7GOClpt1xxq1OxzqXpLePz+LohTvqZDtwtiBCdLGVUtXW8Tm+AILQu1ApwIbVIDLLD6GXPaffYPmEZ3qeCpkmRaRy7f1pHaAuGL9lBBQmqnZSZgdJQ8R8fXlVMaZywN6fyXQdexKvIYW2MsWF5szTjXanm2WCq73j8JviVXxjhN6RdQkVv7Wm2ESDcsZHdKrCoXACsyCbCMSVvmrorD+8Kd611X8mn2OdoABXSn/c=]]></Encrypt> // <AgentID><![CDATA[1000002]]></AgentID> //</xml> 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><AgentID><![CDATA[218]]></AgentID></xml>"; string sMsg = ""; // 解析之后的明文 ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 // TODO: 对明文的处理 // For example: XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); XmlNode root = doc.FirstChild; string content = root["Content"].InnerText; System.Console.WriteLine(content); // ... // ... /* * ------------使用示例三:企业回复用户消息的加密--------------- * 企业被动回复用户的消息也需要进行加密,并且拼接成密文格式的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> * <AgentID>128</AgentID> * </xml> * * 为了将此段明文回复给用户,企业应: 1.自己生成时间时间戳(timestamp),随机数字串(nonce)以便生成消息体签名,也可以直接用从企业微信的post url上解析出的对应值。 * 2.将明文加密得到密文。 3.用密文,步骤1生成的timestamp,nonce和企业在企业微信设定的token生成消息体签名。 4.将密文,消息体签名,时间戳,随机数字串拼接成xml格式的字符串,发送给企业。 * 以上2,3,4步可以用企业微信提供的库函数EncryptMsg来实现。 */ // 需要发送的明文 string sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>"; string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } // TODO: // 加密成功,企业需要将加密之后的sEncryptMsg返回 // HttpUtils.SetResponse(sEncryptMsg); return; }
/// <summary> /// 根据响应实体生成回包XML /// </summary> /// <param name="obj">响应实体</param> /// <param name="signature">签名</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">随机串</param> /// <returns></returns> public string GetRspXmlByObj(ResponsedMsg obj) { string nonce = Guid.NewGuid().ToString().Replace("-", ""); string timestamp = TimeStamp.Now().ToString(); var rspStr = ResponsedMsg.GetXmlByObj(obj); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(this._token, this._encodingAESKey, this._corpID); string sEncryptStr = ""; var res = wxcpt.EncryptMsg(rspStr, timestamp, nonce, ref sEncryptStr); if (res == 0) { return sEncryptStr; } return ""; }
public async Task <string> ReceiveMessage(string msg_signature, string timestamp, string nonce, string echostr) { Logger.WriteLog(Utility.Constants.LogLevel.Debug, "微信传入参数", new { msg_signature, timestamp, nonce, echostr }); //企业微信后台开发者设置的token, corpID, EncodingAESKey string sToken = "wKB3j3POS33LqEy2vTEhiTzh"; string sCorpID = "ww1c5ca8f9af6164f4"; string sEncodingAESKey = "sV96P5yUsG64zuAPQqLDgayL4jdvx7HIDJrlMf8jIWf"; var wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); int ret = 0; string result = ""; if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { string sReqData; using (var streamReader = new StreamReader(Request.Body)) { sReqData = await streamReader.ReadToEndAsync(); } Logger.WriteLog(Utility.Constants.LogLevel.Debug, "微信接收数据", sReqData); ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, sReqData, ref result); if (ret != 0) { return("fail"); } Logger.WriteLog(Utility.Constants.LogLevel.Debug, "微信解密数据", result); var gatewayData = new GatewayData(DataFormat.Xml, result); var content = gatewayData.GetValue <string>("Content"); if (!string.IsNullOrEmpty(content)) { var message = ""; if (int.TryParse(content, out int id)) { message = await _userInfoService.GetStockMessageByIdAsync(id); } else { message = await _userInfoService.GetStockTradeByNameAsync(content); } string sRespData = $"<xml><ToUserName><![CDATA[{gatewayData.GetValue<string>("FromUserName")}]]></ToUserName><FromUserName><![CDATA[{sCorpID}]]></FromUserName><CreateTime>{gatewayData.GetValue<string>("CreateTime")}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{message}]]></Content><MsgId>{gatewayData.GetValue<string>("MsgId")}</MsgId><AgentID>{gatewayData.GetValue<string>("AgentID")}</AgentID></xml>"; ret = wxcpt.EncryptMsg(sRespData, timestamp, nonce, ref result); if (ret != 0) { return("fail"); } } } else { ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref result); if (ret != 0) { return("fail"); } } return(result); }
static void Main(string[] args) { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.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; }
/// <summary> /// 验证企业号签名 /// </summary> /// <param name="token">企业号配置的Token</param> /// <param name="signature">签名内容</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">nonce参数</param> /// <param name="corpId">企业号ID标识</param> /// <param name="encodingAESKey">加密键</param> /// <param name="echostr">内容字符串</param> /// <param name="retEchostr">返回的字符串</param> /// <returns></returns> public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(token, encodingAESKey, corpId); int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr); if (result != 0) { return false; } return true; }
static void Main(string[] args) { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.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 string Get(String msg_signature) { //企业微信后台开发者设置的token, corpID, EncodingAESKey string sToken = "QDG6eK"; string sCorpID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; /* * ------------使用示例一:验证回调URL--------------- *企业开启回调模式时,企业微信会向验证url发送一个get请求 * 假设点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 接收到该请求时,企业应 1.解析出Get请求的参数,包括消息体签名(msg_signature),时间戳(timestamp),随机数字串(nonce)以及企业微信推送过来的随机加密字符串(echostr), * 这一步注意作URL解码。 * 2.验证消息体签名的正确性 * 3.解密出echostr原文,将原文当作Get请求的response,返回给企业微信 * 第2,3步可以用企业微信提供的库函数VerifyURL来实现。 */ Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // string sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature"); //string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyMsgSig = msg_signature; // string sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp"); string sVerifyTimeStamp = "1409659589"; // string sVerifyNonce = HttpUtils.ParseUrl("nonce"); string sVerifyNonce = "263014780"; // string sVerifyEchoStr = HttpUtils.ParseUrl("echostr"); string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); //return; } //ret==0表示验证成功,sEchoStr参数表示明文,用户需要将sEchoStr作为get请求的返回参数,返回给企业微信。 // HttpUtils.SetResponse(sEchoStr); return(sEchoStr); /* * ------------使用示例二:对用户回复的消息解密--------------- * 用户回复消息或者点击事件响应时,企业会收到回调消息,此消息是经过企业微信加密之后的密文以post形式发送给企业,密文格式请参考官方文档 * 假设企业收到企业微信的回调消息如下: * 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> * <AgentID><![CDATA[218]]></AgentID> * </xml> * * 企业收到post请求之后应该 1.解析出url上的参数,包括消息体签名(msg_signature),时间戳(timestamp)以及随机数字串(nonce) * 2.验证消息体签名的正确性。 * 3.将post请求的数据进行xml解析,并将<Encrypt>标签的内容进行解密,解密出来的明文即是用户回复消息的明文,明文格式请参考官方文档 * 第2,3步可以用企业微信提供的库函数DecryptMsg来实现。 */ /* * // string sReqMsgSig = HttpUtils.ParseUrl("msg_signature"); * string sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6"; * // string sReqTimeStamp = HttpUtils.ParseUrl("timestamp"); * string sReqTimeStamp = "1409659813"; * // string sReqNonce = HttpUtils.ParseUrl("nonce"); * string sReqNonce = "1372623149"; * // Post请求的密文数据 * // string sReqData = HttpUtils.PostData(); * 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><AgentID><![CDATA[218]]></AgentID></xml>"; * string sMsg = ""; // 解析之后的明文 * ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); * if (ret != 0) * { * System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); * //return; * } * // ret==0表示解密成功,sMsg表示解密之后的明文xml串 * // TODO: 对明文的处理 * // For example: * XmlDocument doc = new XmlDocument(); * doc.LoadXml(sMsg); * XmlNode root = doc.FirstChild; * string content = root["Content"].InnerText; * System.Console.WriteLine(content); * // ... * // ... */ /* * ------------使用示例三:企业回复用户消息的加密--------------- * 企业被动回复用户的消息也需要进行加密,并且拼接成密文格式的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> * <AgentID>128</AgentID> * </xml> * * 为了将此段明文回复给用户,企业应: 1.自己生成时间时间戳(timestamp),随机数字串(nonce)以便生成消息体签名,也可以直接用从企业微信的post url上解析出的对应值。 * 2.将明文加密得到密文。 3.用密文,步骤1生成的timestamp,nonce和企业在企业微信设定的token生成消息体签名。 4.将密文,消息体签名,时间戳,随机数字串拼接成xml格式的字符串,发送给企业。 * 以上2,3,4步可以用企业微信提供的库函数EncryptMsg来实现。 */ /* * // 需要发送的明文 * string sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>"; * string sEncryptMsg = ""; //xml格式的密文 * ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); * if (ret != 0) * { * System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); * //return; * } * // TODO: * // 加密成功,企业需要将加密之后的sEncryptMsg返回 * // HttpUtils.SetResponse(sEncryptMsg); */ }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.AddHeader("pragma", "no-cache"); context.Response.AddHeader("cache-control", ""); context.Response.CacheControl = "no-cache"; string strAction = context.Request["Action"] ?? ""; string UserName = context.Request["UserName"] ?? ""; string strIP = CommonHelp.getIP(context); Msg_Result Model = new Msg_Result() { Action = strAction.ToUpper(), ErrorMsg = "" }; if (!string.IsNullOrEmpty(strAction)) { #region 企业号应用callback if (strAction == "XXJS") { String strCorpID = context.Request["corpid"] ?? ""; string strCode = context.Request["Code"] ?? ""; try { JH_Auth_QY jaq = new JH_Auth_QYB().GetALLEntities().FirstOrDefault(); JH_Auth_Model jam = new JH_Auth_ModelB().GetEntity(p => p.ModelCode == strCode); //if (jaq != null && jam != null && !string.IsNullOrEmpty(jam.TJId)) if (jaq != null && jam != null) { #region POST if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; // 获得客户端RAW HttpRequest StreamReader srResult = new StreamReader(context.Request.InputStream); string str = srResult.ReadToEnd(); XmlDocument XmlDocument = new XmlDocument(); XmlDocument.LoadXml(HttpContext.Current.Server.UrlDecode(str)); string ToUserName = string.Empty; string strde = string.Empty; string msgtype = string.Empty;//微信响应类型 foreach (XmlNode xn in XmlDocument.ChildNodes[0].ChildNodes) { if (xn.Name == "ToUserName") { ToUserName = xn.InnerText; } } var pj = new JH_Auth_WXPJB().GetEntity(p => p.TJID == jam.TJId); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(pj.Token, pj.EncodingAESKey, ToUserName); int n = wxcpt.DecryptMsg(signature, timestamp, nonce, str, ref strde); XmlDocument XmlDocument1 = new XmlDocument(); XmlDocument1.LoadXml(HttpContext.Current.Server.UrlDecode(strde)); foreach (XmlNode xn1 in XmlDocument1.ChildNodes[0].ChildNodes) { if (xn1.Name == "MsgType") { msgtype = xn1.InnerText; } //CommonHelp.WriteLOG(XmlDocument1.OuterXml); } if (msgtype == "event")//处理事件 { //需要处理进入应用的菜单更改事件 string strEvent = XmlDocument1.ChildNodes[0]["Event"].InnerText; string strUserName = XmlDocument1.ChildNodes[0]["FromUserName"].InnerText; string strAgentID = XmlDocument1.ChildNodes[0]["AgentID"].InnerText; string strEventKey = XmlDocument1.ChildNodes[0]["EventKey"].InnerText; if (strEvent.ToLower() == "enter_agent" || strEvent.ToLower() == "view") { //进入应用和点击菜单 //JH_Auth_User jau = new JH_Auth_UserB().GetEntity(p => p.ComId == jaq.ComId && p.UserName == strUserName); //JH_Auth_QY_Model jhqm = new JH_Auth_QY_ModelB().GetEntity(p => p.ComId == jaq.ComId && p.AgentId == strAgentID); //if (jau != null && jhqm != null) //{ // JH_Auth_YYLog jay = new JH_Auth_YYLog(); // jay.ComId = jaq.ComId; // jay.AgentID = strAgentID; // jay.CorpID = strCorpID; // jay.CRDate = DateTime.Now; // jay.CRUser = strUserName; // jay.Event = strEvent; // jay.EventKey = strEventKey; // jay.ModelCode = strCode; // jay.ModelID = jhqm.ModelID; // jay.QYName = jaq.QYName; // jay.TJID = jam.TJId; // jay.Type = msgtype; // jay.UserName = strUserName; // jay.UserRealName = jau.UserRealName; // new JH_Auth_YYLogB().Insert(jay); // if (strEvent.ToLower() == "enter_agent") // { // var jays = new JH_Auth_YYLogB().GetEntities(p => p.ComId == jaq.ComId && p.Event == "enter_agent" && p.AgentID == strAgentID && p.CRUser == strUserName); // if (jays.Count() <= 1) // { // } // } //} } } if (new List <string> { "text", "image", "voice", "video", "shortvideo", "link" }.Contains(msgtype)) //处理消息事件 { if (XmlDocument1.ChildNodes.Count > 0) { JH_Auth_WXMSG wxmsgModel = new JH_Auth_WXMSG(); wxmsgModel.AgentID = int.Parse(XmlDocument1.ChildNodes[0]["AgentID"].InnerText); wxmsgModel.ComId = jaq.ComId; wxmsgModel.ToUserName = XmlDocument1.ChildNodes[0]["ToUserName"].InnerText; wxmsgModel.FromUserName = XmlDocument1.ChildNodes[0]["FromUserName"].InnerText; wxmsgModel.CRDate = DateTime.Now; wxmsgModel.CRUser = XmlDocument1.ChildNodes[0]["FromUserName"].InnerText; wxmsgModel.MsgId = XmlDocument1.ChildNodes[0]["MsgId"].InnerText; wxmsgModel.MsgType = msgtype; wxmsgModel.ModeCode = strCode; wxmsgModel.Tags = "微信收藏"; switch (msgtype) { case "text": wxmsgModel.MsgContent = XmlDocument1.ChildNodes[0]["Content"].InnerText; break; case "image": wxmsgModel.PicUrl = XmlDocument1.ChildNodes[0]["PicUrl"].InnerText; wxmsgModel.MediaId = XmlDocument1.ChildNodes[0]["MediaId"].InnerText; break; case "voice": wxmsgModel.MediaId = XmlDocument1.ChildNodes[0]["MediaId"].InnerText; wxmsgModel.Format = XmlDocument1.ChildNodes[0]["Format"].InnerText; break; case "video": wxmsgModel.MediaId = XmlDocument1.ChildNodes[0]["MediaId"].InnerText; wxmsgModel.ThumbMediaId = XmlDocument1.ChildNodes[0]["ThumbMediaId"].InnerText; break; case "shortvideo": wxmsgModel.MediaId = XmlDocument1.ChildNodes[0]["MediaId"].InnerText; wxmsgModel.ThumbMediaId = XmlDocument1.ChildNodes[0]["ThumbMediaId"].InnerText; break; case "link": wxmsgModel.Description = XmlDocument1.ChildNodes[0]["Description"].InnerText; wxmsgModel.Title = XmlDocument1.ChildNodes[0]["Title"].InnerText; wxmsgModel.URL = XmlDocument1.ChildNodes[0]["Url"].InnerText; wxmsgModel.PicUrl = XmlDocument1.ChildNodes[0]["PicUrl"].InnerText; break; } if (new List <string>() { "link", "text" }.Contains(msgtype)) { if (msgtype == "link") { var jaw = new JH_Auth_WXMSGB().GetEntity(p => p.ComId == jaq.ComId && p.MsgId == wxmsgModel.MsgId); if (jaw == null) { string strMedType = ".jpg"; JH_Auth_UserB.UserInfo UserInfo = new JH_Auth_UserB.UserInfo(); UserInfo = new JH_Auth_UserB().GetUserInfo(jaq.ComId, wxmsgModel.FromUserName); string fileID = CommonHelp.ProcessWxIMGUrl(wxmsgModel.PicUrl, UserInfo, strMedType); wxmsgModel.FileId = fileID; new JH_Auth_WXMSGB().Insert(wxmsgModel); if (strCode == "TSSQ") { SZHL_TXSX tx1 = new SZHL_TXSX(); tx1.ComId = jaq.ComId; tx1.APIName = "TSSQ"; tx1.MsgID = wxmsgModel.ID.ToString(); tx1.FunName = "SENDWXMSG"; tx1.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); tx1.CRUser = wxmsgModel.CRUser; tx1.CRDate = DateTime.Now; TXSX.TXSXAPI.AddALERT(tx1); //时间为发送时间 } } } else { new JH_Auth_WXMSGB().Insert(wxmsgModel); } } if (!string.IsNullOrEmpty(wxmsgModel.MediaId)) { var jaw = new JH_Auth_WXMSGB().GetEntity(p => p.ComId == jaq.ComId && p.MediaId == wxmsgModel.MediaId); if (jaw == null) { string strMedType = ".jpg"; if (strCode == "QYWD" || strCode == "CRM") //判断模块 { if (msgtype == "shortvideo" || msgtype == "video") //视频,小视频 { strMedType = ".mp4"; } if (new List <string>() { "image", "shortvideo", "video", "voice" }.Contains(msgtype)) //下载到本地服务器 { JH_Auth_UserB.UserInfo UserInfo = new JH_Auth_UserB.UserInfo(); UserInfo = new JH_Auth_UserB().GetUserInfo(jaq.ComId, wxmsgModel.FromUserName); string fileID = CommonHelp.ProcessWxIMG(wxmsgModel.MediaId, strCode, UserInfo, strMedType); wxmsgModel.FileId = fileID; new JH_Auth_WXMSGB().Insert(wxmsgModel); } } } } } } } #endregion #region GET if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET") { Auth(jam.Token, jam.EncodingAESKey, jaq.corpId); } #endregion } } catch (Exception ex) { Model.ErrorMsg = ex.ToString(); CommonHelp.WriteLOG(ex.ToString()); } } #endregion #region 企业会话 if (strAction == "QYIM") { if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { string corpId = context.Request["corpid"] ?? ""; try { JH_Auth_QY jaq = new JH_Auth_QYB().GetEntity(p => p.corpId == corpId); if (jaq != null) { string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; // 获得客户端RAW HttpRequest StreamReader srResult = new StreamReader(context.Request.InputStream); string str = srResult.ReadToEnd(); string strde = string.Empty; var pj = new JH_Auth_WXPJB().GetEntity(p => p.TJID == "tj7882b1f8bc56f05f"); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(pj.Token, pj.EncodingAESKey, corpId); wxcpt.DecryptMsg(signature, timestamp, nonce, str, ref strde); //string strde = HttpContext.Current.Request.QueryString[0]; XmlDocument XmlDocument = new XmlDocument(); XmlDocument.LoadXml(HttpContext.Current.Server.UrlDecode(strde)); string AgentType = string.Empty; string ToUserName = string.Empty; string ItemCount = string.Empty; string PackageId = string.Empty; string Item = string.Empty; #region XML文档处理 foreach (XmlNode xn in XmlDocument.ChildNodes[0].ChildNodes) { if (xn.Name == "AgentType") { AgentType = xn.InnerText; } if (xn.Name == "ToUserName") { ToUserName = xn.InnerText; } if (xn.Name == "ItemCount") { ItemCount = xn.InnerText; } if (xn.Name == "PackageId") { PackageId = xn.InnerText; } if (xn.Name == "Item") { Item += xn.InnerXml; string MsgType = xn.ChildNodes[2].InnerText; if (MsgType == "event") { } else if (new List <string> { "text", "image", "voice", "file", "link" }.Contains(MsgType)) { #region 内容处理 #endregion } } } #endregion HttpContext.Current.Response.Write(PackageId); HttpContext.Current.Response.End(); } } catch (Exception ex) { CommonHelp.WriteLOG("QYIM:" + ex.ToString() + "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } } } #endregion #region 获取唯一code if (strAction.ToUpper() == "GetUserCodeByCode".ToUpper()) { #region 获取Code Model.ErrorMsg = "获取Code错误,请重试"; string strCode = context.Request["code"] ?? ""; string strCorpID = context.Request["corpid"] ?? ""; string strModelCode = context.Request["funcode"] ?? ""; if (!string.IsNullOrEmpty(strCode)) { var qy = new JH_Auth_QYB().GetEntity(p => p.corpId == strCorpID); if (qy != null) { try { //通过微信接口获取用户名 WXHelp wx = new WXHelp(qy); string username = wx.GetUserDataByCode(strCode, strModelCode); if (!string.IsNullOrEmpty(username)) { var jau = new JH_Auth_UserB().GetUserByUserName(qy.ComId, username); if (jau != null) { //如果PCCode为空或者超过60分钟没操作,统统重新生成PCCode,并更新最新操作时间 if (jau.logindate == null) { jau.logindate = DateTime.Now; } TimeSpan ts = new TimeSpan(jau.logindate.Value.Ticks).Subtract(new TimeSpan(DateTime.Now.Ticks)).Duration(); if (string.IsNullOrEmpty(jau.pccode) || ts.TotalMinutes > 60) { string strGuid = CommonHelp.CreatePCCode(jau); jau.pccode = strGuid; jau.logindate = DateTime.Now; new JH_Auth_UserB().Update(jau); } Model.ErrorMsg = ""; Model.Result = jau.pccode; Model.Result1 = jau.UserName; Model.Result2 = ts.TotalMinutes; } } else { Model.ErrorMsg = "当前用户不存在"; } } catch (Exception ex) { Model.ErrorMsg = ex.ToString(); } } else { Model.ErrorMsg = "当前企业号未在电脑端注册"; } } else { Model.ErrorMsg = "Code为空"; } #endregion } #endregion #region 是否存在 if (strAction.ToUpper() == "isexist".ToUpper()) { string strcorpid = context.Request["corpid"] ?? ""; if (strcorpid != "") { var qy = new JH_Auth_QYB().GetEntity(p => p.corpId == strcorpid); if (qy == null) { Model.ErrorMsg = "当前企业号未注册此平台"; } else { if (context.Request.Cookies["szhlcode"] != null) { //通过Cookies获取Code //string szhlcode = "5ab470be-4988-4bb3-9658-050481b98fca"; string szhlcode = context.Request.Cookies["szhlcode"].Value.ToString(); //通过Code获取用户名,然后执行接口方法 var jau = new JH_Auth_UserB().GetUserByPCCode(szhlcode); if (jau == null) { Model.ErrorMsg = "用户Code不存在"; } else { if (new JH_Auth_QYB().GetEntity(d => d.ComId == jau.ComId.Value).corpId != strcorpid) { Model.ErrorMsg = "企业需要重新选择"; } //重写CODE } } } } else { Model.ErrorMsg = "企业号连接有误,请重新连接"; } } #endregion #region 发送提醒 if (strAction.ToUpper() == "AUTOALERT") { TXSX.TXSXAPI.AUTOALERT(); } #endregion } else { #region 获取SuiteTicket if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; // 获得客户端RAW HttpRequest StreamReader srResult = new StreamReader(context.Request.InputStream); string str = srResult.ReadToEnd(); XmlDocument XmlDocument = new XmlDocument(); XmlDocument.LoadXml(HttpContext.Current.Server.UrlDecode(str)); string ToUserName = string.Empty; string Encrypt = string.Empty; string strde = string.Empty; string strinfotype = string.Empty; foreach (XmlNode xn in XmlDocument.ChildNodes[0].ChildNodes) { if (xn.Name == "ToUserName") { ToUserName = xn.InnerText; } if (xn.Name == "Encrypt") { Encrypt = xn.InnerText; } } var pj = new JH_Auth_WXPJB().GetEntity(p => p.TJID == ToUserName); Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(pj.Token, pj.EncodingAESKey, ToUserName); int n = wxcpt.DecryptMsg(signature, timestamp, nonce, str, ref strde); string strtct = string.Empty; string strSuiteId = string.Empty; string strtAuthCorpId = string.Empty; XmlDocument XmlDocument1 = new XmlDocument(); XmlDocument1.LoadXml(HttpContext.Current.Server.UrlDecode(strde)); foreach (XmlNode xn1 in XmlDocument1.ChildNodes[0].ChildNodes) { if (xn1.Name == "SuiteId") { strSuiteId = xn1.InnerText; } if (xn1.Name == "SuiteTicket") { strtct = xn1.InnerText; } if (xn1.Name == "InfoType") { strinfotype = xn1.InnerText; } if (xn1.Name == "AuthCorpId") { strtAuthCorpId = xn1.InnerText; } } if (strinfotype == "suite_ticket") { pj.Ticket = strtct; new JH_Auth_WXPJB().Update(pj); } HttpContext.Current.Response.Write("success"); HttpContext.Current.Response.End(); } #endregion } IsoDateTimeConverter timeConverter = new IsoDateTimeConverter(); timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; string Result = JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented, timeConverter).Replace("null", "\"\""); context.Response.Write(Result); }
public void ProcessRequest(HttpContext param_context) { HttpContext.Current.Response.ContentType = "text/plain"; // string postString = string.Empty; string postString = ""; if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { using (Stream stream = HttpContext.Current.Request.InputStream) { Byte[] postBytes = new Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); // postString = Encoding.UTF8.GetString(postBytes); postString = Encoding.Default.GetString(postBytes); //Handle(postString); //接收xml数据包后解密 string PostData = postString; string sToken = "D2op9SR8HV4U5vVL7p1bKFm2fjLdXV8"; string sCorpID = "wx4fbb38c93e921603"; string sEncodingAESKey = "vQrIN6MevZ2RJekY79C0RC19Fe4KNcvI6UM4IQvGeWq"; Tencent.WXBizMsgCrypt Msg = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); int ret = 0; string sMsg = ""; string MsgSig = HttpContext.Current.Request.QueryString["msg_signature"]; string TimeStamp = HttpContext.Current.Request.QueryString["timestamp"]; string Nonce = HttpContext.Current.Request.QueryString["nonce"]; ret = Msg.DecryptMsg(MsgSig, TimeStamp, Nonce, PostData, ref sMsg); //System.Console.WriteLine(sMsg); //将解析后的Xml数据写入文件 // string txt = sMsg; StreamWriter sw = new StreamWriter(@"E:\程序库\Data1.txt"); sw.WriteLine(sMsg); sw.Flush(); sw.Close(); AnalyzeXml(sMsg);//解析Xml消息 Reply_Msg(TimeStamp, Nonce, sMsg, Choose_EventKey);//回复消息 // Handle(sMsg); } } else { //获取Access_token令牌 // createMenu Get_access = new createMenu(); // Access_tok = Get_access.Get_Access_token("wx4fbb38c93e921603", "O1Ftul_DfvuGJwzZOmUKfGCGJBollEvDk-RqFjxuthumfN3HDbpnareA8mK7LShA"); // Uploadfile("E:\\weixin_api\\pic\\002.jpg", Access_tok, "image"); // Uploadfile("E:\\weixin_api\\music\\001.mp3", Access_tok, "voice"); // Uploadfile("E:\\weixin_api\\video\\001.mp4", Access_tok, "video"); //param_context.Response.Write(HttpContext.Current.Response.ContentType);//表示服务器正在运行 //InterfaceTest();//订阅号验证成为开发者 //团队号验证回调模式 string sToken = "D2op9SR8HV4U5vVL7p1bKFm2fjLdXV8"; string sCorpID = "wx4fbb38c93e921603"; string sEncodingAESKey = "vQrIN6MevZ2RJekY79C0RC19Fe4KNcvI6UM4IQvGeWq"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string VerifyMsgSig = HttpContext.Current.Request.QueryString["msg_signature"]; string VerifyTimeStamp = HttpContext.Current.Request.QueryString["timestamp"]; string VerifyNonce = HttpContext.Current.Request.QueryString["nonce"]; string VerifyEchoStr = HttpContext.Current.Request.QueryString["echoStr"]; string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = "263014780"; string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; if (VerifyEchoStr != null) { sVerifyMsgSig = VerifyMsgSig; sVerifyTimeStamp = VerifyTimeStamp; sVerifyNonce = VerifyNonce; sVerifyEchoStr = VerifyEchoStr; } int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return; } } }
protected void Page_Load(object sender, EventArgs e) { string sql = "select * from asm_platformInfo"; DT = DbHelperSQL.Query(sql).Tables[0]; #region 获取并解析ticket //log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//获取一个日志记录器 //log.Info(DateTime.Now.ToString() + ":" + "*************进来了*************");//写入一条新log //1-获取回传加密数据、签名字符串、时间戳、随机字符串 byte[] data = Request.BinaryRead(Request.TotalBytes); string postData = Encoding.Default.GetString(data); string sReqMsgSig = Request.QueryString["msg_signature"]; //签名字符串encrypt_type string sReqTimeStamp = Request.QueryString["timestamp"]; //时间戳 string sReqNonce = Request.QueryString["nonce"]; //获取随机字符串 Util.Debuglog("postData=" + postData + ";sReqMsgSig=" + sReqMsgSig + ";sReqTimeStamp=" + sReqTimeStamp + ";sReqNonce=" + sReqNonce, "_getTicket.txt"); if (string.IsNullOrEmpty(postData) || string.IsNullOrEmpty(sReqMsgSig) || string.IsNullOrEmpty(sReqTimeStamp) || string.IsNullOrEmpty(sReqNonce)) { //postData = DT.Rows[0]["postData"].ToString(); //sReqMsgSig = DT.Rows[0]["sReqMsgSig"].ToString(); //sReqTimeStamp = DT.Rows[0]["sReqTimeStamp"].ToString(); //sReqNonce = DT.Rows[0]["sReqNonce"].ToString(); string updateSQL = "update asm_platformInfo set postData='" + postData + "',sReqMsgSig='" + sReqMsgSig + "',sReqTimeStamp='" + sReqTimeStamp + "',sReqNonce='" + sReqNonce + "'"; Util.Debuglog("updateSQL=" + updateSQL, "_getTicket.txt"); DbHelperSQL.ExecuteSql(updateSQL); } else { //RedisHelper.SetRedisModel("postData", postData, new TimeSpan(1, 0, 0)); //RedisHelper.SetRedisModel("sReqMsgSig", sReqMsgSig, new TimeSpan(1, 0, 0)); //RedisHelper.SetRedisModel("sReqTimeStamp", sReqTimeStamp, new TimeSpan(1, 0, 0)); //RedisHelper.SetRedisModel("sReqNonce", sReqNonce, new TimeSpan(1, 0, 0)); string updateSQL = "update asm_platformInfo set postData='" + postData + "',sReqMsgSig='" + sReqMsgSig + "',sReqTimeStamp='" + sReqTimeStamp + "',sReqNonce='" + sReqNonce + "'"; Util.Debuglog("updateSQL=" + updateSQL, "_getTicket.txt"); DbHelperSQL.ExecuteSql(updateSQL); } //2-开放平台上设置的token, appID, EncodingAESKey string sToken = OpenPFConfig.Token; string sAppID = OpenPFConfig.Appid; string sEncodingAESKey = OpenPFConfig.AESKey; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); string sMsg = ""; //解析之后的明文 #region 测试用的代码 #endregion int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, postData.Replace(" ", "").Replace("\n", ""), ref sMsg); //if (ret != 0) //{ // log.Info("ERR: 解析失败, ret: " + ret); //} //else //{ // log.Info(ret + "----" + sMsg); //} XDocument xDoc = XDocument.Parse(sMsg.Replace(" ", "")); List <XElement> q = (from c in xDoc.Elements() select c).ToList(); string component_verify_ticket = q.Elements("ComponentVerifyTicket").First().Value; #endregion //将ticket存入Redis string ticket = component_verify_ticket.Split(new string[] { "@@@" }, StringSplitOptions.RemoveEmptyEntries)[1].Replace(" ", ""); string update = "update asm_platformInfo set ticket='" + ticket + "'"; DbHelperSQL.ExecuteSql(update); Response.Write("SUCCESS"); }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); string sToken = "PerformanceHandler"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx4fe8b74e01fffcbb"; string sEncodingAESKey = "U7gOrkwP22ND4bIHSxU0WJqIestRcG2QroykyVKDUSG"; // string sToken = Properties.Settings.Default.Wechat_AgentFee_Token;//"AgentFee"; // string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; // string sEncodingAESKey = Properties.Settings.Default.Wechat_AgentFee_EncodingAESKey;// "he8dYrZ5gLbDrDhfHVJkea1AfmHgRZQJq47kuKpQrSO"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); // 需要发送的明文 String actionType = wechatMessage.EventKey; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); // string sRespData = "<MsgId>1234567890123456</MsgId>"; logger.Info("EventKey: " + wechatMessage.EventKey); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Performance; wechatQueryLog.subSystem = "业绩查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } if (agentWechatAccount != null && !String.IsNullOrEmpty(agentWechatAccount.status) && !agentWechatAccount.status.Equals("Y")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "对不起,你的账号已被停用,请联系联通工作人员!\n\n"); } else if (agentWechatAccount == null) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "用户不存在,请联系联通工作人员!\n\n"); } else { String agentNo = agentWechatAccount.branchNo; if (String.IsNullOrEmpty(agentNo)) { agentNo = agentWechatAccount.agentNo; } String agentType = agentWechatAccount.type; AgentMonthPerformanceDao agentMonthPerformanceDao = new ChinaUnion_DataAccess.AgentMonthPerformanceDao(); AgentDailyPerformanceDao agentDailyPerformanceDao = new ChinaUnion_DataAccess.AgentDailyPerformanceDao(); AgentStarDao agentStarDao = new AgentStarDao(); IList<AgentStar> agentStarList = null; AgentScoreDao agentScoreDao = new AgentScoreDao(); IList<AgentScore> agentScoreList = null; String dateTime = ""; DateTime dt = DateTime.Now.AddMonths(-3); //当前时间 DateTime startQuarter = dt.AddMonths(0 - (dt.Month - 1) % 3).AddDays(1 - dt.Day); //本季度初 if (startQuarter.Month >= 1 && startQuarter.Month <= 3) { dateTime = startQuarter.Year + "年第一季度"; } if (startQuarter.Month >= 4 && startQuarter.Month <= 6) { dateTime = startQuarter.Year + "年第二季度"; } if (startQuarter.Month >= 7 && startQuarter.Month <= 9) { dateTime = startQuarter.Year + "年第三季度"; } if (startQuarter.Month >= 10 && startQuarter.Month <= 12) { dateTime = startQuarter.Year + "年第四季度"; } logger.Info("agentNo: " + agentNo); logger.Info("agentType: " + agentType); switch (actionType) { case "curQuaterStar": case "HistoryQuaterStar": if (actionType.Equals("curQuaterStar")) { agentStarList = agentStarDao.GetLatestByKeyword(agentNo, dateTime); } if (actionType.Equals("HistoryQuaterStar")) { agentStarList = agentStarDao.GetListByKeyword(agentNo); } if (agentStarList != null && agentStarList.Count > 0) { logger.Info("Exist Record: " + agentStarList.Count); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); StringBuilder sbContent = new StringBuilder(); sbContent.AppendFormat("星级查询详情").Append("\n"); for (int i = 0; i < agentStarList.Count;i++ ) { AgentStar agentStar = agentStarList[i]; sbContent.AppendFormat("\n时间:{0}", agentStar.dateTime).Append("\n"); // sbContent.AppendFormat("代理商编号:{0}", agentStar.agentNo).Append("\n"); //sbContent.AppendFormat("代理商名称:{0}", agentStar.agentName).Append("\n"); if (!String.IsNullOrEmpty(agentStar.branchNo)) { sbContent.AppendFormat("渠道编码:{0}", agentStar.branchNo).Append("\n"); sbContent.AppendFormat("渠道名称:{0}", agentStar.branchName).Append("\n"); } sbContent.AppendFormat("星级:{0}", agentStar.star).Append("\n"); } sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", sbContent.ToString()); // sb.Append(sbContent.ToString()); // sb.Append(this.createNewsMessages(feeDate, wechatMessage.FromUserName, agentDailyPerformance)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "本期无星级或尚未发布,请耐心等候\n\n"); } WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Performance; wechatQueryLog.subSystem = "星级查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = dateTime; wechatQueryLog.wechatId = agentNo; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } break; case "curScore": case "HistoryScore": String month = DateTime.Now.AddMonths(-1).ToString("yyyyMM"); if (actionType.Equals("curScore")) { agentScoreList = agentScoreDao.GetLatestByKeyword(agentNo, month); } if (actionType.Equals("HistoryScore")) { agentScoreList = agentScoreDao.GetListByKeyword(agentNo); } if (agentScoreList != null && agentScoreList.Count > 0) { logger.Info("Exist Record: " + agentScoreList.Count); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); StringBuilder sbContent = new StringBuilder(); sbContent.AppendFormat("积分查询详情").Append("\n"); for (int i = 0; i < agentScoreList.Count; i++) { AgentScore agentScore = agentScoreList[i]; sbContent.AppendFormat("\n时间:{0}", agentScore.dateTime).Append("\n"); if (!String.IsNullOrEmpty(agentScore.agentNo)) { sbContent.AppendFormat("代理商编号:{0}", agentScore.agentNo).Append("\n"); sbContent.AppendFormat("代理商名称:{0}", agentScore.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentScore.branchNo)) { sbContent.AppendFormat("渠道编码:{0}", agentScore.branchNo).Append("\n"); sbContent.AppendFormat("渠道名称:{0}", agentScore.branchName).Append("\n"); } sbContent.AppendFormat("渠道积分:{0}", agentScore.score).Append("\n"); sbContent.AppendFormat("本月得分:{0}", agentScore.standardScore).Append("\n"); } sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", sbContent.ToString()); // sb.Append(sbContent.ToString()); // sb.Append(this.createNewsMessages(feeDate, wechatMessage.FromUserName, agentDailyPerformance)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "本期无积分或尚未发布,请耐心等候\n\n"); } wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Performance; wechatQueryLog.subSystem = "积分查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = month; wechatQueryLog.wechatId = agentNo; wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } break; case "YesterdayPerformance": String feeDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); AgentDailyPerformance agentDailyPerformance = new AgentDailyPerformance(); agentDailyPerformance = agentDailyPerformanceDao.GetSummary(agentNo, feeDate,agentType); if (agentDailyPerformance != null) { logger.Info("Exist Record: " + agentNo); sb.Append(this.createNewsMessages(feeDate, agentNo, agentDailyPerformance, agentType)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", DateTime.Now.AddDays(-1).ToString("yyyy年MM月dd日") + "无业绩或者业绩尚未发布\n\n"); } break; case "HistoryDayPerformance": String date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd"); IList<AgentDailyPerformance> agentDailyPerformanceList = agentDailyPerformanceDao.GetAllListDate(agentNo, agentType,date); if (agentDailyPerformanceList == null || agentDailyPerformanceList.Count == 0) { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "近期无业绩或者业绩尚未发布!\n\n"); } else { sb.Append(this.createNewsMessages(agentNo, agentDailyPerformanceList, agentType)); } break; case "LastMonthPerformance": // case "YesterdayPerformance": String feeMonth = DateTime.Now.AddMonths(-1).ToString("yyyy-MM"); AgentMonthPerformance agentMonthPerformance = new AgentMonthPerformance(); agentMonthPerformance = agentMonthPerformanceDao.GetSummary(agentNo, feeMonth, agentType); if (agentMonthPerformance != null) { logger.Info("Exist Record: " + agentMonthPerformance.agentName); sb.Append(this.createNewsMessages(feeMonth, agentNo, agentMonthPerformance, agentType)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", feeMonth.Substring(0,4)+"年"+feeMonth.Substring(5,2)+ "月" + "业绩尚未发布,请耐心等待!\n\n"); } break; case "HistoryMonthPerformance": IList<AgentMonthPerformance> agentMonthPerformanceList = agentMonthPerformanceDao.GetAllListMonth(agentNo,agentType); if (agentMonthPerformanceList == null || agentMonthPerformanceList.Count == 0) { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "近期业绩尚未发布,请耐心等待!\n\n"); } else { sb.Append(this.createNewsMessages(agentNo, agentMonthPerformanceList, agentType)); } break; } } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("sRespData=" + sRespData); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); string sToken = "ContactUsHandler"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx4fe8b74e01fffcbb"; string sEncodingAESKey = "Mh5NDLXhiRMu1GHitnufvEZKBdSh6c1zvOZbpdUOT2T"; // string sToken = Properties.Settings.Default.Wechat_AgentFee_Token;//"AgentFee"; // string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; // string sEncodingAESKey = Properties.Settings.Default.Wechat_AgentFee_EncodingAESKey;// "he8dYrZ5gLbDrDhfHVJkea1AfmHgRZQJq47kuKpQrSO"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); // 需要发送的明文 String actionType = wechatMessage.EventKey; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); // string sRespData = "<MsgId>1234567890123456</MsgId>"; logger.Info("EventKey: " + wechatMessage.EventKey); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Contact; wechatQueryLog.subSystem = "联系人查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } if (agentWechatAccount != null && !String.IsNullOrEmpty(agentWechatAccount.status) && !agentWechatAccount.status.Equals("Y")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "对不起,你的账号已被停用,请联系联通工作人员!\n\n"); } else if (agentWechatAccount == null) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "用户不存在,请联系联通工作人员!\n\n"); } else { String agentNo = agentWechatAccount.branchNo; if (String.IsNullOrEmpty(agentNo)) { agentNo = agentWechatAccount.agentNo; } AgentContactDao agentContactDao = new ChinaUnion_DataAccess.AgentContactDao(); switch (actionType) { case "CommonPhone": sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); StringBuilder sbContent1 = new StringBuilder(); sbContent1.AppendFormat("1、支撑服务热线:4006186802").AppendLine(); sbContent1.AppendFormat("2、服务监督电话:61587555").AppendLine(); sbContent1.AppendFormat("3、IT服务热线:\n 18502143773\n 18502143774"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", sbContent1.ToString()); break; case "ContactPerson": //AgentContact agentContact = new AgentContact(); IList<AgentContact> agentContactList = agentContactDao.GetListByNo(agentNo); if (agentContactList != null && agentContactList.Count > 0) { logger.Info("Exist Record: " + agentContactList.Count); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); StringBuilder sbContent = new StringBuilder(); for (int i = 0; i < agentContactList.Count; i++) { AgentContact agentContact = agentContactList[i]; if (agentContactList.Count > 1) { sbContent.AppendFormat("第{0}联系人\n\n", i + 1); } if (!String.IsNullOrEmpty(agentContact.agentNo)) { sbContent.AppendFormat("代理商编号:{0}", agentContact.agentNo).Append("\n"); sbContent.AppendFormat("代理商名称:{0}", agentContact.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentContact.branchNo)) { sbContent.AppendFormat("渠道编码:{0}", agentContact.branchNo).Append("\n"); sbContent.AppendFormat("渠道名称:{0}", agentContact.branchName).Append("\n"); } sbContent.AppendFormat("所属区县:{0}", agentContact.area).Append("\n"); sbContent.AppendFormat("所属网格:{0}", agentContact.zone).Append("\n"); sbContent.AppendFormat("联系人:{0}", agentContact.contactName).Append("\n"); sbContent.AppendFormat("电话:{0}", agentContact.contactTel).Append("\n"); sbContent.AppendFormat("邮箱:{0}", agentContact.contactEmail).Append("\n").AppendLine(); } sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", sbContent.ToString()); // sb.Append(sbContent.ToString()); // sb.Append(this.createNewsMessages(feeDate, wechatMessage.FromUserName, agentDailyPerformance)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "没有找到对应的联系人,请直接与上海联通确认!\n\n"); } break; } } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); }
static void Main(string[] args) { //公众平台上开发者设置的token, corpID, EncodingAESKey string sToken = "QDG6eK"; string sCorpID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); /* * 假定公众平台上开发者设置的Token * 1. 验证回调URL * 点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * 接收到该请求时,企业应1.先验证签名的正确性 2. 解密出echostr原文。 * 以上两步用verifyURL完成 */ //解析出url上的参数值如下: string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = "263014780"; string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); string input3 = System.Console.ReadLine(); return; } System.Console.WriteLine(sEchoStr); /* 2. 对用户回复的数据进行解密。 * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息: * 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> * <AgentID><![CDATA[218]]></AgentID> * </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><AgentID><![CDATA[218]]></AgentID></xml>"; string sMsg = ""; //解析之后的明文 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); /* * 3. 企业回复用户消息也需要加密和拼接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> * <AgentID>128</AgentID> * </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><AgentID>128</AgentID></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 async Task Index() { String respContent = "Error: 非法请求"; string signature = HttpContext.Request.Query["signature"]; string timestamp = HttpContext.Request.Query["timestamp"]; string nonce = HttpContext.Request.Query["nonce"]; string echostr = HttpContext.Request.Query["echostr"]; string openid = HttpContext.Request.Query["openid"]; //用于验证加密内容的签名 string msg_signature = HttpContext.Request.Query["msg_signature"]; string encrypt_type = HttpContext.Request.Query["encrypt_type"]; Logger.WriteLogAsync("请求方式:" + HttpContext.Request.Method.ToUpper() + ",请求原地址:" + HttpContext.Request.GetAbsoluteUri().ToString()); //验证消息是否来自微信服务器 if (WeChatBase.CheckSignature(signature, timestamp, nonce)) { if (HttpContext.Request.Method.ToUpper() == "GET") { if (!string.IsNullOrEmpty(echostr)) { respContent = echostr; } } else if (HttpContext.Request.Method.ToUpper() == "POST") { respContent = "Error: 处理失败"; try { //采用流的方式去读数据会出现问题,故改用循环读取字节 List <Byte> reqContent = new List <Byte>(); int readInt = -1; while ((readInt = Request.Body.ReadByte()) != -1) { reqContent.Add((Byte)readInt); } Byte[] postBytes = reqContent.ToArray(); string beforeReqData = WeChatBase.WxEncoding.GetString(postBytes); if (!string.IsNullOrEmpty(beforeReqData)) { if (encrypt_type is string a && a.Equals("aes"))//(WeChatBase.IsSecurity) { Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(WeChatBase.WxToken, WeChatBase.WxEncodingAESKey, WeChatBase.WxAppId); string afterReqData = String.Empty; //解析之后的明文 int reqRet = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, beforeReqData, ref afterReqData); if (reqRet == 0) { WxMessageHelp wxMsgHelp = new WxMessageHelp(); String retMessage = wxMsgHelp.MessageHandle(afterReqData); string respData = String.Empty; //xml格式的密文 int resqRet = wxcpt.EncryptMsg(retMessage, timestamp, nonce, ref respData); if (resqRet == 0) { respContent = respData; } else { Logger.WriteLogAsync("Error:接收微信服务器推送的消息,加密报文失败,ret: " + resqRet); } } else { Logger.WriteLogAsync("Error:接收微信服务器推送的消息,解密报文失败,ret: " + reqRet); } } else { WxMessageHelp wxMsgHelp = new WxMessageHelp(); String retMessage = wxMsgHelp.MessageHandle(beforeReqData); respContent = retMessage; } } }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); // string sToken = "AgentFee"; // string sCorpID = "wx4fe8b74e01fffcbb"; // string sEncodingAESKey = "gvGJnhpjeljcKzvfe8B8vnmMBBLkJFuzUYSjsGcDQFE"; string sToken ="AgentFeeAndInvoicePaymentHandler";//"AgentFee"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; string sEncodingAESKey = "4m6avCYhQ2p4IwjtMpFWNHRd46k2uIgdLbHSAlyCQsJ";// "he8dYrZ5gLbDrDhfHVJkea1AfmHgRZQJq47kuKpQrSO"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); // 需要发送的明文 String actionType = wechatMessage.EventKey; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); // string sRespData = "<MsgId>1234567890123456</MsgId>"; logger.Info("EventKey: " + wechatMessage.EventKey); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Commission; wechatQueryLog.subSystem = "佣金结算与支付查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } if (agentWechatAccount != null && !String.IsNullOrEmpty(agentWechatAccount.status) && !agentWechatAccount.status.Equals("Y")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "对不起,你的账号已被停用,请联系联通工作人员!\n\n"); } else if (agentWechatAccount==null) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "用户不存在,请联系联通工作人员!\n\n"); } else { String agentNo = agentWechatAccount.branchNo; if (String.IsNullOrEmpty(agentNo)) { agentNo = agentWechatAccount.agentNo; } switch (actionType) { case "FeeQueryHelp": sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "佣金查询说明\n\n"); break; case "last6MonthBonus": String strBonusList = "最近6月红包查询\n\n"; for (int i = 1; i <= 6; i++) { String tempFeeMonth = DateTime.Now.AddMonths(0 - i).ToString("yyyyMM"); String url1 = String.Format("http://{0}/Wechat/AgentBonusDetailQuery.aspx?agentNo={1}&feeMonth={2}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(tempFeeMonth, QueryStringEncryption.key)); strBonusList = strBonusList + "<a href=\"" + url1 + "\">" + i + ":" + tempFeeMonth + "</a>"; strBonusList = strBonusList + "\n\n"; } sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", strBonusList); break; case "preMonthBonus": case "curMonthBonus": String feeMonthBonus = DateTime.Now.AddMonths(-1).ToString("yyyyMM"); if (actionType.Equals("preMonthBonus")) { feeMonthBonus = DateTime.Now.AddMonths(-2).ToString("yyyyMM"); } AgentBonusDao agentBonusDao = new AgentBonusDao(); AgentBonus agentBonus = agentBonusDao.GetByKey(feeMonthBonus, agentNo); if (agentBonus != null && !String.IsNullOrEmpty(agentBonus.agentNo)) { sb.Append(this.createAgentBonusNewsMessages(feeMonthBonus, agentBonus, agentNo)); } else { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "本月无红包或者红包尚未发布!\n\n"); } break; case "Latest6MonthFeeQuery": String strList = "最近6月佣金查询\n\n"; for (int i = 1; i <= 6; i++) { String tempFeeMonth = DateTime.Now.AddMonths(0 - i).ToString("yyyy-MM"); String url1 = String.Format("http://{0}/Wechat/AgentFeeQuery.aspx?agentNo={1}&feeMonth={2}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(tempFeeMonth, QueryStringEncryption.key)); strList = strList + "<a href=\"" + url1 + "\">" + i + ":" + tempFeeMonth + "</a>"; strList = strList + "\n\n"; } sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", strList); break; case "PreMonthFeeQuery": case "CurMonthFeeQuery": String feeMonth = DateTime.Now.AddMonths(-1).ToString("yyyy-MM"); if (actionType.Equals("PreMonthFeeQuery")) { feeMonth = DateTime.Now.AddMonths(-2).ToString("yyyy-MM"); } AgentFeeDao agentFeeDao = new AgentFeeDao(); AgentFee agentFee = agentFeeDao.GetByKey(feeMonth, agentNo); if (agentFee != null && !String.IsNullOrEmpty(agentFee.agentFeeSeq)) { sb.Append(this.createAgentFeeNewsMessages(feeMonth, agentFee, agentNo)); } else { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "本月无佣金或者佣金尚未发布\n\n"); } break; case "PaymentQueryHelp": sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "发票支付查询说明\n\n"); break; case "Latest6MonthPaymentQuery": String strList1 = "最近6月发票支付查询\n\n"; for (int i = 1; i <= 6; i++) { String tempFeeMonth = DateTime.Now.AddMonths(0 - i).ToString("yyyyMM"); String url1 = String.Format("http://{0}/Wechat/InvoicePaymentQuery.aspx?agentNo={1}&feeMonth={2}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(tempFeeMonth, QueryStringEncryption.key)); strList1 = strList1 + "<a href=\"" + url1 + "\">" + i + ":" + tempFeeMonth + "</a>"; strList1 = strList1 + "\n\n"; } sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", strList1); break; case "PreMonthPaymentQuery": case "CurMonthPaymentQuery": feeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM"); if (actionType.Equals("PreMonthPaymentQuery")) { feeMonth = DateTime.Now.AddMonths(-2).ToString("yyyyMM"); } InvoicePaymentDao agentInvoicePaymentDao = new InvoicePaymentDao(); IList<InvoicePayment> agentInvoicePaymentList = new List<InvoicePayment>(); // agentNo = "";//"DL224049"; // feeMonth = "201412"; logger.Info("1.feeMonth=" + feeMonth); logger.Info("2.agentNo=" + agentNo); agentInvoicePaymentList = agentInvoicePaymentDao.GetList(agentNo, null, feeMonth, null); if (agentInvoicePaymentList != null && agentInvoicePaymentList.Count > 0) { sb.Append(this.createPaymentNewsMessages(feeMonth, agentNo, agentInvoicePaymentList)); } else { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", feeMonth.Substring(0, 4) + "年" + feeMonth.Substring(4, 2) + "月" + "无发票受理记录或尚未完成,请耐心等候!\n\n"); } break; default: if (!Regex.IsMatch(wechatMessage.Content, "((20[0-9][0-9])|(19[0-9][0-9]))-((0[1-9])|(1[0-2]))")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "请输入\"yyyy-mm\"查询某月佣金,支付结算和红包,例如:\"" + DateTime.Now.ToString("yyyy-MM") + "\"查询" + DateTime.Now.ToString("yyyy年MM月") + "佣金\n\n"); } else { feeMonth = wechatMessage.Content; agentFeeDao = new AgentFeeDao(); agentFee = agentFeeDao.GetByKey(feeMonth, wechatMessage.FromUserName); agentBonusDao = new AgentBonusDao(); feeMonthBonus = feeMonth.Replace("-", ""); agentBonus = agentBonusDao.GetByKey(feeMonthBonus, agentNo); agentInvoicePaymentDao = new InvoicePaymentDao(); String feeMonthInvoice = feeMonth.Replace("-", ""); agentInvoicePaymentList = agentInvoicePaymentDao.GetList(agentNo, null, feeMonthInvoice, null); sb.Append(this.createAllNewsMessages(feeMonth, wechatMessage.FromUserName, agentFee, agentBonus, agentInvoicePaymentList)); } break; } } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); }
static void Main(string[] args) { //公众平台上开发者设置的token, corpID, EncodingAESKey string sToken = "QDG6eK"; string sCorpID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); /* * 假定公众平台上开发者设置的Token 1. 验证回调URL * 点击验证时,企业收到类似请求: * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3×tamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.WeiXin.qq.com * 接收到该请求时,企业应1.先验证签名的正确性 2. 解密出echostr原文。 * 以上两步用verifyURL完成 */ //解析出url上的参数值如下: string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = "263014780"; string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret ); string input3 = System.Console.ReadLine(); return; } System.Console.WriteLine(sEchoStr); /* 2. 对用户回复的数据进行解密。 * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息: * 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> <AgentID><![CDATA[218]]></AgentID> </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><AgentID><![CDATA[218]]></AgentID></xml>"; string sMsg = ""; //解析之后的明文 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); /* * 3. 企业回复用户消息也需要加密和拼接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> * <AgentID>128</AgentID> * </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><AgentID>128</AgentID></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; }
/// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); string sToken = "BusinessPolicyHandler"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx4fe8b74e01fffcbb"; string sEncodingAESKey = "3jJb1Xr7z6fF7LJPCESk8wX8XFf8E6mK4MYIbiOY8yt";// "omiSDTqK4GjKmsQ6eCJSWpOtmqPcz6A3B41RBcg6Ey9"; // string sToken = Properties.Settings.Default.Wechat_AgentFee_Token;//"AgentFee"; // string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; // string sEncodingAESKey = Properties.Settings.Default.Wechat_AgentFee_EncodingAESKey;// "he8dYrZ5gLbDrDhfHVJkea1AfmHgRZQJq47kuKpQrSO"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); // 需要发送的明文 String actionType = wechatMessage.EventKey; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Notice; wechatQueryLog.subSystem = "通知公告与促销政策"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } // string sRespData = "<MsgId>1234567890123456</MsgId>"; logger.Info("EventKey: " + wechatMessage.EventKey); String agentNo = wechatMessage.FromUserName; AgentDao agentDao = new AgentDao(); Agent agent = agentDao.Get(agentNo); if (agent != null && !String.IsNullOrEmpty(agent.status) && agent.status.Equals("Y")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "对不起,你的账号已被停用,请联系联通工作人员!\n\n"); } else { PolicyDao policyDao = new ChinaUnion_DataAccess.PolicyDao(); switch (actionType) { case "LatestPolicy": case "HistoryPolicy": case "LatestNotice": case "HistoryNotice": IList<Policy> policyList =null; if (actionType.Equals("LatestNotice")) { policyList = policyDao.GetAllList(""); } else { policyList = policyDao.GetAllList(""); } if (policyList != null && policyList.Count > 0) { sb.Append(this.createNewsMessages(wechatMessage.FromUserName, policyList)); } else { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "没有公告发布!\n\n"); } break; default: break; } } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); }