123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513 |
- using LYFZ.Weixin.SDK;
- using LYFZ.WXLibrary;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Xml;
- using System.Xml.Linq;
- namespace LYFZ.WeixinServers.WeiXinAPP
- {
- public partial class WXService : System.Web.UI.Page
- {
- /// <summary>
- /// 壳域名
- /// </summary>
- string requestUrl = "";
- /// <summary>
- /// 加密锁域名
- /// </summary>
- string JMGDomainName = "-2";
- protected void Page_Load(object sender, EventArgs e)
- {
- /* string signature = Request["signature"];
- string timestamp = Request["timestamp"];
- string nonce = Request["nonce"];
- //回复普通文本消息
- string replayMsg = ReplayPassiveMessageAPI.RepayText("ozy4qt1eDxSxzCr0aNT0mXCWfrDE", "gh_3c884a361561", "TESTCOMPONENT_MSG_TYPE_TEXT_callback");
- string encryptMsg = replayMsg;
-
- var msg_signature = Request.QueryString.Get("msg_signature");
- var wxBizMsgCrypt = new Tencent.WXBizMsgCrypt(OpenPlatformConfig.OpenToken, OpenPlatformConfig.OpenEncodingAESKey, OpenPlatformConfig.OpenAppID);
- var ret = wxBizMsgCrypt.EncryptMsg(replayMsg, timestamp, nonce, ref encryptMsg);
- if (ret != 0)//加密失败
- {
- //TODO:开发者加密失败的业务处理逻辑
- LYFZ.WXLibrary.CommonHandleClass.WriteLog(string.Format("加密失败,加密消息返回{0},响应体{1}", ret, encryptMsg), JMGDomainName, Global.LogsDongleDomainList);
- }
- */
- try
- {
- if (Request["appid"] != null)
- {
- //新版接口请求处理
- this.OpenPlatformRetqusetHandle();
- /*LYFZ.WXLibrary.CommonHandleClass.WriteLog("进入自定义一般处理文件工功能" , Global.LogsDongleDomainList);
- LYFZ.WeixinServers.WeiXinAPP.Api.WeiXinService wxService = new Api.WeiXinService();
- wxService.ProcessRequest(HttpContext.Current);*/
- }
- else
- {
- WriteContent("");
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("非法请求Url:" + this.Request.Url, "-2", Global.LogsDongleDomainList);
- }
- }
- catch//(Exception ex)
- {
- WriteContent("");
- //LYFZ.WXLibrary.CommonHandleClass.WriteLog("Load处理出错:"+ex.Message+" 请求Url:" + this.Request.Url, "-2", Global.LogsDongleDomainList);
- }
- finally {
- System.Threading.Thread.Sleep(1);
- Response.End();
- }
- }
- /// <summary>
- /// 客户请求缓存集合
- /// </summary>
- static Dictionary<string, ClientRequestCache> ClientRequestCacheList = new Dictionary<string, ClientRequestCache>();
- /// <summary>
- /// 添加客户请求缓存
- /// </summary>
- /// <param name="crCache"></param>
- static void AddClientRequestCache(ClientRequestCache crCache)
- {
- lock (ClientRequestCacheList)
- {
- LYFZ.WXLibrary.ClientRequestCache RequestCache = null;
- if (ClientRequestCacheList.ContainsKey(crCache.Key))
- {
- RequestCache = ClientRequestCacheList[crCache.Key];
- RequestCache.RequestCount++;
- }
- else
- {
- ClientRequestCacheList.Add(crCache.Key, crCache);
- }
- }
- }
- /// <summary>
- /// 移除客户请求
- /// </summary>
- /// <param name="key"></param>
- static void RemoveClientRequestCache()
- {
- List<string> delCacheKeyList = new List<string>();
- lock (ClientRequestCacheList)
- {
- foreach (ClientRequestCache crCache in ClientRequestCacheList.Values)
- {
- if (crCache.RequestTime > DateTime.Now.AddMilliseconds(-30))
- {
- delCacheKeyList.Add(crCache.Key);
- }
- }
- if (delCacheKeyList.Count > 0)
- {
- foreach (string key in delCacheKeyList)
- {
- ClientRequestCacheList.Remove(key);
- }
- delCacheKeyList.Clear();
- delCacheKeyList = null;
- System.GC.Collect();
- }
- }
- }
- /// <summary>
- /// 获取客户请求
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- static ClientRequestCache GetClientRequestCache(string key)
- {
- LYFZ.WXLibrary.ClientRequestCache RequestCache = null;
- lock (ClientRequestCacheList)
- {
- if (ClientRequestCacheList.ContainsKey(key))
- {
- RequestCache = ClientRequestCacheList[key];
- return RequestCache;
- }
- else
- {
- return null;
- }
- }
- }
- /// <summary>
- /// 新版开放平台接口请求处理
- /// Url:http://localhost:8086/WeiXinAPP/WXService.aspx?
- /// appid=/wx570bc396a51b8ff8
- /// &signature=b8c09dacd2f78ab91c66e671bbafedc7a8214585×
- /// tamp=1463793056
- /// &nonce=1644617734
- /// &encrypt_type=aes
- /// &msg_signature=9a1f16de1078d3727c51fcd0a8c5527441bd4cc8
- /// </summary>
- void OpenPlatformRetqusetHandle()
- {
- string appid = Request["appid"].ToString().Trim().Trim('/');
- string signature = Request["signature"];
- string timestamp = Request["timestamp"];
- string nonce = Request["nonce"];
- // string echostr = Request["echostr"];
- try
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("开如处理公众号AppID:" + appid + "的请求,Url:" + this.Request.Url, appid, Global.LogsDongleDomainList);
- }
- catch { }
- try
- {
- //获取当前公众号AppID的处理对象
- LYFZ.WXLibrary.AuthorizedAPPIDHandle APPIDHandle = null;
- if (OpenPlatformConfig.AuthorizedAPPIDHandleList.ContainsKey(appid))
- {
- APPIDHandle = OpenPlatformConfig.AuthorizedAPPIDHandleList[appid];
- JMGDomainName = APPIDHandle.JMGDomainName;
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("公众号AppID:" + appid + "对应的标识符:" + JMGDomainName, appid, Global.LogsDongleDomainList);
- if (Request.HttpMethod == "GET")
- {
- WriteContent("标识符:" + JMGDomainName + ",如果你在浏览器中看到这句话,说明此微信公众账号已经成功授权,可以正常使用我们提供的相关功能。");
- }
- else
- {
- WeixinMessage message = null;
- var safeMode = Request.QueryString.Get("encrypt_type") == "aes";
- var postDataDocument = "";//new XDocument();// LYFZ.Weixin.SDK.Helpers.XmlUtility.Convert(Request.InputStream);
- try
- {
- Request.InputStream.Seek(0, SeekOrigin.Begin);//强制调整指针位置
- using (var streamReader = new StreamReader(Request.InputStream))
- {
- var decryptMsg = string.Empty;
- var msg = streamReader.ReadToEnd();
- #region 解密
- if (safeMode)
- {
- var msg_signature = Request.QueryString.Get("msg_signature");
- var wxBizMsgCrypt = new Tencent.WXBizMsgCrypt(OpenPlatformConfig.OpenToken, OpenPlatformConfig.OpenEncodingAESKey, OpenPlatformConfig.OpenAppID);
- var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decryptMsg);
- if (ret != 0)//解密失败
- {
- //TODO:开发者解密失败的业务处理逻辑
- LYFZ.WXLibrary.CommonHandleClass.WriteLog(string.Format("新版开放平台接口解密失败,解密消息返回{0},密文为:{1}", ret, msg));
- }
- }
- else
- {
- decryptMsg = msg;
- }
- #endregion
- //postDataDocument.(decryptMsg);
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("POST 请求解密后的信息:" + decryptMsg, appid, Global.LogsDongleDomainList);
- message = AcceptMessageAPI.Parse(decryptMsg);
-
- postDataDocument = decryptMsg;//XDocument.Parse(encryptMsg);
- }
- }
- catch (Exception ex)
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("POST 请求加密解密时出错:" + ex.Message, appid, Global.LogsDongleDomainList);
- }
- if (message != null)
- {
- RemoveClientRequestCache();
- ClientRequestCache crCache = new ClientRequestCache(appid, message);
- AddClientRequestCache(crCache);
- string openId = message.Body.FromUserName.Value.ToString();
- string myUserName = message.Body.ToUserName.Value.ToString();
- if (appid.ToLower().Trim() == OpenPlatformConfig.MicroLetterTestAPPID.ToLower().Trim())
- {
- //微信后台专用测试公众号APPID 在全网发布时使用
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("POST 请求开始处理微信后台专用(全网发布)测试", "-2", Global.LogsDongleDomainList);
- switch (message.Type)
- {
- case WeixinMessageType.Text:
- string Content = message.Body.Content.Value.ToString();
- if (Content.Contains("QUERY_AUTH_CODE:"))
- {
- //发送Api文本消息
- bool apisend = LYFZ.Weixin.SDK.ReplayActiveMessageAPI.RepayText(APPIDHandle.Authorizer_access_token, openId, Content.Split(':')[1] + "_from_api");
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("微信后台专用(全网发布)测试 => 发送Api文本消息:" + apisend.ToString(), appid, Global.LogsDongleDomainList);
- WriteContent("");
- }
- else if (Content.Contains("TESTCOMPONENT_MSG_TYPE_TEXT"))
- {
- //回复普通文本消息
- string replayMsg = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "TESTCOMPONENT_MSG_TYPE_TEXT_callback");
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("微信后台专用(全网发布)测试 => 回复普通文本消息:" + replayMsg, appid, Global.LogsDongleDomainList);
- RepayTextMsg(safeMode, replayMsg, signature, timestamp, nonce);
- }
- break;
- case WeixinMessageType.Event:
- //发送事件消息
- string eventValue = message.Body.Event.Value.ToString();
- bool eventsend = LYFZ.Weixin.SDK.ReplayActiveMessageAPI.RepayText(APPIDHandle.Authorizer_access_token, openId, eventValue + "from_callback");
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("微信后台专用(全网发布)测试 => 发送事件消息:" + eventsend.ToString(), appid, Global.LogsDongleDomainList);
- WriteContent("");
- break;
- }
- }
- else
- {
- string response = new LYFZ.WXLibrary.WeixinExecutor().ServiceExecute(message).ToLower().Trim();
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("POST 当前事件值:" + response, appid, Global.LogsDongleDomainList);
- //获取客户接口配置信息
- LYFZ.WeixinServiceDate.Model.Model_CustomerInterfaces cusModel = Global.GetCustomerModel(JMGDomainName);
- if (cusModel != null && cusModel.ID > 0)
- {
- requestUrl = cusModel.GetRequestUrl();
- /* string newSignature = ""; //新的签名
- if (timestamp != null && nonce != null)
- {
- newSignature = BasicAPI.GetSignature(timestamp, nonce, cusModel.Token); //新的签名
- }*/
-
- string replayMsg = "";
- if (LYFZ.WXLibrary.CommonHandleClass.MicroLetterEventList.Contains(response))
- {
-
- ClientRequestCache currentRequestCache = GetClientRequestCache(crCache.Key);
- if (currentRequestCache.RequestCount < 3)
- {
- if (!String.IsNullOrEmpty(requestUrl)&& !requestUrl.ToLower().Contains("http://p.lyfz.net"))
- {
- try
- {
- string functionCode = LYFZ.WXLibrary.CommonHandleClass.GetFunctionCode(response);
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("公众号AppID:" + appid + "请求功能代码:" + functionCode, appid, Global.LogsDongleDomainList);
- try
- {
- string content = message.Body.Content.Value.ToString();
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("提交的内容" + content, appid, Global.LogsDongleDomainList);
- if (content.Split('#').Length > 1)
- {
- replayMsg = MicroMessageProcessing.WeiXinMessageFastData(functionCode, content, openId, requestUrl, cusModel.ID, appid);
- }
- else
- {
- replayMsg = MicroMessageProcessing.WeiXinMessageData(functionCode, openId, requestUrl, cusModel.ID, appid);
- }
- }
- catch
- {
- replayMsg = MicroMessageProcessing.WeiXinMessageData(functionCode, openId, requestUrl, cusModel.ID, appid);
- }
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("公众号AppID:" + appid + "请求“" + requestUrl + "”返回信息:" + replayMsg, appid, Global.LogsDongleDomainList);
- replayMsg = ReplayPassiveMessageAPI.RepayText(openId, myUserName, replayMsg);
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("公众号AppID:" + appid + "请求“" + requestUrl + "”XML格式化后信息:" + replayMsg, appid, Global.LogsDongleDomainList);
- }
- catch (Exception ex)
- {
- replayMsg = "";
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("在请求公众号AppID:" + appid + "的信息出错:" + ex.Message, appid, Global.LogsDongleDomainList);
- }
- }
- else
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("获取当前公众号AppID:" + appid + "的请求超时<br /> Url=" + requestUrl.Trim(), appid, Global.LogsDongleDomainList);
- replayMsg = "";
- }
- }
- else {
- replayMsg = "";
- }
- }
- else if (OpenPlatformConfig.IsTransmitService(response))
- {
- replayMsg = ReplayPassiveMessageAPI.TransmitService(openId, myUserName);
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("公众号AppID:" + appid + "的信息已转到多客服:" + response, appid, Global.LogsDongleDomainList);
- }
- else
- {
- replayMsg = "";//ReplayPassiveMessageAPI.RepayText(openId, myUserName, "收到的信息:" + response);
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("非法指令请求 公众号AppID:" + appid + "对应的标识:" + JMGDomainName + "收到的信息:" + response, appid, Global.LogsDongleDomainList);
- }
- if (!String.IsNullOrEmpty(replayMsg))
- {
- RepayTextMsg(safeMode, replayMsg,signature, timestamp, nonce);
- }
- else
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("当前公众号AppID:" + appid + "的返回信息为空", appid, Global.LogsDongleDomainList);
- WriteContent("");
- }
- }
- else
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("获取当前公众号AppID:" + appid + "的客户接口配置信息失败", appid, Global.LogsDongleDomainList);
- WriteContent("");
- }
- }
- }
- else
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("获取当前公众号AppID:" + appid + "的客户接口配置信息失败", appid, Global.LogsDongleDomainList);
- WriteContent("");
- }
- }
- }
- else
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("获取当前公众号AppID:" + appid + "的处理对象失败", appid, Global.LogsDongleDomainList);
- WriteContent("");
- }
- }
- catch (Exception ex)
- {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog("处理当前公众号AppID:" + appid + "信息时出错:" + ex.Message, appid, Global.LogsDongleDomainList);
- WriteContent("");
- }
- }
- void RepayTextMsg(bool safeMode, string replayMsg, string signature, string timestamp, string nonce)
- {
- string encryptMsg = replayMsg;
- if (safeMode)
- {
- var msg_signature = Request.QueryString.Get("msg_signature");
- var wxBizMsgCrypt = new Tencent.WXBizMsgCrypt(OpenPlatformConfig.OpenToken, OpenPlatformConfig.OpenEncodingAESKey, OpenPlatformConfig.OpenAppID);
- var ret = wxBizMsgCrypt.EncryptMsg(replayMsg, timestamp, nonce, ref encryptMsg);
- if (ret != 0)//加密失败
- {
- //TODO:开发者加密失败的业务处理逻辑
- LYFZ.WXLibrary.CommonHandleClass.WriteLog(string.Format("加密失败,加密消息返回{0},响应体{1}", ret, encryptMsg), "-2", Global.LogsDongleDomainList);
- }
- else {
- LYFZ.WXLibrary.CommonHandleClass.WriteLog(string.Format("加密成功,加密前的消息{0}", replayMsg), "-2", Global.LogsDongleDomainList);
- LYFZ.WXLibrary.CommonHandleClass.WriteLog(string.Format("加密成功,加密后的消息{0}",encryptMsg), "-2", Global.LogsDongleDomainList);
- }
- }
- WriteContent(encryptMsg);
- }
-
- public static string getUrlQueryString(System.Collections.Specialized.NameValueCollection query)
- {
- string retUrlQueryString = "";
- foreach (string key in query.AllKeys)
- {
- if (key != null && key.ToLower() != "requestUrl".ToLower() && key.ToLower() != "yuname")
- {
- string[] values = query.GetValues(key);
- foreach (string value in values)
- {
- retUrlQueryString += key + "=" + value + "&";
- }
- }
- }
- return retUrlQueryString.Trim('&');
- }
- public static string getRequestUrl(string url, string parameters)
- {
- if (parameters.Length > 0)
- {
- if (url.Contains("?"))
- {
- return url + "&" + parameters.Trim('&');
- }
- else
- {
- return url + "?" + parameters.Trim('&');
- }
- }
- else
- {
- return url;
- }
- }
- private void WriteContent(string str)
- {
- try
- {
- if (!str.ToLower().Contains("Request failed,Exception:".ToLower()) && !str.Contains("Url参数错误"))
- {
- Global.UpdateCustCallFrequency(JMGDomainName);
- }
- }
- catch { }
- // Response.Output.Write(str);
- Response.Write(str);
- }
- #region Web GET POST方式提交
- /// <summary>
- /// Web POST方式提交
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <returns></returns>
- public static string HttpWebRequestPOST(string url, string postData)
- {
- if (url.Trim().Length > 1)
- {
- return LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestPOST(url, postData, Encoding.UTF8, "text/xml");
- }
- else {
- return "Url参数错误";
- }
- }
- /// <summary>
- /// Web GET方式提交
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string HttpWebRequestGET(string url)
- {
- if (url.Trim().Length > 1)
- {
- return LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestGET(url, Encoding.UTF8);
- }
- else {
- return "Url参数错误";
- }
- }
- #endregion
-
- }
- }
|