/// <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); }
/// <summary> /// 以推送过来请求中的随机字符串、时间戳为基础进行响应消息加密 /// </summary> /// <param name="xmlMsgTxt">要加密的明文</param> /// <returns>加密后的密文</returns> private string MessageEncrypt(string xmlMsgTxt) { string timestamp = TimeHelper.GetTime(DateTime.Now).ToString(); string nonce = StringHelper.RandomStr(StrType.NumAndLowercase, 16); string sEncryptMsg = null; //xml格式的密文 int result = wxcpt.EncryptMsg(xmlMsgTxt, timestamp, nonce, ref sEncryptMsg); SystemLogHelper.Info(GetType().FullName, "消息加密处理结果:" + CryptResult(result)); return(sEncryptMsg); }
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="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); }
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; }
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="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); }
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 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, 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; }
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(); 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="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); }
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> /// 根据响应实体生成回包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 ""; }
/// <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); }
/// <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); }
/// <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); }
/// <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 = "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); }
//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); }
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; } } }