public WechatContext(WechatMsgRequestModel request) { Logger.Debug("微信服务器消息:" + JsonConvert.SerializeObject(request)); _securityHelper = new WechatSecurityHelper(request.Msg_Signature, request.Timestamp, request.Nonce); _requestMessage = _securityHelper.DecryptMsg(request.RequestContent); Logger.Debug("收到微信消息:" + _requestMessage); }
/// <summary> /// 普通用户调用 /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> private DirectoryEntry GetDirectoryObject(string userName, string password) { try { var adPathList = ADPath.Split('|'); foreach (var path in adPathList) { try { var entry = new DirectoryEntry(path, userName, password, AuthenticationTypes.Secure); Object native = entry.NativeObject; return(entry); } catch (Exception ex) { logHelper.Debug($"Ad:GetDirectoryObject出错:{ex.Message}", ex); continue; } } return(null); } catch (Exception ex) { logHelper.Debug($"Ad:GetDirectoryObject出错:{ex.Message}", ex); return(null); } }
/// <summary> /// 定时推送 /// </summary> /// <returns></returns> public async Task <Result> TimingPush() { // todo改成多线程推送 var dtNow = DateTime.Now; // 获取当前时间间隔在1分钟之内的任务 var lstPushConf = await repo.QueryAsync <WxAutoPushShow>(x => x.IsDel == 0 && x.PushTime >= dtNow.AddMinutes(-TimingSpanMin) && x.PushTime < dtNow.AddMinutes(TimingSpanMin)); foreach (var push in lstPushConf) { try { // 查询推送用户列表 logHelper.Debug("AutoPushJob:任务信息:" + ComHelper.JsonSerialize(push)); string strSql = Get2DayActWxUserSql(push); var lstWxUser = await repo.SqlQueryAsync <WxUserInfo>(strSql, new { CreateTime = dtNow.AddDays(-2) }); logHelper.Debug("AutoPushJob:符合任务ID:" + push.Id + "任务名:" + push.PushName + "的用户有:" + lstWxUser.Select(x => x.OpenId).Distinct().JsonSerializeNoNull()); // 推送消息 await PushMsgToUser(push, lstWxUser); } catch (Exception ex) { logHelper.Error("AutoPushJob:获取定时推送消息失败:" + ex.Message + " " + ex.StackTrace); } } return(new Result { IsSucc = true, Message = "定时推送任务执行完成!" }); }
/// <summary> /// 处理企业号推送事件 /// </summary> /// <param name="recMsg"></param> /// <returns></returns> public async Task <string> DealQyEvent(PubReceiveMsgCData recMsg) { try { switch (recMsg.Event) { case PubEventType.subscribe: await DealWxSubscribe(recMsg); // 关注后判断扫码事件处理 await DealWxscan(recMsg); break; case PubEventType.unsubscribe: await DealWxUnsubscribe(recMsg); break; case PubEventType.scan: await DealWxscan(recMsg); break; case PubEventType.location: logHelper.Debug("location"); break; case PubEventType.location_select: logHelper.Debug("location"); break; case PubEventType.click: await DealWxClick(recMsg); break; case PubEventType.view: logHelper.Debug("view"); break; case PubEventType.poi_check_notify: logHelper.Debug("poi_check_notify"); break; default: break; } } catch (Exception ex) { logHelper.Error("DealQyEvent:处理企业号推送事件失败:" + ex.Message + " " + ex.StackTrace); } return(wxAutoComResponse.ResponseOK());; }
///// <summary> ///// 构造方法 ///// </summary> ///// <param name="logHelper"></param> ///// <param name="autoPushSvc"></param> //public AutoPushJob(ILogHelper<AutoPushJob> logHelper, AutoPushSvc autoPushSvc) //{ // this.logHelper = logHelper; // this.autoPushSvc = autoPushSvc; //} /// <summary> /// 执行定时任务 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Execute(IJobExecutionContext context) { this.serviceProvider = StaticServiceProvider.Current; this.logHelper = serviceProvider.GetRequiredService <ILogHelper <AutoPushJob> >(); this.autoPushSvc = serviceProvider.GetRequiredService <AutoPushSvc>(); logHelper.Debug($"AutoPushJob:微信定时推送任务开始执行:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} "); await autoPushSvc.TimingPush(); logHelper.Debug($"AutoPushJob:微信定时推送任务执行结束:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} "); }
public Result <string> SaveMedia([FromBody] WxMediaShow item) { try { if (string.IsNullOrEmpty(item.Type) || string.IsNullOrEmpty(item.LocalUrl)) { return(new Result <string> { Message = "保存失败:参数不足!" }); } var mType = ComHelper.GetEnumValueByStr <PubMediaType>(item.Type); var filePath = ComHelper.GetPhyWWWRoot(item.LocalUrl); // 上传永久素材 var upRes = PubMediaApi.AddMaterial(mType, filePath, item.Title, item.Introduction); logHelper.Debug("SaveMedia:上传微信永久素材结果:" + upRes.JsonSerialize()); if (!upRes.IsSuss) { var msg = "上传微信永久素材失败:" + upRes.errcode + " " + upRes.errmsg; logHelper.Debug("SaveMedia:" + msg); return(new Result <string> { Message = msg }); } // 保存上传结果 var userName = currentUser.UserName; var dtNow = DateTime.Now; item.MediaId = upRes.media_id; item.WxUrl = upRes.url; item.Creater = userName; item.Updater = userName; item.CreateTime = dtNow; item.UpdateTime = dtNow; repo.Save(item); return(new Result <string> { IsSucc = true, Message = "保存永久素材成功!" }); } catch (Exception ex) { logHelper.Error("SaveMedia:保存永久素材失败:" + ex.Message + " " + ex.StackTrace); } return(new Result <string> { Message = "保存永久素材失败!" }); }
/// <summary> /// 保存微信日志到数据库 /// </summary> /// <returns></returns> public async Task SaveWxOptLog(PubReceiveMsgCData recMsg) { try { // 判断是否重复提交 var exist = await repo.FirstOrDefaultAsync <WxUserOptLog>(d => d.FromUserName == recMsg.FromUserName && d.CreateTime == recMsg.DtCreateTime); if (exist != null) { logHelper.Debug("重复的微信请求(微信首次请求我方服务器已保存记录但未返回正确回应的二次请求),不保存!IopenId:" + recMsg.FromUserName); return; } // 保存微信日志 var wxLog = new WxUserOptLog(); wxLog.MsgId = recMsg.MsgId.ToString(); wxLog.ToUserName = recMsg.ToUserName; wxLog.FromUserName = recMsg.FromUserName; wxLog.CreateTime = recMsg.DtCreateTime.Value; wxLog.MsgType = recMsg.MsgType.ToString(); wxLog.Content = recMsg.Content; wxLog.PicUrl = recMsg.PicUrl; wxLog.MediaId = recMsg.MediaId; wxLog.Format = recMsg.Format; wxLog.ThumbMediaId = recMsg.ThumbMediaId; wxLog.LocationX_Latitude = recMsg.Location_X.ToString(); wxLog.LocationY_Longitude = recMsg.Location_Y.ToString(); wxLog.Scale = recMsg.Scale.ToString(); wxLog.LabelPrecision = recMsg.Label; wxLog.Title = recMsg.Title; wxLog.Description = recMsg.Description; wxLog.Url = recMsg.Url; wxLog.Event = recMsg.Event.ToString(); wxLog.EventKey = recMsg.EventKey; wxLog.Ticket = recMsg.Ticket; wxLog.Creater = "system"; wxLog.CreateTime = recMsg.DtCreateTime.Value; wxLog.Updater = "system"; wxLog.UpdateTime = recMsg.DtCreateTime.Value; await repo.SaveAsync(wxLog); logHelper.Debug("SaveWxDbLog:保存微信日志到数据成功:" + ComHelper.JsonSerialize(wxLog)); } catch (Exception ex) { logHelper.Error("SaveWxDbLog:保存微信日志到数据失败:" + ex.Message + " " + ex.StackTrace); } }
/// <summary> /// 处理关键字 /// </summary> /// <param name="gzhClient"></param> /// <param name="gzhServer"></param> /// <param name="keyword"></param> /// <returns></returns> public async Task <string> DealWithKeyWord(string gzhClient, string gzhServer, string keyword) { // 当前时间 var dtNow = DateTime.Now; var timeStamp = ComHelper.ConvertDateTimeInt(dtNow); // 当前微信用户信息 var wxUser = await repo.FirstOrDefaultAsync <WxUserInfo>(x => x.OpenId == gzhClient); // 自动应答的内容 WxAutoKeywordShow autoKeyword = null; // 超过1条的相同关键字的自动回复 改用客服消息发送 var lstOthers = new List <WxAutoKeywordShow> { }; if (keyword == "openid") { return(await wxAutoComResponse.SendWxText(gzhClient, gzhServer, timeStamp, "您的OpenId为:" + gzhClient)); } else { var sql = string.Format(@" SELECT * FROM WxAutoKeyword WHERE IsDel = 0 AND CONCAT('、',KeyWords,'、') LIKE '%、{0}、%' ORDER BY CreateTime DESC LIMIT 5 ", keyword); var lstKeywords = await repo.SqlQueryAsync <WxAutoKeywordShow>(sql); if (lstKeywords.Count > 0) { autoKeyword = lstKeywords[0]; } // 发送客服消息 if (lstKeywords.Count > 1) { lstOthers = lstKeywords.Skip(1).Take(4).ToList(); } } // 公众号自动应答回复第一条关键字消息 if (autoKeyword == null) { var msg = "DealQyText:无法找到对应关键字活动:" + keyword; logHelper.Debug(msg); return(wxAutoComResponse.ResponseOK()); } // 其他发送客服消息(不等待) SendKfAutoKeyword(wxUser, lstOthers); // 根据不同类型推送消息 return(await SendMsgByPush(gzhClient, gzhServer, autoKeyword, wxUser)); }
/// <summary> /// 自动推送红包(公众号自动回复) /// </summary> /// <param name="gzhClient"></param> /// <param name="gzhSever"></param> /// <param name="autoKeyword"></param> /// <param name="dtNow"></param> /// <param name="timeStamp"></param> /// <returns></returns> public async Task <string> SendResponseRedPack(string gzhClient, string gzhSever, WxAutoKeywordShow autoKeyword, DateTime dtNow, int timeStamp) { // 红包只能8点之后领取 if (dtNow.Hour < 8) { return(await wxAutoComResponse.SendWxText(gzhSever, gzhClient, timeStamp, "亲:微信红包将于8点到24点之间才能领取")); } // 红包参数配置 金额|个数|祝福语|红包名称|红包备注 if (autoKeyword.RedAmount <= 0 || autoKeyword.RedCount <= 0) { logHelper.Error("SendMsgByPush:红包配置失败!autoID:" + autoKeyword.Id); return(await wxAutoComResponse.SendWxText(gzhClient, gzhSever, timeStamp, "获取红包失败,请稍候重试!")); } // 红包已发放个数 var sendCount = repo.SqlQuerySingle <int>($" SELECT COUNT(1) FROM WxAutoKeywordDetail WHERE AutoId = {autoKeyword.Id} "); if (sendCount >= autoKeyword.RedCount) { logHelper.Error("SendMsgByPush:红包已经抢完,autoID:" + autoKeyword.Id); return(await wxAutoComResponse.SendWxText(gzhClient, gzhSever, timeStamp, "客官,您来晚了,红包已被先到的小伙伴抢完鸟,下次记得早点来哦。")); } // 判断用户是否已经发放过红包 var exist = repo.FirstOrDefault <WxAutoKeywordDetail>(x => x.Id == autoKeyword.Id && x.Opend == gzhClient); if (exist != null) { logHelper.Error("SendMsgByPush:重复领取红包,autoID:" + autoKeyword.Id + " OpenID:" + gzhClient); return(await wxAutoComResponse.SendWxText(gzhClient, gzhSever, timeStamp, "你已经领取过此红包,请把机会留给更多的人!")); } // 发放红包 var payRes = RedpackApi.SendPack(gzhClient, autoKeyword.RedAmount, autoKeyword.RedAct, autoKeyword.RedWish, autoKeyword.RedRemark, ""); if (payRes.IsSucc) { //红包发送成功 WxAutoKeywordDetail redHis = await SaveAutoKeywordHis(autoKeyword.Id, gzhClient); logHelper.Debug("SendMsgByPush:发送红包成功:" + redHis.JsonSerialize()); return(await wxAutoComResponse.SendWxText(gzhClient, gzhSever, timeStamp, "红包发放成功,请注意查收~~")); } else { logHelper.Error("SendMsgByPush:红包发送失败,错误码:" + payRes.err_code + " 错误描述" + payRes.err_code_des); return(await wxAutoComResponse.SendWxText(gzhClient, gzhSever, timeStamp, "微信服务器暂忙,请稍候重试。")); } }
/// <summary> /// 联系客服(菜单) /// </summary> /// <param name="recMsg"></param> /// <returns></returns> public async Task <string> ContactKf(PubReceiveMsg recMsg) { try { var timeStamp = ComHelper.ConvertDateTimeInt(DateTime.Now); if (!IsWorkTime()) { var msg = "您好!现在非客服上班时间,请您在每天9-22点联系我们的客服美眉!"; return(await wxAutoComResponse.SendWxText(recMsg.FromUserName, recMsg.ToUserName, timeStamp, msg)); } else { PubKfApi.SendTextMsg(recMsg.FromUserName, "正在为你转接在线客服,请稍后....."); var msg = PubMsgApi.BuildKfTransferMsg(recMsg.FromUserName, recMsg.ToUserName, timeStamp); logHelper.Debug("ContactKf:msg:" + msg.JsonSerialize()); // 发送客服消息提醒 return(await wxAutoComResponse.AutoMsgResponse(msg)); } } catch (Exception ex) { logHelper.Error("ContactKf:联系客服失败:" + ex.Message + " " + ex.StackTrace); } return(wxAutoComResponse.ResponseOK());; }
/// <summary> /// 微信推送菜单点击事件处理 /// </summary> /// <param name="recMsg"></param> /// <returns></returns> public async Task <string> Deal(PubReceiveMsgCData recMsg) { if (!string.IsNullOrEmpty(recMsg.EventKey)) { var keyWord = recMsg.EventKey.Trim().ToLower(); logHelper.Debug("WxEventClick:EventKey:" + keyWord); switch (keyWord) { // 联系客服 case "gotoservices": return(await wxKfTransferHelper.ContactKf(recMsg)); // surprise 或者 其他文本 default: return(await wxAutoResponseHelper.DealWithKeyWord(recMsg.FromUserName, recMsg.ToUserName, keyWord)); } } return(wxAutoComResponse.ResponseOK());; }
private static string VoiceMsgHandleAsync(XmlDocument xmldoc) { string responseContent = "", reply = null; var ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName"); var FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName"); var Content = xmldoc.SelectSingleNode("/xml/Recognition"); if (Content != null) { //设置回复消息 reply = ChatRobotHelper.GetBotReply(HttpContext.Current.Server.UrlEncode(Content.InnerText)); if (reply == "error") { reply = Content.InnerText; } responseContent = string.Format(ReplyMessageType.MessageText, FromUserName.InnerText, ToUserName.InnerText, DateTime.Now.Ticks, String.IsNullOrEmpty(reply) ? "Sorry,I can not follow you." : reply); } Logger.Debug("接受的消息:" + Content.InnerText + "\r\n 发送的消息:" + reply); return(responseContent); }
public async Task <Result <string> > SaveMenus([FromBody] JObject objPara) { try { dynamic obj = objPara as dynamic; List <WxMenusShow> lstMenu = ComHelper.JsonDeserialize <List <WxMenusShow> >(obj.lstMenu.ToString()); logHelper.Debug("SaveMenus:获取到待保存的公众号菜单数据:" + lstMenu.JsonSerialize()); #region 保存菜单到公众号 var wxMenus = new PubMenus(); wxMenus.button = new List <PubMenu>(); foreach (var lv1 in lstMenu) { // 一级菜单 var wxMenuLv1 = new PubMenu(); wxMenuLv1.type = lv1.Type; wxMenuLv1.name = lv1.Name; wxMenuLv1.key = lv1.Key; wxMenuLv1.url = lv1.Url; wxMenuLv1.media_id = lv1.MediaId; wxMenuLv1.appid = lv1.Appid; wxMenuLv1.pagepath = lv1.Pagepath; if (lv1.SubButton != null && lv1.SubButton.Count > 0) { wxMenuLv1.sub_button = new List <PubMenu>(); foreach (var lv2 in lv1.SubButton) { // 二级菜单 var wxMenuLv2 = new PubMenu(); wxMenuLv2.type = lv2.Type; wxMenuLv2.name = lv2.Name; wxMenuLv2.key = lv2.Key; wxMenuLv2.url = lv2.Url; wxMenuLv2.media_id = lv2.MediaId; wxMenuLv2.appid = lv2.Appid; wxMenuLv2.pagepath = lv2.Pagepath; wxMenuLv1.sub_button.Add(wxMenuLv2); } } wxMenus.button.Add(wxMenuLv1); } logHelper.Debug("SaveMenus:获取到待提交公众号的菜单数据:" + wxMenus.JsonSerialize()); var apiRes = PubMenuApi.SaveMenu(wxMenus); logHelper.Debug("SaveMenus:保存公众号菜单结果:" + ComHelper.JsonSerialize(apiRes)); if (!apiRes.IsSuss) { var msg = "保存公众号菜单失败:错误代码:" + apiRes.errcode + " 原因:" + apiRes.errmsg; logHelper.Error("SaveMenus:" + msg); return(new Result <string> { Message = msg }); } #endregion #region 保存菜单到数据库 var dtNow = DateTime.Now; var lstIds = new List <int>(); var order = 1; var curUser = currentUser.UserName; foreach (var lv1 in lstMenu) { lv1.Level = 1; lv1.Order = order; if (!lv1.CreateTime.HasValue) { lv1.Creater = curUser; lv1.CreateTime = dtNow; } lv1.Updater = curUser; lv1.UpdateTime = dtNow; await repo.SaveAsync(lv1); lstIds.Add(lv1.Id); order++; if (lv1.SubButton != null && lv1.SubButton.Count > 0) { lv1.Type = ""; lv1.Key = ""; lv1.Url = ""; lv1.MediaId = ""; lv1.Appid = ""; lv1.Pagepath = ""; foreach (var lv2 in lv1.SubButton) { lv2.ParentId = lv1.Id; lv2.Level = 2; lv2.Order = order; if (!lv2.CreateTime.HasValue) { lv2.Creater = curUser; lv2.CreateTime = dtNow; } lv2.Updater = curUser; lv2.UpdateTime = dtNow; await repo.SaveAsync(lv2); lstIds.Add(lv2.Id); order++; } } } // 禁用掉停用的菜单 if (lstIds.Count > 0) { var strIds = string.Join(",", lstIds); var strSql = string.Format(" UPDATE WxMenus SET IsDel = 1, Updater = '{0}', UpdateTime = '{1}' WHERE Id NOT IN ({2}) ", currentUser.UserName, dtNow, strIds); await repo.ExecuteCommandAsync(strSql); } #endregion return(new Result <string> { IsSucc = true, Message = "保存微信公众号菜单列表成功!" }); } catch (Exception ex) { logHelper.Error("GetMenus:保存微信公众号菜单列表失败:" + ex.Message + " " + ex.StackTrace); } return(new Result <string> { Message = "保存微信公众号菜单列表失败!" }); }
public string Process([FromQuery] string signature, string timestamp, string nonce, string echostr) { logHelper.Debug("Process:" + Request.Host.Value); // 验签 int ret = WXBizMsgCrypt.VerifySignature(PubInterface.Conf.AppToken, timestamp, nonce, "", signature); // 判断是否验签成功 if (ret != 0) { var msg = "Process:微信验证服务器失败:错误代码:" + ret; logHelper.Debug(msg); return(msg); } // 验证签名成功返回结果 return(echostr); }
public static void Debug(string msg) { _logHelper.Debug(msg); }
public void Debug(Exception ex) { _logHelper.Debug(ex); }
public void Debug(string data) { logHelper.Debug(data); }
/// <summary> /// 自动应答(客服消息) /// </summary> /// <param name="item"></param> /// <param name="openId"></param> /// <returns></returns> public async Task <Result <string> > AutoRespond(WxAutoKeywordShow item, string openId) { try { // 自动推送类型 Enum_ApMsgType type = ComHelper.GetEnumValueByStr <Enum_ApMsgType>(item.ContentType); // 发送客服消息预览 PubApiResult apiRes = new PubApiResult(); switch (type) { case Enum_ApMsgType.Text: item.TextContent = item.TextContent.Replace("{nickname}", string.Empty); apiRes = PubKfApi.SendTextMsg(openId, item.TextContent); break; case Enum_ApMsgType.Image: apiRes = PubKfApi.SendImageMsg(openId, item.MediaId); break; case Enum_ApMsgType.Voice: apiRes = PubKfApi.SendVoiceMsg(openId, item.MediaId); break; case Enum_ApMsgType.News: apiRes = PubKfApi.SendMpNewsMsg(openId, item.MediaId); break; case Enum_ApMsgType.Video: apiRes = PubKfApi.SendVideoMsg(openId, item.MediaId, item.VideoThumbMediaId, item.VideoTitle, item.VideoDescription); break; case Enum_ApMsgType.BackNews: var lstArts = await wxAutoConvertHelper.GetAutoKeywordBackNews(item); apiRes = PubKfApi.SendNewsMsg(openId, lstArts); break; case Enum_ApMsgType.RedBag: return(await wxAutoConvertHelper.SendAutoKeywordRedPack(item, openId)); default: break; } logHelper.Debug("PrevKeyword:预览返回结果:" + ComHelper.JsonSerialize(apiRes)); if (!apiRes.IsSuss) { var msg = "预览出错:" + apiRes.errcode + " " + apiRes.errmsg; logHelper.Error("PrevKeyword:" + msg); return(new Result <string> { Message = msg }); } return(new Result <string> { IsSucc = true, Message = "发送预览消息成功!" }); } catch (Exception ex) { logHelper.Error("PrevKeyword:发送预览消息失败:" + ex.Message + " " + ex.StackTrace); } return(new Result <string> { Message = "发送预览消息失败!" }); }
/// <summary> /// 自动应答响应 /// </summary> /// <param name="msg"></param> /// <returns></returns> public async Task <string> AutoMsgResponse(string msg) { logHelper.Debug("AutoMsgResponse:Msg:" + msg); return(await Task.FromResult(msg)); }