支持转接客服 菜单 关注推送内容等 留着备用 免得忘记
<%@ WebHandler Language="C#" Class="API" %> using System; using System.Web; using System.Net; using System.IO; using System.Collections.Generic; using System.Web.SessionState; using System.Runtime.Serialization.Json; using System.Text; using System.Xml; using System.Collections; ////// 周祥 微信通用接口 /// public class API : IHttpHandler, IRequiresSessionState { ////// appid /// public const string appid = ""; ////// appsecret /// public const string appsecret = ""; public HttpRequest Request = null; public HttpResponse Response = null; public HttpContext context2 = null; ////// load /// /// public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/Json"; Request = context.Request; Response = context.Response; context2 = context; if (Request.HttpMethod.ToString().ToLower() == "post") { StreamReader stream = new StreamReader(Request.InputStream); string xml = stream.ReadToEnd(); manageXml(xml); } else { if (Request["code"] != null && Request["code"] != "" && Request["state"] != null && Request["state"] != "" && Request["tzid"] != null && Request["tzid"] != "") { GetOpenID(Request["code"], Request["state"], Request["tzid"]); } else if (Request["signature"] != null && Request["signature"] != "" && Request["timestamp"] != null && Request["timestamp"] != "" && Request["nonce"] != null && Request["nonce"] != "") { OneData(); } else if (Request["token"] != null) { Response.Write(GetAccessToken()); } else { Response.Write("404"); } } } public void GetOpenID(string code, string state, string tzid) { //获取code 获取openid 然后进行跳转 参考例子在谷歌浏览器下载里面 Dictionaryh = new Dictionary (); h.Add("grant_type", "authorization_code"); h.Add("appid", appid); h.Add("secret", appsecret); h.Add("code", code); string token = HttpRequstGet("https://api.weixin.qq.com/sns/oauth2/access_token", h); //反序列化 如果成功 说明返回token成功 TokenOpenModel model = null; try { model = JsonDeserialize (token); } catch (Exception ex) { Log.ErrorLog("微信接口获取OpenId出错:" + ex.ToString()); } if (model.openid != null) { //model.openid = DESEncrypt.Encrypt(model.openid); switch (tzid) { case "1": Response.Redirect("http://zxaioykx.gicp.net:54660/wap/?tid=" + tzid + "&openid=" + model.openid); break; case "2": Response.Redirect("http://zxaioykx.gicp.net:54660/wap/?tid=" + tzid + "&openid=" + model.openid); break; case "3": Response.Redirect("http://m.400sky.com.cn"); break; case "4": Response.Redirect("http://m.400sky.com.cn"); break; case "5": Response.Redirect("http://wap.400sky.com.cn/mhzn.htm"); break; default: break; } } else { Response.Redirect("http://www.400sky.com.cn/404"); } } /// /// 第一次绑定 验证 /// public void OneData() { string echoStr = Request.QueryString["echoStr"].ToString(); if (checkSignature()) { //创建菜单 //CreateOrDelMenu(false); //CreateOrDelMenu(true); if (!string.IsNullOrEmpty(echoStr)) { Response.Write(echoStr); Response.End(); } } } public bool IsReusable { get { return false; } } ////// 验证微信签名 /// ///public bool checkSignature() { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string token = "hltxjsbzhouxiang"; string[] ArrTmp = { token, timestamp, nonce }; Array.Sort(ArrTmp); string tmpStr = string.Join("", ArrTmp); tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { return true; } return false; } /////////////////////////////////号令天下智能微信机器人接口/////////////////////////////////////// /// /// 关注后 推送菜单 /// ///public static string Menu() { string Content = ""; Content += "您好!欢迎您关注号令天下通讯有限公司官方微信服务号.\n"; Content += "我是号令天下微信客服小令,很高兴为您服务!\n"; Content += "如果你是号令的经销代理商点击这里验证身份后,即可使用如下功能:\n"; Content += "账户查询,账户号码,账户余额,账户详情\n"; Content += "号码充值,为号码充值,为代理商充值\n"; Content += "号码预占,预占自己喜欢的号码\n"; Content += "回复内容[1]显示主菜单"; return Content; } /// /// 关注后 推送菜单 /// ///public static string Menu2() { string Content = ""; Content += "您好!我是号令天下官方微信客服小令,很高兴为您服务\n"; Content += "您可以回复关键字,获取您想了解的咨询\n"; Content += "1.获取服务菜单导航\n"; Content += "2.什么是400电话?\n"; Content += "3.号令简介\n"; Content += "4.400电话的核心服务功能\n"; Content += "5.招商加盟\n"; Content += "6.最新活动靓号\n"; Content += "7.号令最新动态\n"; Content += "8.联系我们\n"; Content += "9.意见反馈\n\n"; Content += "回复任意内容,有专业客服人员为您服务,如果您要了解更多号令资讯,请访问号令微官网"; return Content; } public void hl2(string FromUserName, string ToUserName) { IList list = new List (); ReturnPicModel model = new ReturnPicModel() { Url = "http://mp.weixin.qq.com/s?__biz=MjM5NDU1MzkzMw==&mid=200487034&idx=1&sn=a49ed5c809f9d7c7569b1736103049f3#rd", Description = "400业务,又称主被叫分摊付费业务,是一项为被叫客户提供一个全国范围内的唯一号码,并把对该号码的呼叫接至被叫客户事先规定目的地(电话号码或呼叫中心)的全国性智能网业务", PicUrl = "http://mmbiz.qpic.cn/mmbiz/5o1ibcmuYzje2HiaMEwAOzYhmqWCU0uLdkM7jb6E3l6ZzFc2B53ia4q275a7ParIJe0jhGX7NiamYgpuP0ib5mDXqoQ/0", Title = "什么是400电话?" }; list.Add(model); ReturnImgXml(FromUserName, ToUserName, list); } public void hl3(string FromUserName, string ToUserName) { IList list = new List (); ReturnPicModel model = new ReturnPicModel() { Url = "http://mp.weixin.qq.com/s?__biz=MjM5NDU1MzkzMw==&mid=201380423&idx=3&sn=280021c420bc244cbfe8203801ea3d8f#rd", Description = "号令天下,是中国最强二类虚拟运营商之一,号令天下以服务全中国的中小企业为宗旨,发展紧紧围绕中小企业需求进行,产品以简单、实用、功能强大为原则开发", PicUrl = "http://mmbiz.qpic.cn/mmbiz/5o1ibcmuYzjdxiagVg99J1dm3PzviawHt2icicDwyh7CD9iciaOtNxmvLD01Cu7CK9XuFuIJicADWbUTZ7bQjvEKO0I3kw/640", Title = "号令简介" }; list.Add(model); ReturnImgXml(FromUserName, ToUserName, list); } public void hl4(string FromUserName, string ToUserName) { IList list = new List (); ReturnPicModel model = new ReturnPicModel() { Url = "http://mp.weixin.qq.com/s?__biz=MjM5NDU1MzkzMw==&mid=200718952&idx=1&sn=d5096808ae876d918d256a73495d9cf6#rd", Description = "号令天下为您贴心提供400核心服务功能", PicUrl = "http://mmbiz.qpic.cn/mmbiz/5o1ibcmuYzjdzokGAt5DxAzh2LplBZvtrv2IBW3PdUobVIunuvIETsYibGicNloAwndibF9OQBPRzfcBCuJxhppf6A/0", Title = "400电话的核心服务功能" }; list.Add(model); ReturnImgXml(FromUserName, ToUserName, list); } public void hl5(string FromUserName, string ToUserName) { IList list = new List (); ReturnPicModel model = new ReturnPicModel() { Url = "http://wap.400sky.com.cn/kshzs.html", Description = "7*24小时贴心售后服务保障,专业的技术研发团队,为您保驾护航", PicUrl = "http://wap.400sky.com.cn/images/vipdl.jpg", Title = "招商加盟" }; list.Add(model); ReturnImgXml(FromUserName, ToUserName, list); } public void hl7(string FromUserName, string ToUserName) { IList list = new List (); ReturnPicModel model = new ReturnPicModel() { Url = "http://mp.weixin.qq.com/s?__biz=MjM5NDU1MzkzMw==&mid=201238846&idx=5&sn=57a8e5af197ce9f79f03290315a0cf43#rd", Description = "号令2014年11月15日全体员工运动会!", PicUrl = "http://mmbiz.qpic.cn/mmbiz/5o1ibcmuYzjeVF4y6oia71qgiaQibH6dN4C0NFHAl5XIL1T2MR59gE0yk5Q3ynYnYGzOJmVZnHW5bQ4V5RtqxUaLAw/0", Title = "激情青春,活力绽放!" }; list.Add(model); ReturnImgXml(FromUserName, ToUserName, list); } public void hl8(string FromUserName, string ToUserName) { ReturnXml(FromUserName, ToUserName, "联系我们:\n\n 24小客服电话 :400-999-4000 \n公司官方邮箱 :haolingtianxia@163.com\n 官方微信服务号: szhltx2013\n 公司地址:深圳市宝安区宝源路华源科技创新园B座1区7层"); } public static string LiangHao() { string lianghao = "最新靓号推荐:\n\n"; lianghao += "400-089-9766\n"; lianghao += "400-050-0755\n"; lianghao += "400-068-8199\n"; lianghao += "400-073-7333\n"; lianghao += "400-085-5333\n"; lianghao += "400-092-7676\n"; lianghao += "400-725-6333\n"; lianghao += "400-725-9000\n"; lianghao += "400-725-9966\n"; lianghao += "400-725-9996\n\n"; lianghao += "更多更好的靓号均在号令天下!"; return lianghao; } /// /// 返回XML给微信 /// /// /// /// public void ReturnXml(string FromUserName, string ToUserName, string msg) { string strresponse = ""; strresponse += " "; Response.Write(strresponse); } ///"; strresponse += " "; strresponse += " " + DateTime.Now.Ticks.ToString() + " "; strresponse += ""; strresponse += " "; strresponse += " 0 "; strresponse += " /// 返回图文消息 /// /// /// /// /// public void ReturnImgXml(string FromUserName, string ToUserName, IListlist, int flag = 0) { string strresponse = " "; strresponse += " "; Response.Write(strresponse); } ///"; strresponse += " "; strresponse += " " + DateTime.Now.Ticks.ToString() + " "; strresponse += ""; strresponse += " 1 "; strresponse += ""; for (int i = 0; i < list.Count; i++) { var m = list[i]; strresponse += " "; strresponse += "- "; strresponse += "
"; } strresponse += ""; strresponse += " "; strresponse += " "; strresponse += " "; strresponse += " " + flag + " "; strresponse += "/// 转接客服系统 /// /// /// /// public void ReturnKf(string FromUserName, string ToUserName) { string strresponse = ""; strresponse += " "; Response.Write(strresponse); //////////////通知用户/////////////// string strresponse2 = "{ \"touser\":\"" + FromUserName + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"正在接入客服,请稍候!\" }}"; string token = HttpRequstPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + GetAccessToken(), strresponse2); //////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////////////////////// ///"; strresponse += " "; strresponse += " " + DateTime.Now.Ticks.ToString() + " "; strresponse += ""; strresponse += " /// 处理微信推送过来的消息 /// /// public void manageXml(string xml) { Log.ErrorLog("微信:" + xml); try { //解析 Hashtable requestHT = ParseXml(xml); //open_id string fromUserName = (string)requestHT["FromUserName"]; // 公众帐号 string toUserName = (string)requestHT["ToUserName"]; // 消息类型 string msgType = (string)requestHT["MsgType"]; //消息处理 if (msgType == ReqMsgType.Text.ToString()) { //文本消息 可以用来自动获取用户输入的关键词 进行推送 string msg = (string)requestHT["Content"]; if (msg == "1") { ReturnXml(fromUserName, toUserName, Menu2()); } else if (msg == "6") { ReturnXml(fromUserName, toUserName, LiangHao()); } else if (msg == "2") { hl2(fromUserName, toUserName); } else if (msg == "3") { hl3(fromUserName, toUserName); } else if (msg == "4") { hl4(fromUserName, toUserName); } else if (msg == "5") { hl5(fromUserName, toUserName); } else if (msg == "7") { hl7(fromUserName, toUserName); } else if (msg == "8") { hl8(fromUserName, toUserName); } else if (msg == "9") { ReturnKf(fromUserName, toUserName); } else { //如果没有找到自己定义的菜单项 则把消息发送到客服 //ReturnXml(fromUserName, toUserName, "正在为您接入客服,请稍候!"); ReturnKf(fromUserName, toUserName); //ReturnXml(fromUserName, toUserName, "您的反馈内容,我们已经记录并发送给客服,请等待客服联系您!"); } } else if (msgType == ReqMsgType.Event) { //事件消息 监控各个事件 //事件类型 string eventType = (string)requestHT["Event"]; if (eventType == ReqEventType.CLICK) { //菜单点击 暂时不做处理 string eventEventKey = (string)requestHT["EventKey"]; switch (eventEventKey) { case "lxwm": hl8(fromUserName, toUserName); break; case "zxdt": hl7(fromUserName, toUserName); break; case "yjfk": ReturnKf(fromUserName, toUserName); break; default: break; } } else if (eventType == ReqEventType.Subscribe) { //关注用户 ReturnXml(fromUserName, toUserName, Menu()); } else if (eventType == ReqEventType.Unsubscribe) { //取消关注 暂时不做处理 } else if (eventType == ReqEventType.VIEW) { //菜单跳转 暂时不做处理 } } else if (msgType == ReqMsgType.Image) { ReturnKf(fromUserName, toUserName); } else if (msgType == ReqMsgType.Link) { ReturnKf(fromUserName, toUserName); } else if (msgType == ReqMsgType.Location) {; ReturnKf(fromUserName, toUserName); } else if (msgType == ReqMsgType.Video) { ReturnKf(fromUserName, toUserName); } else if (msgType == ReqMsgType.Voice) { ReturnKf(fromUserName, toUserName); } } catch (Exception ex) { Log.ErrorLog("处理微信发来的请求信息出错:" + ex.ToString()); } } ////// 创建菜单 /// public void CreateOrDelMenu(bool IsDel) { string menu = "{" + "\"button\": [" + " {" + "\"name\": \"我的帐户\", " + "\"sub_button\": [" + "{" + "\"type\": \"view\", " + " \"name\": \"我的帐户\", " + " \"url\": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://www.400sky.com.cn/api/weixin/1&response_type=code&scope=snsapi_base&state=s1#wechat_redirect\", " + " \"sub_button\": [ ]" + " }, " + " {" + "\"type\": \"view\", " + " \"name\": \"号码充值\", " + " \"url\": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://www.400sky.com.cn/api/weixin/2&response_type=code&scope=snsapi_base&state=s1#wechat_redirect\", " + " \"sub_button\": [ ]" + "}, " + "{" + " \"type\": \"view\", " + " \"name\": \"查号平台\", " + " \"url\": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://www.400sky.com.cn/api/weixin/3&response_type=code&scope=snsapi_base&state=s1#wechat_redirect\", " + "\"sub_button\": [ ]" + " }," + " {" + "\"type\": \"view\", " + " \"name\": \"号码预占\", " + " \"url\": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://www.400sky.com.cn/api/weixin/4&response_type=code&scope=snsapi_base&state=s1#wechat_redirect\", " + " \"sub_button\": [ ]" + " }," + " {" + "\"type\": \"click\", " + " \"name\": \"意见反馈\", " + " \"key\": \"yjfk\", " + " \"sub_button\": [ ]" + " }" + " ]" + " }, " + " {" + "\"name\": \"号令服务\", " + " \"sub_button\": [" + " {" + " \"type\": \"view\", " + " \"name\": \"号码测吉凶\"," + "\"url\": \"http://wap.400sky.com.cn/fsyc.html\"," + " \"sub_button\": [ ]" + " }, " + " {" + " \"type\": \"view\", " + "\"name\": \"400电话功能介绍\", " + " \"url\": \"http://mp.weixin.qq.com/s?__biz=MjM5NDU1MzkzMw==&mid=200718952&idx=1&sn=d5096808ae876d918d256a73495d9cf6#rd\", " + " \"sub_button\": [ ]" + " }, " + " {" + " \"type\": \"view\", " + " \"name\": \"招商加盟\", " + " \"url\": \"http://wap.400sky.com.cn/kshzs.html\", " + " \"sub_button\": [ ]" + " }," + "{" + " \"type\": \"view\", " + " \"name\": \"一键合作\", " + " \"url\": \"http://wap.400sky.com.cn/default2.aspx\", " + " \"sub_button\": [ ]" + " }," + "{" + " \"type\": \"view\", " + " \"name\": \"卖号指南\", " + " \"url\": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://www.400sky.com.cn/api/weixin/5&response_type=code&scope=snsapi_base&state=s1#wechat_redirect\", " + " \"sub_button\": [ ]" + " }" + "]" + "}," + " {" + " \"name\": \"关于号令\", " + " \"sub_button\": [" + " {" + " \"type\": \"view\", " + " \"name\": \"微官网\", " + " \"url\": \"http://wap.400sky.com.cn/\", " + " \"sub_button\": [ ]" + " }, " + " {" + "\"type\": \"view\", " + " \"name\": \"号令介绍视频\"," + " \"url\": \"http://m.400sky.com.cn/default_yyjz.aspx\", " + " \"sub_button\": [ ]" + " }, " + " {" + " \"type\": \"view\", " + " \"name\": \"号令上市信息\", " + " \"url\": \"http://mp.weixin.qq.com/s?__biz=MjM5NDU1MzkzMw==&mid=200759595&idx=1&sn=f300680006f8c8b75f5adf328c4878b2#rd\", " + " \"sub_button\": [ ]" + " }, " + " {" + " \"type\": \"click\", " + " \"name\": \"号令最新动态\", " + " \"key\": \"zxdt\", " + "\"sub_button\": [ ]" + " }, " + " {" + "\"type\": \"click\", " + " \"name\": \"联系我们\"," + " \"key\": \"lxwm\", " + " \"sub_button\": [ ]" + " }" + " ]" + " }" + "]" + " }"; if (IsDel) { HttpRequstPost(" https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + GetAccessToken(), menu); //Log.ErrorLog("创建菜单:" + ret); } else { HttpRequstPost(" https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + GetAccessToken(), menu); //Log.ErrorLog("删除菜单:" + ret); } } ////// 将xml文件转换成Hashtable /// /// ///public static Hashtable ParseXml(String xml) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); XmlNode bodyNode = xmlDocument.ChildNodes[0]; Hashtable ht = new Hashtable(); if (bodyNode.ChildNodes.Count > 0) { foreach (XmlNode xn in bodyNode.ChildNodes) { ht.Add(xn.Name, xn.InnerText); } } return ht; } /// /// 获取授权 注意:授权一般有效期为2小时 所以需要进行存储 否则导致接口调用失败 /// ///public string GetAccessToken() { if (context2.Cache["WxAccessToken"] == null) { Dictionary h = new Dictionary (); h.Add("grant_type", "client_credential"); h.Add("appid", appid); h.Add("secret", appsecret); string token = HttpRequstGet("https://api.weixin.qq.com/cgi-bin/token", h); //反序列化 如果成功 说明返回token成功 TokenModel model = null; try { model = JsonDeserialize (token); } catch (Exception ex) { Log.ErrorLog("微信接口获取AccessToken出错:" + ex.ToString()); } if (model.access_token != null) { context2.Cache.Insert("WxAccessToken", model.access_token, null, DateTime.Now.AddSeconds(model.expires_in), System.Web.Caching.Cache.NoSlidingExpiration); return model.access_token; } } return (String)context2.Cache["WxAccessToken"]; } /// /// 请求方法 /// /// /// /// ///public static string HttpRequstGet(string RequstUrl, Dictionary h = null, string type = "application/Json") { if (h != null) { foreach (var item in h) { RequstUrl += (RequstUrl.IndexOf("?") > -1 ? "&" : "?"); RequstUrl += item.Key + "=" + item.Value; } } string responseData = null; HttpWebRequest webRequest = WebRequest.Create(RequstUrl) as HttpWebRequest; webRequest.Method = "GET"; webRequest.ServicePoint.Expect100Continue = false; webRequest.Timeout = 10000000; webRequest.ContentType = type; StreamReader responseReader = null; try { responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); } catch { } finally { webRequest.GetResponse().GetResponseStream().Close(); responseReader.Close(); responseReader = null; webRequest = null; } return responseData; } /// /// 请求方法 /// /// /// /// ///public static string HttpRequstPost(string RequstUrl, string param) { byte[] bs = Encoding.UTF8.GetBytes(param); string responseData = String.Empty; Encoding encoding = Encoding.UTF8; HttpWebRequest webRequest = WebRequest.Create(RequstUrl) as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = bs.Length; using (Stream reqStream = webRequest.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd().ToString(); } } return responseData; } /// /// JSON序列化 /// ////// /// public static string JsonSerializer (T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// /// JSON反序列化 /// ////// /// public static T JsonDeserialize (string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } } public class TokenModel { /// /// token /// public string access_token { get; set; } ////// time /// public int expires_in { get; set; } } public class TokenOpenModel { public string access_token { get; set; } public int expires_in { get; set; } public string refresh_token { get; set; } public string openid { get; set; } public string scope { get; set; } } public class ReturnPicModel { public string Title { get; set; } public string Description { get; set; } public string PicUrl { get; set; } public string Url { get; set; } } public class ReqMsgType { ////// 图片消息 /// public const string Image = "image"; ////// 语音消息 /// public const string Voice = "voice"; ////// 视频消息 /// public const string Video = "video"; ////// 文本消息 /// public const string Text = "text"; ////// 事件消息 /// public const string Event = "event"; ////// 位置消息 /// public const string Location = "location"; ////// 链接消息 /// public const string Link = "link"; } public class ReqEventType { ////// 关注消息 /// public const string Subscribe = "subscribe"; ////// 取消关注 /// public const string Unsubscribe = "unsubscribe"; ////// 菜单点击 /// public const string CLICK = "CLICK"; ////// 菜单跳转 /// public const string VIEW = "VIEW"; }