//<?xml version="1.0" encoding="utf-8"?> //<xml> // <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName> // <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName> // <CreateTime>1357986928</CreateTime> // <MsgType><![CDATA[text]]></MsgType> // <Content><![CDATA[中文]]></Content> // <MsgId>5832509444155992350</MsgId> //</xml> /// <summary> /// 获取XDocument转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(XDocument doc) { RequestMessageBase requestMessage = null; RequestMsgType msgType; try { msgType = MsgTypeHelper.GetRequestMsgType(doc); switch (msgType) { case RequestMsgType.Text: requestMessage = new RequestMessageText(); break; case RequestMsgType.Location: requestMessage = new RequestMessageLocation(); break; case RequestMsgType.Image: requestMessage = new RequestMessageImage(); break; case RequestMsgType.Voice: requestMessage = new RequestMessageVoice(); break; case RequestMsgType.Link: requestMessage = new RequestMessageLink(); break; case RequestMsgType.Event: //判断Event类型 switch (doc.Root.Element("Event").Value.ToUpper()) { case "ENTER"://进入会话 requestMessage = new RequestMessageEvent_Enter(); break; case "LOCATION"://地理位置 requestMessage = new RequestMessageEvent_Location(); break; case "SUBSCRIBE"://订阅(关注) requestMessage = new RequestMessageEvent_Subscribe(); break; case "UNSUBSCRIBE"://取消订阅(关注) requestMessage = new RequestMessageEvent_Unsubscribe(); break; case "CLICK"://菜单点击 requestMessage = new RequestMessageEvent_Click(); break; default://其他意外类型(也可以选择抛出异常) requestMessage = new RequestMessageEventBase(); break; } break; default: throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常 } EntityHelper.FillEntityWithXml(requestMessage, doc); } catch (ArgumentException ex) { throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex); } return requestMessage; }
public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as ResponseMessageText; responseMessage.Content = "文字信息"; return responseMessage; }
/// <summary> /// 推送纯文字 /// </summary> public IResponseMessageBase GetResponseMessageTxt(RequestMessageText requestMessage, int ruleId, int accountId) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); string openid = requestMessage.FromUserName; string token = ConvertDateTimeInt(DateTime.Now).ToString(); responseMessage.Content = new BLL.weixin_request_content().GetContent(ruleId); new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "text", responseMessage.Content, requestMessage.ToUserName); return responseMessage; }
/// <summary> /// 推送纯文字 /// </summary> /// <param name="id"></param> /// <returns></returns> public IResponseMessageBase GetResponseMessageTxt(RequestMessageText requestMessage, int Indexid, int wid) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); string openid = requestMessage.FromUserName; string token = ConvertDateTimeInt(DateTime.Now).ToString(); responseMessage.Content = getDataTxtComm(wid, Indexid, openid, token); wxResponseBaseMgr.Add(wid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "text", responseMessage.Content, requestMessage.ToUserName); return responseMessage; }
/// <summary> /// 将RequestMessageEventBase转换成RequestMessageText类型,其中Content = requestMessage.EventKey /// </summary> /// <param name="requestMessageEvent"></param> /// <returns></returns> public static RequestMessageText ConvertToRequestMessageText(this IRequestMessageEventBase requestMessageEvent) { var requestMessage = requestMessageEvent; var requestMessageText = new RequestMessageText() { FromUserName = requestMessage.FromUserName, ToUserName = requestMessage.ToUserName, CreateTime = requestMessage.CreateTime, MsgId = requestMessage.MsgId, Content = requestMessage.EventKey }; return requestMessageText; }
/// <summary> /// 推送多图文 /// </summary> public IResponseMessageBase GetResponseMessageNews(Senparc.Weixin.MP.Entities.RequestMessageText requestMessage, int ruleId, int accountId) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage); string openid = requestMessage.FromUserName; string token = ConvertDateTimeInt(DateTime.Now).ToString(); Article article; List <Article> artList = new List <Article>(); IList <Model.weixin_request_content> twList = new BLL.weixin_request_content().GetModelList(10, ruleId, string.Empty); foreach (Model.weixin_request_content modelt in twList) { article = new Article(); article.Title = modelt.title; article.Description = modelt.content; article.Url = GetWXApiUrl(modelt.link_url, token, openid); if (string.IsNullOrEmpty(modelt.img_url)) { article.PicUrl = string.Empty; } else { if (modelt.img_url.Contains("http://")) { article.PicUrl = modelt.img_url; } else { //因为安装目录是以/开头,所以去掉,以免出现双斜杆 article.PicUrl = siteConfig.weburl + "/" + siteConfig.webpath.Replace("/", "") + modelt.img_url; } } artList.Add(article); } if (artList.Count == 0) { new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "-1", requestMessage.ToUserName); } else { new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "这次发了" + artList.Count + "条图文", requestMessage.ToUserName); } responseMessage.Articles.AddRange(artList); return(responseMessage); }
public override IResponseMessageBase OnTextOrEventRequest(RequestMessageText requestMessage) { // 预处理文字或事件类型请求。 // 这个请求是一个比较特殊的请求,通常用于统一处理来自文字或菜单按钮的同一个执行逻辑, // 会在执行OnTextRequest或OnEventRequest之前触发,具有以下一些特征: // 1、如果返回null,则继续执行OnTextRequest或OnEventRequest // 2、如果返回不为null,则终止执行OnTextRequest或OnEventRequest,返回最终ResponseMessage // 3、如果是事件,则会将RequestMessageEvent自动转为RequestMessageText类型,其中RequestMessageText.Content就是RequestMessageEvent.EventKey //if (requestMessage.Content == "OneClick") //{ // var strongResponseMessage = CreateResponseMessage<ResponseMessageText>(); // strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行"; // return strongResponseMessage; //} return null;//返回null,则继续执行OnTextRequest或OnEventRequest }
/// <summary> /// 推送多图文 /// update note 1: /// 李朴 2013-8-20 添加会员卡的cardno参数 /// 注意:如果该会员注册过,则字符串没有cardno参数; /// 只有在会员注册过,在数据库里查询到该会员的cadno,则在url里添加节点cardno。 /// </summary> /// <param name="requestMessage"></param> /// <param name="Indexid"></param> /// <returns></returns> public IResponseMessageBase GetResponseMessageNews(RequestMessageText requestMessage, int Indexid, int wid) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(requestMessage); string openid = requestMessage.FromUserName; string token = ConvertDateTimeInt(DateTime.Now).ToString(); List<Article> picTxtList = getDataPicTxtComm(wid, Indexid, openid, token); if (picTxtList == null || picTxtList.Count <= 0) { wxResponseBaseMgr.Add(wid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "-1", requestMessage.ToUserName); } else { wxResponseBaseMgr.Add(wid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "这次发了" + picTxtList.Count + "条图文", requestMessage.ToUserName); } responseMessage.Articles.AddRange(picTxtList); return responseMessage; }
/// <summary> /// 处理文字请求 /// </summary> /// <returns></returns> public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { //TODO:这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs //方法一 //var responseMessage = // ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as // ResponseMessageText; //方法二 var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage); responseMessage.Content = string.Format( "您刚才发送了文字信息:{0}\r\n您还可以发送【位置】【图片】【语音】等类型的信息,查看不同格式的回复。\r\nSDK官方地址:http://weixin.senparc.com", requestMessage.Content); return responseMessage; }
/// <summary> /// 处理语音请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public IResponseMessageBase GetResponseMessageeMusic(RequestMessageText requestMessage, int Indexid, int wid) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageMusic>(requestMessage); Model.wx_requestRuleContent model_wx = getDataMusicComm(wid, Indexid); if (model_wx == null) { wxResponseBaseMgr.Add(wid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "music", "-1", requestMessage.ToUserName); } else { responseMessage.Music.MusicUrl = model_wx.mediaUrl; responseMessage.Music.Title = model_wx.rContent; responseMessage.Music.Description = model_wx.rContent2; wxResponseBaseMgr.Add(wid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "music", "音乐链接:" + model_wx.mediaUrl + "|标题:" + model_wx.rContent + "|描述:" + model_wx.rContent2, requestMessage.ToUserName); } return responseMessage; }
//<?xml version="1.0" encoding="utf-8"?> //<xml> // <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName> // <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName> // <CreateTime>1357986928</CreateTime> // <MsgType><![CDATA[text]]></MsgType> // <Content><![CDATA[中文]]></Content> // <MsgId>5832509444155992350</MsgId> //</xml> public static IRequestMessageBase GetRequestEntity(XDocument doc) { var msgType = MsgTypeHelper.GetMsgType(doc); RequestMessageBase requestMessage = null; switch (msgType) { case RequestMsgType.Text: requestMessage = new RequestMessageText(); break; case RequestMsgType.Location: requestMessage = new RequestMessageLocation(); break; case RequestMsgType.Image: requestMessage = new RequestMessageImage(); break; default: throw new ArgumentOutOfRangeException(); } EntityHelper.FillEntityWithXml(requestMessage, doc); return requestMessage; }
/// <summary> /// 将RequestMessageEventBase转换成RequestMessageText类型,其中Content = requestMessage.EventKey /// </summary> /// <param name="requestMessageEvent"></param> /// <returns></returns> public static RequestMessageText ConvertToRequestMessageText(this IRequestMessageEventBase requestMessageEvent) { var requestMessage = requestMessageEvent; var requestMessageText = new RequestMessageText() { FromUserName = requestMessage.FromUserName, ToUserName = requestMessage.ToUserName, CreateTime = requestMessage.CreateTime, MsgId = requestMessage.MsgId }; //判断是否具有EventKey属性 if (requestMessageEvent is IRequestMessageEventKey) { requestMessageText.Content = (requestMessageEvent as IRequestMessageEventKey).EventKey; } else { requestMessageText.Content = ""; } return requestMessageText; }
/// <summary> /// 推送纯文字 /// 2013-9-12 /// </summary> /// <param name="id"></param> /// <returns></returns> public IResponseMessageBase GetResponseMessageTxtByContent(RequestMessageText requestMessage, string content,int wid) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); var locationService = new LocationService(); responseMessage.Content = content; wxResponseBaseMgr.Add(wid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "text","文字请求,推送纯粹文字,内容为:"+ content, requestMessage.ToUserName); return responseMessage; }
/// <summary> /// 模块功能回复【请求为‘文字’类型】 /// </summary> /// <param name="requestMessage"></param> /// <param name="modelFunctionName"></param> /// <param name="modelFunctionId"></param> /// <param name="apiid"></param> /// <returns></returns> public IResponseMessageBase GetModuleResponse(RequestMessageText requestMessage, string modelFunctionName, int modelFunctionId, int apiid) { string openid = requestMessage.FromUserName; string token = ConvertDateTimeInt(DateTime.Now).ToString(); IList<Model.ResponseContentEntity> responselist = new List<Model.ResponseContentEntity>(); responselist= PanDuanMoudle(modelFunctionName, modelFunctionId, openid, apiid); if (responselist == null || responselist.Count <= 0) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); responseMessage.Content = "【" + modelFunctionName + "】功能模块未获得到数据"; return responseMessage; } Model.ReponseContentType responseType = responselist[0].rcType; if (responseType == Model.ReponseContentType.text) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); responseMessage.Content = responselist[0].rContent.ToString(); wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "text", responseMessage.Content, requestMessage.ToUserName); return responseMessage; } else if (responseType == Model.ReponseContentType.txtpic) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(requestMessage); IList<Article> rArticlelist = new List<Article>(); Article article = new Article(); foreach (Model.ResponseContentEntity response in responselist) { article = new Article(); article.Title = response.rContent; article.Description = response.rContent2; article.Url =getWXApiUrl(response.detailUrl, token, openid) + getWxUrl_suffix(); if (response.picUrl == null || response.picUrl.ToString().Trim() == "") { article.PicUrl = ""; } else { if (!response.picUrl.Contains("http://")) { article.PicUrl = MyCommFun.getWebSite() + response.picUrl; } else { article.PicUrl = response.picUrl; } } rArticlelist.Add(article); } responseMessage.Articles.AddRange(rArticlelist); wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "这次发了" + rArticlelist.Count+ "条图文", requestMessage.ToUserName); return responseMessage; } else { return null; } }
/// <summary> /// 获取请求XML /// </summary> /// <returns></returns> private XDocument GetrequestMessaageDoc(string url, string token, RequestMsgType requestType, Event? eventType) { RequestMessageBase requestMessaage = null; switch (requestType) { case RequestMsgType.Text: requestMessaage = new RequestMessageText() { Content = Request.Form["Content"], }; break; case RequestMsgType.Location: requestMessaage = new RequestMessageLocation() { Label = Request.Form["Label"], Location_X = double.Parse(Request.Form["Location_X"]), Location_Y = double.Parse(Request.Form["Location_Y"]), Scale = int.Parse(Request.Form["Scale"]) }; break; case RequestMsgType.Image: requestMessaage = new RequestMessageImage() { PicUrl = Request.Form["PicUrl"], }; break; case RequestMsgType.Voice: requestMessaage = new RequestMessageVoice() { Format = Request.Form["Format"], Recognition = Request.Form["Recognition"], }; break; case RequestMsgType.Video: requestMessaage = new RequestMessageVideo() { MsgId = long.Parse(Request.Form["MsgId"]), ThumbMediaId = Request.Form["ThumbMediaId"], }; break; //case RequestMsgType.Link: // break; case RequestMsgType.Event: if (eventType.HasValue) { RequestMessageEventBase requestMessageEvent = null; switch (eventType.Value) { //case Event.ENTER: // break; case Event.LOCATION: requestMessageEvent = new RequestMessageEvent_Location() { Latitude = long.Parse(Request.Form["Event.Latitude"]), Longitude = long.Parse(Request.Form["Event.Longitude"]), Precision = double.Parse(Request.Form["Event.Precision"]) }; break; case Event.subscribe: requestMessageEvent = new RequestMessageEvent_Subscribe() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.unsubscribe: requestMessageEvent = new RequestMessageEvent_Unsubscribe(); break; case Event.CLICK: requestMessageEvent = new RequestMessageEvent_Click() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.scan: requestMessageEvent = new RequestMessageEvent_Scan() { EventKey = Request.Form["Event.EventKey"], Ticket = Request.Form["Event.Ticket"] }; break; case Event.VIEW: requestMessageEvent = new RequestMessageEvent_View() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.MASSSENDJOBFINISH: requestMessageEvent = new RequestMessageEvent_MassSendJobFinish() { FromUserName = "******",//系统指定 ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]), FilterCount = int.Parse(Request.Form["Event.FilterCount"]), SendCount = int.Parse(Request.Form["Event.SendCount"]), Status = Request.Form["Event.Status"], TotalCount = int.Parse(Request.Form["Event.TotalCount"]) }; break; default: throw new ArgumentOutOfRangeException("eventType"); } requestMessaage = requestMessageEvent; } else { throw new ArgumentOutOfRangeException("eventType"); } break; default: throw new ArgumentOutOfRangeException("requestType"); } requestMessaage.CreateTime = DateTime.Now; requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户 requestMessaage.ToUserName = "******"; return requestMessaage.ConvertEntityToXml(); }
/// <summary> /// 处理文字请求 autor:lipu /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { IResponseMessageBase IR = null; int apiid = 0; try { // var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); string keywords = requestMessage.Content; //发送了文字信息 apiid = wxcomm.getApiid();//这里的appiid即为微帐号主键Id(wid) if (!wxcomm.ExistApiidAndWxId(apiid, requestMessage.ToUserName)) { //验证接收方是否为我们系统配置的帐号,即验证微帐号与微信原始帐号id是否一致,如果不一致,说明【1】配置错误,【2】数据来源有问题 wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "none", "验证微帐号与微信原始帐号id不一致,说明【1】配置错误,【2】数据来源有问题", requestMessage.ToUserName); return wxcomm.GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致,可能原因【1】系统配置错误,【2】非法的数据来源", apiid); } int responseType = 0; string modelFunctionName = ""; int modelFunctionId = 0; int ruleId = rBll.GetRuleIdByKeyWords(apiid, keywords, out responseType, out modelFunctionName, out modelFunctionId); if (ruleId <= 0 || responseType<=0) { // 2014-9-18 暂时性功能 针对ID为 gh_04bf23f25940的平台客户 保存发送者的ID 及 生成抽奖序号 并保存。 //if (requestMessage.ToUserName == "gh_04bf23f25940" && requestMessage.Content = "橘州抽奖") //{} //else //{ // 2014-9-18原功能 wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "none", "未取到关键词对应的数据", requestMessage.ToUserName); return wxcomm.GetResponseMessageTxtByContent(requestMessage,"未找到匹配的关键词",apiid); //} } if (modelFunctionId > 0) { //模块功能回复 return wxcomm.GetModuleResponse(requestMessage, modelFunctionName, modelFunctionId, apiid); } switch (responseType) { case 1: //发送纯文字 IR = wxcomm.GetResponseMessageTxt(requestMessage, ruleId, apiid); break; case 2: //发送多图文 IR = wxcomm.GetResponseMessageNews(requestMessage, ruleId, apiid); break; case 3: //发送语音 IR = wxcomm.GetResponseMessageeMusic(requestMessage, ruleId, apiid); break; default: break; } // wxRequestBaseMgr.Add(apiid, requestMessage.MsgType.ToString(), requestMessage.FromUserName, requestMessage.CreateTime.ToString(), requestMessage.Content, requestMessage.ToString()); } catch (Exception ex) { BLL.wx_logs logs = new BLL.wx_logs(); logs.AddErrLog(apiid, "用户请求文字", "CustomMessageHandler.OnTextRequest", "错误:"+ex.Message); } return IR; }
/// <summary> /// 文字类型请求 /// </summary> public abstract IResponseMessageBase OnTextRequest(RequestMessageText requestMessage);
private static readonly string _urlVote = ConfigurationManager.AppSettings["UrlVote"]; //投票大赛的地址 #endregion Fields #region Methods /// <summary> /// 获取XDocument转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(IWeChatManagementService service, XDocument doc, PostModel postModel = null) { RequestMessageBase requestMessage = null; RequestMsgType msgType; try { msgType = MsgTypeHelper.GetRequestMsgType(doc); switch (msgType) { case RequestMsgType.Text: requestMessage = new RequestMessageText(); requestMessage.FillEntityWithXml(doc); /*tim update by 2016-03-31*/ var rMessage = (RequestMessageText) requestMessage; //回复手机号重新绑定到会员 var b = System.Text.RegularExpressions.Regex.IsMatch(rMessage.Content.Trim(), @"^1[3|4|5|8][0-9]\d{8}$"); if (b) { var customerService = ServiceLocatorFactory.GetServiceLocator().GetService<ICustomerManagementService>(); var result = customerService.RebindFans(new CustRebindFansModel { Openid = rMessage.FromUserName, Mobile = rMessage.Content }); LoggerFactories.CreateLogger() .Write($"rebind result:{result.errcode}", TraceEventType.Information); } else { //处理投票活动消息 var result = HandleVote(rMessage.Content, requestMessage.FromUserName); if (result) { return requestMessage; } CustomApi.SendText(AppID, requestMessage.FromUserName, "感谢您的回复,玖伍淘车会尽快回复您。"); } break; case RequestMsgType.Location: requestMessage = new RequestMessageLocation(); break; case RequestMsgType.Image: requestMessage = new RequestMessageImage(); break; case RequestMsgType.Voice: requestMessage = new RequestMessageVoice(); break; case RequestMsgType.Video: requestMessage = new RequestMessageVideo(); break; case RequestMsgType.Link: requestMessage = new RequestMessageLink(); break; case RequestMsgType.ShortVideo: requestMessage = new RequestMessageShortVideo(); break; case RequestMsgType.Event: //判断Event类型 switch (doc.Root.Element("Event").Value.ToUpper()) { case "ENTER": //进入会话 requestMessage = new RequestMessageEvent_Enter(); break; case "LOCATION": //地理位置 requestMessage = new RequestMessageEvent_Location(); break; case "SUBSCRIBE": //订阅(关注) requestMessage = new RequestMessageEvent_Subscribe(); EntityHelper.FillEntityWithXml(requestMessage, doc); var taskSubscribe = new Task(() => { service.GenerateWechatFriend(AppID, requestMessage.FromUserName, true); }); taskSubscribe.Start(); var slogan = _slogan.Replace("\\n", Environment.NewLine); //"\n\n<a src=''>点击参加玖伍淘车首届“/强绝代车王/强”微信自拍投票大赛<a/>"; var btnContent = ConfigurationManager.AppSettings["BtnContent"]; var tourl = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={AppID}&redirect_uri={_urlVote}&response_type=code&scope=snsapi_base&state=vote&connect_redirect=1#wechat_redirect"; btnContent = $"<a href=\"{tourl}\">{btnContent}</a>"; slogan = string.Concat(slogan, Environment.NewLine, btnContent); CustomApi.SendText(AppID, requestMessage.FromUserName, slogan); //判断是否扫描场景二维码关注 var xElement = doc.Root.Element("EventKey"); if (xElement != null && xElement.Value.Contains("qrscene_")) { var code = xElement.Value.Replace("qrscene_", ""); service.UpdateWechatFriendQrScene(requestMessage.FromUserName, code, AppID); } break; case "UNSUBSCRIBE": //取消订阅(关注) requestMessage = new RequestMessageEvent_Unsubscribe(); EntityHelper.FillEntityWithXml(requestMessage, doc); service.UpdateWechatFriendUnSubscribe(AppID, requestMessage.FromUserName); var activityservice = ServiceLocatorFactory.GetServiceLocator().GetService<IActivityManagementService>(); activityservice.UnSubscribe(AppID, requestMessage.FromUserName); break; case "CLICK": //菜单点击 requestMessage = new RequestMessageEvent_Click(); break; case "SCAN": //二维码扫描 requestMessage = new RequestMessageEvent_Scan(); break; case "VIEW": //URL跳转 requestMessage = new RequestMessageEvent_View(); break; case "MASSSENDJOBFINISH": requestMessage = new RequestMessageEvent_MassSendJobFinish(); break; case "TEMPLATESENDJOBFINISH": //模板信息 requestMessage = new RequestMessageEvent_TemplateSendJobFinish(); break; case "SCANCODE_PUSH": //扫码推事件(scancode_push) requestMessage = new RequestMessageEvent_Scancode_Push(); break; case "SCANCODE_WAITMSG": //扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg) requestMessage = new RequestMessageEvent_Scancode_Waitmsg(); break; case "PIC_SYSPHOTO": //弹出系统拍照发图(pic_sysphoto) requestMessage = new RequestMessageEvent_Pic_Sysphoto(); break; case "PIC_PHOTO_OR_ALBUM": //弹出拍照或者相册发图(pic_photo_or_album) requestMessage = new RequestMessageEvent_Pic_Photo_Or_Album(); break; case "PIC_WEIXIN": //弹出微信相册发图器(pic_weixin) requestMessage = new RequestMessageEvent_Pic_Weixin(); break; case "LOCATION_SELECT": //弹出地理位置选择器(location_select) requestMessage = new RequestMessageEvent_Location_Select(); break; case "CARD_PASS_CHECK": //卡券通过审核 requestMessage = new RequestMessageEvent_Card_Pass_Check(); break; case "CARD_NOT_PASS_CHECK": //卡券未通过审核 requestMessage = new RequestMessageEvent_Card_Not_Pass_Check(); break; case "USER_GET_CARD": //领取卡券 requestMessage = new RequestMessageEvent_User_Get_Card(); break; case "USER_DEL_CARD": //删除卡券 requestMessage = new RequestMessageEvent_User_Del_Card(); break; case "KF_CREATE_SESSION": //多客服接入会话 requestMessage = new RequestMessageEvent_Kf_Create_Session(); break; case "KF_CLOSE_SESSION": //多客服关闭会话 requestMessage = new RequestMessageEvent_Kf_Close_Session(); break; case "KF_SWITCH_SESSION": //多客服转接会话 requestMessage = new RequestMessageEvent_Kf_Switch_Session(); break; case "POI_CHECK_NOTIFY": //审核结果事件推送 requestMessage = new RequestMessageEvent_Poi_Check_Notify(); break; case "WIFICONNECTED": //Wi-Fi连网成功事件 requestMessage = new RequestMessageEvent_WifiConnected(); break; case "USER_CONSUME_CARD": //卡券核销 requestMessage = new RequestMessageEvent_User_Consume_Card(); break; case "USER_ENTER_SESSION_FROM_CARD": //从卡券进入公众号会话 requestMessage = new RequestMessageEvent_User_Enter_Session_From_Card(); break; case "USER_VIEW_CARD": //进入会员卡 requestMessage = new RequestMessageEvent_User_View_Card(); break; case "MERCHANT_ORDER": //微小店订单付款通知 requestMessage = new RequestMessageEvent_Merchant_Order(); var merchantOrderresult = (RequestMessageEvent_Merchant_Order) requestMessage; EntityHelper.FillEntityWithXml(requestMessage, doc); var orderresult = OrderApi.GetByIdOrder(AppID, merchantOrderresult.OrderId); if (orderresult.errcode == ReturnCode.请求成功) { var rewardsManagementService = ServiceLocatorFactory.GetServiceLocator() .GetService<IRewardsManagementService>(); var wholesaleCouponresult = rewardsManagementService.WholesaleCoupon(new CouponBuyModel() { //ProductId = orderresult.order.product_id, //OrderId = orderresult.order.order_id, //Accountid = AppID, //Number = orderresult.order.product_count, //Openid = orderresult.order.buyer_openid Order = orderresult.order }); var text = JsonConvert.SerializeObject(orderresult.order); var logresult = $"MERCHANT_ORDER:{text} result:{JsonConvert.SerializeObject(wholesaleCouponresult)}"; LoggerFactories.CreateLogger().Write(logresult, TraceEventType.Information); } break; case "SUBMIT_MEMBERCARD_USER_INFO": //接收会员信息事件通知 requestMessage = new RequestMessageEvent_Submit_Membercard_User_Info(); break; case "SHAKEAROUNDUSERSHAKE": //摇一摇事件通知 requestMessage = new RequestMessageEvent_ShakearoundUserShake(); break; default: //其他意外类型(也可以选择抛出异常) requestMessage = new RequestMessageEventBase(); break; } break; default: throw new UnknownRequestMsgTypeException( $"MsgType:{msgType} 在RequestMessageFactory中没有对应的处理程序!", new ArgumentOutOfRangeException()); //为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常 } } catch (ArgumentException ex) { //throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex); LoggerFactories.CreateLogger() .Write($"RequestMessage转换出错!可能是MsgType不存在!,XML:{doc}", TraceEventType.Error, ex); } return requestMessage; }
/// <summary> /// 处理语音请求 /// </summary> public IResponseMessageBase GetResponseMessageeMusic(RequestMessageText requestMessage, int ruleId, int accountId) { string EventName = ""; var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageMusic>(requestMessage); Model.weixin_request_content model = new BLL.weixin_request_content().GetModel(ruleId); if (model == null) { new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "music", "-1", requestMessage.ToUserName); } else { if (model.media_url.Contains("http://")) { responseMessage.Music.MusicUrl = model.media_url; } else { //因为安装目录是以/开头,所以去掉,以免出现双斜杆 responseMessage.Music.MusicUrl = siteConfig.weburl + "/" + siteConfig.webpath.Replace("/", "") + model.media_url; } responseMessage.Music.Title = model.title; responseMessage.Music.Description = model.content; new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "music", "音乐链接:" + model.media_url + "|标题:" + model.title + "|描述:" + model.content, requestMessage.ToUserName); } return responseMessage; }
/// <summary> /// 获取请求XML /// </summary> /// <returns></returns> private XDocument GetrequestMessaageDoc(string url, string token, RequestMsgType requestType, Event? eventType) { RequestMessageBase requestMessaage = null; switch (requestType) { case RequestMsgType.Text: requestMessaage = new RequestMessageText() { Content = Request.Form["Content"], }; break; case RequestMsgType.Location: requestMessaage = new RequestMessageLocation() { Label = Request.Form["Label"], Location_X = double.Parse(Request.Form["Location_X"]), Location_Y = double.Parse(Request.Form["Location_Y"]), Scale = int.Parse(Request.Form["Scale"]) }; break; case RequestMsgType.Image: requestMessaage = new RequestMessageImage() { PicUrl = Request.Form["PicUrl"], }; break; case RequestMsgType.Voice: requestMessaage = new RequestMessageVoice() { Format = Request.Form["Format"], Recognition = Request.Form["Recognition"], }; break; case RequestMsgType.Video: requestMessaage = new RequestMessageVideo() { MsgId = long.Parse(Request.Form["MsgId"]), ThumbMediaId = Request.Form["ThumbMediaId"], }; break; //case RequestMsgType.Link: // break; case RequestMsgType.Event: if (eventType.HasValue) { RequestMessageEventBase requestMessageEvent = null; switch (eventType.Value) { //case Event.ENTER: // break; case Event.LOCATION: requestMessageEvent = new RequestMessageEvent_Location() { Latitude = long.Parse(Request.Form["Event.Latitude"]), Longitude = long.Parse(Request.Form["Event.Longitude"]), Precision = double.Parse(Request.Form["Event.Precision"]) }; break; case Event.subscribe: requestMessageEvent = new RequestMessageEvent_Subscribe() { EventKey = Request.Form["Event.EventKey"], Ticket = Request.Form["Event.Ticket"] }; break; case Event.unsubscribe: requestMessageEvent = new RequestMessageEvent_Unsubscribe(); break; case Event.CLICK: requestMessageEvent = new RequestMessageEvent_Click() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.scan: requestMessageEvent = new RequestMessageEvent_Scan() { EventKey = Request.Form["Event.EventKey"], Ticket = Request.Form["Event.Ticket"] }; break; case Event.VIEW: requestMessageEvent = new RequestMessageEvent_View() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.MASSSENDJOBFINISH: requestMessageEvent = new RequestMessageEvent_MassSendJobFinish() { FromUserName = "******",//系统指定 ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]), FilterCount = int.Parse(Request.Form["Event.FilterCount"]), SentCount = int.Parse(Request.Form["Event.SentCount"]), Status = Request.Form["Event.Status"], TotalCount = int.Parse(Request.Form["Event.TotalCount"]) }; break; case Event.TEMPLATESENDJOBFINISH: requestMessageEvent = new RequestMessageEvent_TemplateSendJobFinish() { FromUserName = "******",//系统指定 MsgID = long.Parse(Request.Form["Event.MsgID"]), Status = Request.Form["Event.Status"], }; break; case Event.scancode_push: requestMessageEvent = new RequestMessageEvent_Scancode_Push() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], ScanCodeInfo = new ScanCodeInfo() { ScanResult = Request.Form["Event.ScanResult"], ScanType = Request.Form["Event.ScanType"], } }; break; case Event.scancode_waitmsg: requestMessageEvent = new RequestMessageEvent_Scancode_Waitmsg() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], ScanCodeInfo = new ScanCodeInfo() { ScanResult = Request.Form["Event.ScanResult"], ScanType = Request.Form["Event.ScanType"], } }; break; case Event.pic_sysphoto: var sysphotoPicMd5Sum = Request.Form["Event.PicMd5Sum"]; PicItem sysphotoPicItem = new PicItem() { item = new Md5Sum() { PicMd5Sum = sysphotoPicMd5Sum } }; List<PicItem> sysphotoPicItems = new List<PicItem>(); sysphotoPicItems.Add(sysphotoPicItem); requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendPicsInfo = new SendPicsInfo() { Count = Request.Form["Event.Count"], PicList = sysphotoPicItems } }; break; case Event.pic_photo_or_album: var photoOrAlbumPicMd5Sum = Request.Form["Event.PicMd5Sum"]; PicItem photoOrAlbumPicItem = new PicItem() { item = new Md5Sum() { PicMd5Sum = photoOrAlbumPicMd5Sum } }; List<PicItem> photoOrAlbumPicItems = new List<PicItem>(); photoOrAlbumPicItems.Add(photoOrAlbumPicItem); requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendPicsInfo = new SendPicsInfo() { Count = Request.Form["Event.Count"], PicList = photoOrAlbumPicItems } }; break; case Event.pic_weixin: var weixinPicMd5Sum = Request.Form["Event.PicMd5Sum"]; PicItem weixinPicItem = new PicItem() { item = new Md5Sum() { PicMd5Sum = weixinPicMd5Sum } }; List<PicItem> weixinPicItems = new List<PicItem>(); weixinPicItems.Add(weixinPicItem); requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendPicsInfo = new SendPicsInfo() { Count = Request.Form["Event.Count"], PicList = weixinPicItems } }; break; case Event.location_select: requestMessageEvent = new RequestMessageEvent_Location_Select() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendLocationInfo = new SendLocationInfo() { Label = Request.Form["Event.Label"], Location_X = Request.Form["Event.Location_X"], Location_Y = Request.Form["Event.Location_Y"], Poiname = Request.Form["Event.Poiname"], Scale = Request.Form["Event.Scale"], } }; break; default: throw new ArgumentOutOfRangeException("eventType"); } requestMessaage = requestMessageEvent; } else { throw new ArgumentOutOfRangeException("eventType"); } break; default: throw new ArgumentOutOfRangeException("requestType"); } requestMessaage.MsgId = long.Parse(Request.Form["MsgId"]); requestMessaage.CreateTime = DateTime.Now; requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户 requestMessaage.ToUserName = "******"; return requestMessaage.ConvertEntityToXml(); }
/// <summary> /// 推送多图文 /// </summary> public IResponseMessageBase GetResponseMessageNews(RequestMessageText requestMessage, int ruleId, int accountId) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(requestMessage); string openid = requestMessage.FromUserName; string token = ConvertDateTimeInt(DateTime.Now).ToString(); Article article; List<Article> artList = new List<Article>(); IList<Model.weixin_request_content> twList = new BLL.weixin_request_content().GetModelList(10, ruleId, string.Empty); foreach (Model.weixin_request_content modelt in twList) { article = new Article(); article.Title = modelt.title; article.Description = modelt.content; article.Url = GetWXApiUrl(modelt.link_url, token, openid); if (string.IsNullOrEmpty(modelt.img_url)) { article.PicUrl = string.Empty; } else { if (modelt.img_url.Contains("http://")) { article.PicUrl = modelt.img_url; } else { //因为安装目录是以/开头,所以去掉,以免出现双斜杆 article.PicUrl = siteConfig.weburl + "/" + siteConfig.webpath.Replace("/", "") + modelt.img_url; } } artList.Add(article); } if (artList.Count == 0) { new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "-1", requestMessage.ToUserName); } else { new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "txtpic", "这次发了" + artList.Count + "条图文", requestMessage.ToUserName); } responseMessage.Articles.AddRange(artList); return responseMessage; }
//<?xml version="1.0" encoding="utf-8"?> //<xml> // <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName> // <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName> // <CreateTime>1357986928</CreateTime> // <MsgType><![CDATA[text]]></MsgType> // <Content><![CDATA[中文]]></Content> // <MsgId>5832509444155992350</MsgId> //</xml> /// <summary> /// 获取XDocument转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(XDocument doc, PostModel postModel = null) { RequestMessageBase requestMessage = null; RequestMsgType msgType; try { msgType = MsgTypeHelper.GetRequestMsgType(doc); switch (msgType) { case RequestMsgType.Text: requestMessage = new RequestMessageText(); break; case RequestMsgType.Location: requestMessage = new RequestMessageLocation(); break; case RequestMsgType.Image: requestMessage = new RequestMessageImage(); break; case RequestMsgType.Voice: requestMessage = new RequestMessageVoice(); break; case RequestMsgType.Video: requestMessage = new RequestMessageVideo(); break; case RequestMsgType.Link: requestMessage = new RequestMessageLink(); break; case RequestMsgType.ShortVideo: requestMessage = new RequestMessageShortVideo(); break; case RequestMsgType.Event: //判断Event类型 switch (doc.Root.Element("Event").Value.ToUpper()) { case "ENTER"://进入会话 requestMessage = new RequestMessageEvent_Enter(); break; case "LOCATION"://地理位置 requestMessage = new RequestMessageEvent_Location(); break; case "SUBSCRIBE"://订阅(关注) requestMessage = new RequestMessageEvent_Subscribe(); break; case "UNSUBSCRIBE"://取消订阅(关注) requestMessage = new RequestMessageEvent_Unsubscribe(); break; case "CLICK"://菜单点击 requestMessage = new RequestMessageEvent_Click(); break; case "SCAN"://二维码扫描 requestMessage = new RequestMessageEvent_Scan(); break; case "VIEW"://URL跳转 requestMessage = new RequestMessageEvent_View(); break; case "MASSSENDJOBFINISH": requestMessage = new RequestMessageEvent_MassSendJobFinish(); break; case "TEMPLATESENDJOBFINISH"://模板信息 requestMessage = new RequestMessageEvent_TemplateSendJobFinish(); break; case "SCANCODE_PUSH"://扫码推事件(scancode_push) requestMessage = new RequestMessageEvent_Scancode_Push(); break; case "SCANCODE_WAITMSG"://扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg) requestMessage = new RequestMessageEvent_Scancode_Waitmsg(); break; case "PIC_SYSPHOTO"://弹出系统拍照发图(pic_sysphoto) requestMessage = new RequestMessageEvent_Pic_Sysphoto(); break; case "PIC_PHOTO_OR_ALBUM"://弹出拍照或者相册发图(pic_photo_or_album) requestMessage = new RequestMessageEvent_Pic_Photo_Or_Album(); break; case "PIC_WEIXIN"://弹出微信相册发图器(pic_weixin) requestMessage = new RequestMessageEvent_Pic_Weixin(); break; case "LOCATION_SELECT"://弹出地理位置选择器(location_select) requestMessage = new RequestMessageEvent_Location_Select(); break; case "CARD_PASS_CHECK"://卡券通过审核 requestMessage = new RequestMessageEvent_Card_Pass_Check(); break; case "CARD_NOT_PASS_CHECK"://卡券未通过审核 requestMessage = new RequestMessageEvent_Card_Not_Pass_Check(); break; case "USER_GET_CARD"://领取卡券 requestMessage = new RequestMessageEvent_User_Get_Card(); break; case "USER_DEL_CARD"://删除卡券 requestMessage = new RequestMessageEvent_User_Del_Card(); break; case "KF_CREATE_SESSION"://多客服接入会话 requestMessage = new RequestMessageEvent_Kf_Create_Session(); break; case "KF_CLOSE_SESSION"://多客服关闭会话 requestMessage = new RequestMessageEvent_Kf_Close_Session(); break; case "KF_SWITCH_SESSION"://多客服转接会话 requestMessage = new RequestMessageEvent_Kf_Switch_Session(); break; case "POI_CHECK_NOTIFY"://审核结果事件推送 requestMessage = new RequestMessageEvent_Poi_Check_Notify(); break; case "WIFICONNECTED"://Wi-Fi连网成功事件 requestMessage = new RequestMessageEvent_WifiConnected(); break; case "USER_CONSUME_CARD"://卡券核销 requestMessage = new RequestMessageEvent_User_Consume_Card(); break; case "USER_ENTER_SESSION_FROM_CARD"://从卡券进入公众号会话 requestMessage = new RequestMessageEvent_User_Enter_Session_From_Card(); break; case "USER_VIEW_CARD"://进入会员卡 requestMessage = new RequestMessageEvent_User_View_Card(); break; case "MERCHANT_ORDER"://微小店订单付款通知 requestMessage = new RequestMessageEvent_Merchant_Order(); break; case "SUBMIT_MEMBERCARD_USER_INFO"://接收会员信息事件通知 requestMessage = new RequestMessageEvent_Submit_Membercard_User_Info(); break; default://其他意外类型(也可以选择抛出异常) requestMessage = new RequestMessageEventBase(); break; } break; default: throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常 } EntityHelper.FillEntityWithXml(requestMessage, doc); } catch (ArgumentException ex) { throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex); } return requestMessage; }
/// <summary> /// 推送纯文字 /// </summary> public IResponseMessageBase GetResponseMessageTxtByContent(RequestMessageText requestMessage, string content, int accountId) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); responseMessage.Content = content; new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "text", "文字请求,推送纯粹文字,内容为:" + content, requestMessage.ToUserName); return responseMessage; }
//<?xml version="1.0" encoding="utf-8"?> //<xml> // <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName> // <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName> // <CreateTime>1357986928</CreateTime> // <MsgType><![CDATA[text]]></MsgType> // <Content><![CDATA[中文]]></Content> // <MsgId>5832509444155992350</MsgId> //</xml> /// <summary> /// 获取XDocument转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(XDocument doc) { RequestMessageBase requestMessage = null; RequestMsgType msgType; try { msgType = MsgTypeHelper.GetRequestMsgType(doc); switch (msgType) { case RequestMsgType.Text: requestMessage = new RequestMessageText(); break; case RequestMsgType.Location: requestMessage = new RequestMessageLocation(); break; case RequestMsgType.Image: requestMessage = new RequestMessageImage(); break; case RequestMsgType.Voice: requestMessage = new RequestMessageVoice(); break; case RequestMsgType.Video: requestMessage = new RequestMessageVideo(); break; case RequestMsgType.Link: requestMessage = new RequestMessageLink(); break; case RequestMsgType.ShortVideo: requestMessage = new RequestMessageShortVideo(); break; case RequestMsgType.Event: //判断Event类型 switch (doc.Root.Element("Event").Value.ToUpper()) { case "ENTER"://进入会话 requestMessage = new RequestMessageEvent_Enter(); break; case "LOCATION"://地理位置 requestMessage = new RequestMessageEvent_Location(); break; case "SUBSCRIBE"://订阅(关注) requestMessage = new RequestMessageEvent_Subscribe(); break; case "UNSUBSCRIBE"://取消订阅(关注) requestMessage = new RequestMessageEvent_Unsubscribe(); break; case "CLICK"://菜单点击 requestMessage = new RequestMessageEvent_Click(); break; case "SCAN"://二维码扫描 requestMessage = new RequestMessageEvent_Scan(); break; case "VIEW"://URL跳转 requestMessage = new RequestMessageEvent_View(); break; case "MASSSENDJOBFINISH": //事件推送群发 requestMessage = new RequestMessageEvent_MassSendJobFinish(); break; case "TEMPLATESENDJOBFINISH"://模板信息 requestMessage = new RequestMessageEvent_TemplateSendJobFinish(); break; case "SCANCODE_PUSH"://扫码推事件(scancode_push) requestMessage = new RequestMessageEvent_Scancode_Push(); break; case "SCANCODE_WAITMSG"://扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg) requestMessage = new RequestMessageEvent_Scancode_Waitmsg(); break; default://其他意外类型(也可以选择抛出异常) requestMessage = new RequestMessageEventBase(); break; } break; default: throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常 } EntityHelper.FillEntityWithXml(requestMessage, doc); } catch (ArgumentException ex) { throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex); } return requestMessage; }
public override IResponseMessageBase OnTextOrEventRequest(RequestMessageText requestMessage) { return null; string txt = requestMessage.Content.ToLower(); if (Regex.IsMatch(txt, "^(a|b|c)$", RegexOptions.IgnoreCase)) { return WeixinRender.Render(this, "res:" + txt); } if (!String.IsNullOrEmpty(Variables.WxDefaultResponseMessage)) { var strongResponseMessage = CreateResponseMessage<ResponseMessageText>(); strongResponseMessage.Content = Variables.WxDefaultResponseMessage; return strongResponseMessage; } return null; // 预处理文字或事件类型请求。 // 这个请求是一个比较特殊的请求,通常用于统一处理来自文字或菜单按钮的同一个执行逻辑, // 会在执行OnTextRequest或OnEventRequest之前触发,具有以下一些特征: // 1、如果返回null,则继续执行OnTextRequest或OnEventRequest // 2、如果返回不为null,则终止执行OnTextRequest或OnEventRequest,返回最终ResponseMessage // 3、如果是事件,则会将RequestMessageEvent自动转为RequestMessageText类型,其中RequestMessageText.Content就是RequestMessageEvent.EventKey return null; if (requestMessage.Content == "OneClick") { var strongResponseMessage = CreateResponseMessage<ResponseMessageText>(); strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行"; return strongResponseMessage; } return null;//返回null,则继续执行OnTextRequest或OnEventRequest }