public MCServiceHandler(int mpId, MpAccountDto account, ICacheManager cacheManager, ILogger logger, IAccessTokenContainer accessTokenContainer , IMatialFileService matialFileService , IWebUrlService webUrlService , IYiliBabyClubInterfaceService yiliBabyClubInterfaceService) { _cacheManager = cacheManager; _logger = logger; mpid = mpId; _account = account; _accessTokenContainer = accessTokenContainer; _matialFileService = matialFileService; _webUrlService = webUrlService; _yiliBabyClubInterfaceService = yiliBabyClubInterfaceService; MamaBanToYun2OneMediaID = _matialFileService.MaMaBanToYun2One; JNHToLongLineMediaID = _matialFileService.JNHToLongLine; wxOnlineUrl = _webUrlService.GetSiteRootAddress() + _matialFileService.WxOnlineUrl; auth2Url = _webUrlService.GetSiteRootAddress() + _matialFileService.Auth2Url; defaultUserName = _yiliBabyClubInterfaceService.ApiUserName; defaultUserPwd = _yiliBabyClubInterfaceService.ApiPassword; deviceCode = _yiliBabyClubInterfaceService.ApiDeviceCode; yiliwechat = _yiliBabyClubInterfaceService.Yiliwechat; }
public async Task <IActionResult> OnPostAjaxAsync([FromBody] MpAccountDto mpAccountDto) { MpAccount mpAccount = null; if (mpAccountDto.Id > 0) { mpAccount = await _mpAccountService.GetObjectAsync(z => z.Id == mpAccountDto.Id); if (mpAccount == null) { return(RenderError("公众号信息不存在!")); } mpAccountDto.AddTime = mpAccount.AddTime; _mpAccountService.Mapper.Map(mpAccountDto, mpAccount); mpAccount.LastUpdateTime = DateTime.Now; } else { mpAccount = new MpAccount(mpAccountDto); } await _mpAccountService.SaveObjectAsync(mpAccount); //重新进行公众号注册 await AccessTokenContainer.RegisterAsync(mpAccount.AppId, mpAccount.AppSecret, $"{mpAccount.Name}-{mpAccount.Id}"); //立即获取 AccessToken await AccessTokenContainer.GetAccessTokenAsync(mpAccount.AppId, true); //return RedirectToPage("./Edit", new { id = mpAccount.Id, uid = Uid }); return(Ok(new { id = mpAccount.Id, uid = Uid })); }
/// <summary> /// 发送全部用户 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="totalCount"></param> public async Task SendAllAsync(MpAccountDto account, MpMessageDto args, long totalCount) { IDBHelper yilidb = new MssqlHelper(JobConfig.ConnectionStrings["YiliscrmDb"]); if (JobConfig.AppSettings["Debugger"] != "true")//正式发送 { #region 发送消息 string updateSql = "Update MpMessages SET SendState='{1}',WxMsgID='{2}' WHERE ID='{0}'"; var result = await SendAllByGroup(account, args, yilidb); if (result != null && result.errcode == ReturnCode.请求成功) { await yilidb.ExcuteNonQueryAsync(string.Format(updateSql, args.Id, (int)MpMessageTaskState.Doing, result.msg_id), null, false); } else { await yilidb.ExcuteNonQueryAsync(string.Format(updateSql, args.Id, (int)MpMessageTaskState.Fail, ""), null, false); } #endregion } else//测试,不发送 { yilidb.ExcuteNonQuery($"UPDATE MpMessages SET SuccessCount={totalCount},FailCount=0,FinishDate=GetDate(),SendCount={totalCount},SendState='(int)MpMessageTaskState.Success' Where ID={args.Id}", null, false); } }
/// <summary> /// 按openid逐组群发 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="taskId"></param> /// <param name="totalCount"></param> public async Task SendMessageAsync(MpAccountDto account, MpMessageDto args, long totalCount) { IDBHelper db = new MssqlHelper(JobConfig.ConnectionStrings["YiliscrmGroupMessage"]); IDBHelper yilidb = new MssqlHelper(JobConfig.ConnectionStrings["YiliscrmDb"]); var msgResult = await db.FindToListAsync <TaskGroupMessageDto>($"SELECT * FROM TaskGroupMessages WHERE ISDELETED=0 AND MpID='{args.MpID}' AND TaskState='{(int)MpMessageTaskState.Wait}' AND MessageID='" + args.Id + "'", null, false); if (JobConfig.AppSettings["Debugger"] != "true")//正式发送 { string updateSql = "Update TaskGroupMessages SET TaskState='{1}',WxMsgID='{2}' WHERE ID='{0}'"; foreach (var drItem in msgResult) { var result = await SendByOpenIds(account, args, drItem.OpenIDs.Split(','), yilidb); if (result != null && result.errcode == ReturnCode.请求成功) { await db.ExcuteNonQueryAsync(string.Format(updateSql, drItem.Id, (int)MpMessageTaskState.Doing, result.msg_id), null, false); } else { await db.ExcuteNonQueryAsync(string.Format(updateSql, drItem.Id, (int)MpMessageTaskState.Fail, ""), null, false); } } } else { foreach (var drItem in msgResult) { await db.ExcuteNonQueryAsync($"Update TaskGroupMessages SET TaskState='{(int)MpMessageTaskState.Success}',SuccessCount='{drItem.SendCount}',FailCount=0 WHERE ID='{drItem.Id}'", null, false); } yilidb.ExcuteNonQuery($"UPDATE MpMessages SET SuccessCount=totalCount,FailCount=0,FinishDate=GetDate(),SendCount={totalCount},SendState='{(int)MpMessageTaskState.Success}' Where ID={args.Id}", null, false); } }
/// <summary> /// handler=Ajax /// </summary> /// <param name="mpId"></param> /// <param name="pageIndex"></param> /// <returns></returns> public async Task <IActionResult> OnGetAjaxAsync(int mpId = 0, int pageIndex = 1, int pageSize = 10) { MpAccountDto mpAccountDto = null;// new MpAccountDto(); if (mpId > 0) { var mpAccount = await _mpAccountService.GetObjectAsync(z => z.Id == mpId); if (mpAccount == null) { return(RenderError("公众号配置不存在:" + mpId)); } mpAccountDto = _mpAccountService.Mapper.Map <MpAccountDto>(mpAccount); } var seh = new Ncf.Utility.SenparcExpressionHelper <Models.WeixinUser>(); seh.ValueCompare.AndAlso(mpAccountDto != null, z => z.MpAccountId == mpAccountDto.Id); var where = seh.BuildWhereExpression(); var result = await _weixinUserService.GetObjectListAsync(pageIndex, pageSize, where, z => z.Id, Ncf.Core.Enums.OrderingType.Descending, z => z.Include(p => p.UserTags_WeixinUsers).ThenInclude(p => p.UserTag)); //ViewData["Test"] = result.FirstOrDefault(); var weixinUserDtos = new PagedList <WeixinUserDto>(result.Select(z => _weixinUserService.Mapper.Map <WeixinUserDto>(z)).ToList(), result.PageIndex, result.PageCount, result.TotalCount); return(Ok(new { mpAccountDto, weixinUserDtos = new { weixinUserDtos.TotalCount, list = weixinUserDtos.Select(_ => new { _.AddTime, _.Remark, _.AdminRemark, _.City, _.Country, _.Groupid, _.HeadImgUrl, _.Id, _.Language, _.LastUpdateTime, _.MpAccountId, _.NickName, _.OpenId, _.Province, _.Qr_Scene, _.Qr_Scene_Str, _.Sex, _.Subscribe, _.Subscribe_Scene, Subscribe_Time = new DateTime(1970, 1, 1).AddSeconds(_.Subscribe_Time).ToString(), //_.Tagid_List, _.UnionId, UserTags_WeixinUsers = _.UserTags_WeixinUsers.Select(__ => new { __.UserTag, __.UserTagId, __.WeixinUserId }), }).AsEnumerable() } })); }
public async Task <IActionResult> OnGetAjaxAsync(int id = 0) { var mpAccountDto = new MpAccountDto(); if (id > 0) { var mpAccount = await _mpAccountService.GetObjectAsync(z => z.Id == id); if (mpAccount == null) { return(RenderError("公众号信息不存在!")); } mpAccountDto = _mpAccountService.Mapper.Map <MpAccountDto>(mpAccount); } return(Ok(mpAccountDto)); }
/// <summary> /// 按openid逐组群发 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="taskId"></param> /// <param name="totalCount"></param> private async Task SendMessageAsync(MpAccountDto account, MpMessageDto args, long totalCount) { var msgResult = await _taskGroupMessageAppService.GetList(new Wechat.TaskGroupMessages.Dto.GetTaskGroupMessagesInput { MpID = args.MpID, TaskState = (int)MpMessageTaskState.Wait, MessageId = args.Id }); if (JobConfig.AppSettings["Debugger"] != "true")//正式发送 { LogWriter.Info("群发消息开始 准备开始"); foreach (var drItem in msgResult) { var result = await SendByOpenIds(account, args, drItem.OpenIDs.Split(',')); LogWriter.Info($"群发消息开始 开始反写状态 {JsonConvert.SerializeObject(args)} {JsonConvert.SerializeObject(drItem)}"); if (result != null && result.errcode == ReturnCode.请求成功) { LogWriter.Info($"群发消息 请求返回成功 {JsonConvert.SerializeObject(result)}"); drItem.TaskState = (int)MpMessageTaskState.Doing; drItem.WxMsgID = result.msg_id; await _taskGroupMessageAppService.Update(drItem); } else { LogWriter.Info($"群发消息 请求返回失败 {JsonConvert.SerializeObject(result)}"); drItem.TaskState = (int)MpMessageTaskState.Fail; await _taskGroupMessageAppService.Update(drItem); } } } else { foreach (var drItem in msgResult) { drItem.TaskState = (int)MpMessageTaskState.Success; drItem.SuccessCount = drItem.SendCount; drItem.FailCount = 0; await _taskGroupMessageAppService.Update(drItem); } args.SuccessCount = totalCount; args.FailCount = 0; args.FinishDate = DateTime.Now; args.SendCount = totalCount; args.SendState = (int)MpMessageTaskState.Success; await _mpMessageAppService.UpdateSendState(new List <MpMessageDto>() { args }); } }
public async Task <IActionResult> OnGetAsync(int id = 0) { IsEdit = id > 0; if (IsEdit) { var mpAccount = await _mpAccountService.GetObjectAsync(z => z.Id == id); if (mpAccount == null) { return(RenderError("公众号信息不存在!")); } MpAccountDto = _mpAccountService.Mapper.Map <MpAccountDto>(mpAccount); } else { MpAccountDto = new MpAccountDto(); } return(Page()); }
/// <summary> /// 发送全部用户 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="totalCount"></param> private async Task SendAllAsync(MpAccountDto account, MpMessageDto args, long totalCount) { Logger.Info($"hangfileDebug {System.Configuration.ConfigurationManager.AppSettings["hangfileDebug"]}"); if (JobConfig.AppSettings["Debugger"] != "true")//正式发送 { #region 发送消息 LogWriter.Info("群发消息开始 准备开始"); var result = await SendAllByGroup(account, args); LogWriter.Info("群发消息开始 开始反写状态"); if (result != null && result.errcode == ReturnCode.请求成功) { LogWriter.Info($"群发消息 请求返回成功 {JsonConvert.SerializeObject(result)}"); args.SendState = (int)MpMessageTaskState.Doing; args.WxMsgID = result.msg_id; await _mpMessageAppService.UpdateSendState(new List <MpMessageDto>() { args }); } else { LogWriter.Info($"群发消息 请求返回失败 {JsonConvert.SerializeObject(result)} {JsonConvert.SerializeObject(args)}"); args.SendState = (int)MpMessageTaskState.Fail; await _mpMessageAppService.UpdateSendState(new List <MpMessageDto>() { args }); LogWriter.Info($"群发消息 请求返回失败 更新状态结束 {JsonConvert.SerializeObject(args)}"); } #endregion } else//测试,不发送 { args.SuccessCount = totalCount; args.FailCount = 0; args.FinishDate = DateTime.Now; args.SendCount = totalCount; args.SendState = (int)MpMessageTaskState.Success;//发送成功 await _mpMessageAppService.TaskUpdate(args); } }
public CustomMessageHandler(Stream inputStream, PostModel postModel, ILogger logger , ICacheManager cacheManager, IMpAccountAppService mpAccountAppService, int _mpId , IMpEventAppService mpEventAppService, IMpMediaVideoAppService mpMediaVideoAppService , IMpSelfArticleAppService mpSelfArticleAppService , IMpSelfArticleGroupAppService mpSelfArticleGroupAppService , IMpSelfArticleGroupItemAppService mpSelfArticleGroupItemAppService , IMpEventRequestMsgLogAppService mpEventRequestMsgLogAppService , IMpKeyWordReplyAppService mpKeyWordReplyAppService , IMpEventClickViewLogAppService mpEventClickViewLogAppService , IMpMenuAppService mpMenuAppService , IMpMessageAppService mpMessageAppService , IAccessTokenContainer accessTokenContainer , IMpFanAppService mpFanAppService , IMpEventScanLogAppService mpEventScanLogAppService , ICustomerServiceResponseTextAppService customerServiceResponseTextAppService , IMpUserMemberAppService mpUserMemberAppService , MpAccountDto account , IMpChannelAppService mpChannelAppService , IIocResolver iocResolver , IMatialFileService matialFileService , IWebUrlService webUrlService , IYiliBabyClubInterfaceService yiliBabyClubInterfaceService , int maxRecordCount = 0) : base(inputStream, postModel, maxRecordCount) { mpId = _mpId; _cacheManager = cacheManager; _logger = logger; _accessTokenContainer = accessTokenContainer; _mpAccountAppService = mpAccountAppService; _mpEventAppService = mpEventAppService; _mpEventClickViewLogAppService = mpEventClickViewLogAppService; _mpEventRequestMsgLogAppService = mpEventRequestMsgLogAppService; _mpEventScanLogAppService = mpEventScanLogAppService; _mpFanAppService = mpFanAppService; _mpKeyWordReplyAppService = mpKeyWordReplyAppService; _mpMediaVideoAppService = mpMediaVideoAppService; _mpMenuAppService = mpMenuAppService; _mpMessageAppService = mpMessageAppService; _mpSelfArticleGroupItemAppService = mpSelfArticleGroupItemAppService; _mpSelfArticleGroupAppService = mpSelfArticleGroupAppService; _mpSelfArticleAppService = mpSelfArticleAppService; WeixinContext.ExpireMinutes = 3; _customerServiceResponseTextAppService = customerServiceResponseTextAppService; _mpUserMemberAppService = mpUserMemberAppService; _iocResolver = iocResolver; _account = account; _matialFileService = matialFileService; _webUrlService = webUrlService; _mpChannelAppService = mpChannelAppService; _yiliBabyClubInterfaceService = yiliBabyClubInterfaceService; domain = _webUrlService.GetSiteRootAddress(); if (!string.IsNullOrEmpty(postModel.AppId)) { appId = postModel.AppId;//通过第三方开放平台发送过来的请求 } //在指定条件下,不使用消息去重 base.OmitRepeatedMessageFunc = requestMessage => { var textRequestMessage = requestMessage as RequestMessageText; if (textRequestMessage != null && textRequestMessage.Content == "容错") { return(false); } return(true); }; }
public CreateOrEditMpAccountViewModel(MpAccountDto output) { output.MapTo(this); }
/// <summary> /// 发送全部用户 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="yilidb"></param> /// <returns></returns> private async Task <SendResult> SendAllByGroup(MpAccountDto account, MpMessageDto args, IDBHelper yilidb) { SendResult result = null; if (args.MessageType == MpMessageType.text.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.Content, GroupMessageType.text, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.Content, GroupMessageType.text, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.video.ToString()) { var videoId = int.Parse(args.VideoID.ToString()); var video = yilidb.FindOne <MpMediaVideo>("SELECT TOP 1 * FROM MpMediaVideos WHERE ID=" + videoId, null, false); if (video == null) { throw new Exception(string.Format("视频{0}不存在", args.VideoName)); } try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.VideoMediaID, GroupMessageType.video, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.VideoMediaID, GroupMessageType.video, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.voice.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.VoiceMediaID, GroupMessageType.voice, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.VoiceMediaID, GroupMessageType.voice, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.image.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.ImageMediaID, GroupMessageType.image, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.ImageMediaID, GroupMessageType.image, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.mpnews.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.ArticleMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.ArticleMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.mpmultinews.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.ArticleGroupMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.ArticleGroupMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } return(result); }
/// <summary> /// 按openid群发 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="openIds"></param> /// <returns></returns> private async Task <SendResult> SendByOpenIds(MpAccountDto account, MpMessageDto args, string[] openIds, IDBHelper yilidb) { SendResult result = null; if (args.MessageType == MpMessageType.text.ToString()) { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, GroupMessageType.text, args.Content, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, GroupMessageType.text, args.Content, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { } } } else if (args.MessageType == MpMessageType.video.ToString()) { var videoId = int.Parse(args.VideoID.ToString()); var video = yilidb.FindOne <MpMediaVideo>("SELECT TOP 1 * FROM MpMediaVideos WHERE ID=" + videoId, null, false); if (video == null) { throw new Exception(string.Format("视频{0}不存在", args.VideoName)); } try { result = await GroupMessageApi.SendVideoGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, video.Title, video.Description, args.VideoMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { try { result = await GroupMessageApi.SendVideoGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, video.Title, video.Description, args.VideoMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { } } } else if (args.MessageType == MpMessageType.voice.ToString()) { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, GroupMessageType.voice, args.VoiceMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, GroupMessageType.voice, args.VoiceMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { } } } else if (args.MessageType == MpMessageType.image.ToString()) { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, GroupMessageType.image, args.ImageMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, GroupMessageType.image, args.ImageMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { } } } else if (args.MessageType == MpMessageType.mpnews.ToString()) { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, GroupMessageType.mpnews, args.ArticleMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, GroupMessageType.mpnews, args.ArticleMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { } } } else if (args.MessageType == MpMessageType.mpmultinews.ToString()) { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, GroupMessageType.mpnews, args.ArticleGroupMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { try { result = await GroupMessageApi.SendGroupMessageByOpenIdAsync((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, GroupMessageType.mpnews, args.ArticleGroupMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds.ToArray()); } catch { } } } return(result); }
/// <summary> /// 发送全部用户 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <returns></returns> private async Task <SendResult> SendAllByGroup(MpAccountDto account, MpMessageDto args) { SendResult result = null; if (args.MessageType == MpMessageType.text.ToString()) { try { LogWriter.Info("群发消息开始 全部开始"); result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), "", args.Content, GroupMessageType.text, true, clientmsgid: $"MpMessage{args.Id}"); LogWriter.Info("群发消息开始 全部结束"); } catch (Exception ex) { LogWriter.Error("群发消息开始 第一次报错", ex); try { LogWriter.Info("群发消息开始 全部开始2"); result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), "", args.Content, GroupMessageType.text, true, clientmsgid: $"MpMessage{args.Id}"); LogWriter.Info("群发消息开始 全部结束2"); } catch (Exception ex2) { LogWriter.Error("群发消息开始 第二次报错", ex2); } } } else if (args.MessageType == MpMessageType.video.ToString()) { var videoId = int.Parse(args.VideoID.ToString()); var video = await _mpMediaVideoAppService.Get(new Abp.Application.Services.Dto.EntityDto <int> { Id = videoId }); if (video == null) { throw new Exception(string.Format("视频{0}不存在", args.VideoName)); } try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), "", args.VideoMediaID, GroupMessageType.video, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), "", args.VideoMediaID, GroupMessageType.video, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.voice.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), "", args.VoiceMediaID, GroupMessageType.voice, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), "", args.VoiceMediaID, GroupMessageType.voice, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.image.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), "", args.ImageMediaID, GroupMessageType.image, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), "", args.ImageMediaID, GroupMessageType.image, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.mpnews.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), "", args.ArticleMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), "", args.ArticleMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } else if (args.MessageType == MpMessageType.mpmultinews.ToString()) { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), "", args.ArticleGroupMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { try { result = GroupMessageApi.SendGroupMessageByGroupId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), "", args.ArticleGroupMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}"); } catch { } } } return(result); }
/// <summary> /// 按openid群发 /// </summary> /// <param name="account"></param> /// <param name="args"></param> /// <param name="openIds"></param> /// <returns></returns> private async Task <SendResult> SendByOpenIds(MpAccountDto account, MpMessageDto args, string[] openIds) { SendResult result = null; if (args.MessageType == MpMessageType.text.ToString()) { try { LogWriter.Info("群发消息开始 openid开始"); result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), GroupMessageType.text, args.Content, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); LogWriter.Info("群发消息开始 openid结束"); } catch (Exception ex) { LogWriter.Error("群发消息开始 第一次报错", ex); try { LogWriter.Info("群发消息开始 openid开始2"); result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), GroupMessageType.text, args.Content, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); LogWriter.Info("群发消息开始 openid结束2"); } catch (Exception ex2) { LogWriter.Error("群发消息开始 第二次报错", ex2); } } } else if (args.MessageType == MpMessageType.video.ToString()) { var videoId = int.Parse(args.VideoID.ToString()); var video = await _mpMediaVideoAppService.Get(new Abp.Application.Services.Dto.EntityDto <int> { Id = videoId }); if (video == null) { throw new Exception(string.Format("视频{0}不存在", args.VideoName)); } try { result = GroupMessageApi.SendVideoGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), video.Title, video.Description, args.VideoMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { try { result = GroupMessageApi.SendVideoGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), video.Title, video.Description, args.VideoMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { } } } else if (args.MessageType == MpMessageType.voice.ToString()) { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), GroupMessageType.voice, args.VoiceMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), GroupMessageType.voice, args.VoiceMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { } } } else if (args.MessageType == MpMessageType.image.ToString()) { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), GroupMessageType.image, args.ImageMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), GroupMessageType.image, args.ImageMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { } } } else if (args.MessageType == MpMessageType.mpnews.ToString()) { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), GroupMessageType.mpnews, args.ArticleMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), GroupMessageType.mpnews, args.ArticleMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { } } } else if (args.MessageType == MpMessageType.mpmultinews.ToString()) { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), GroupMessageType.mpnews, args.ArticleGroupMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { try { result = GroupMessageApi.SendGroupMessageByOpenId(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), GroupMessageType.mpnews, args.ArticleGroupMediaID, $"MpMessage{args.Id}", Senparc.Weixin.Config.TIME_OUT, openIds); } catch { } } } await _mpMessageAppService.UpdateSendState(new List <MpMessageDto> { args }); return(result); }
private async Task ReFreshFans(MpAccountDto model) { var mpId = model.Id; #region 初始化 var sb = new StringBuilder(); int stoptick = 0, stopcount = 100; var fanssavestr = @" if not exists(select * from MpFans where MpID='{0}' and OpenID='{1}') insert into MpFans ([MpID],[OpenID],[NickName],[Sex],[Language],[City],[Province],[Country],[HeadImgUrl],[SubscribeTime],[UnionID],[WxGroupID],[IsFans],[UpdateTime],CreationTime,IsDeleted) values ({0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}',getdate(),getdate(),0) else update MpFans SET [MpID]='{0}',[OpenID]='{1}',[NickName]='{2}',[Sex]='{3}',[Language]='{4}',[City]='{5}',[Province]='{6}',[Country]='{7}',[HeadImgUrl]='{8}',[SubscribeTime]='{9}',[UnionID]='{10}',[WxGroupID]='{12}',[IsFans]='{13}',[UpdateTime]=getdate(),IsDeleted=0 WHERE MpID='{0}' and OpenID='{1}' "; #endregion #region 更新用户 #region 更新前10000个用户 OpenIdResultJson fansopenids = null; try { fansopenids = UserApi.Get(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret), ""); } catch (Exception ex) { LogWriter.Error(string.Format("获取MpID为{0}的openid报错,错误信息:{1}", mpId, ex)); fansopenids = UserApi.Get(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret, true), ""); } DateTime now = DateTime.Now; if (fansopenids.count > 0) { foreach (var id in fansopenids.data.openid) { UserInfoJson wxinfo = null; try { wxinfo = UserApi.Info(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret), id); } catch (Exception ex) { LogWriter.Error(string.Format("获取MpID为{0},openid为{1}的用户信息报错,错误信息:{2}", mpId.ToString(), id, ex)); wxinfo = UserApi.Info(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret, true), id); } sb.AppendFormat(fanssavestr, mpId, id, DbTool.ToSqlParamString(wxinfo.nickname), wxinfo.sex, DbTool.ToSqlParamString(wxinfo.language), DbTool.ToSqlParamString(wxinfo.city), DbTool.ToSqlParamString(wxinfo.province), DbTool.ToSqlParamString(wxinfo.country), DbTool.ToSqlParamString(wxinfo.headimgurl), DateTimeHelper.GetDateTimeFromXml(wxinfo.subscribe_time), DbTool.ToSqlParamString(wxinfo.unionid), DbTool.ToSqlParamString(wxinfo.remark), wxinfo.groupid, wxinfo.subscribe); stoptick++; if (stoptick % stopcount == 0 || stoptick == fansopenids.count) { if (sb.Length > 0) { await StaticObjects.db.ExcuteNonQueryAsync(sb.ToString(), null, false); } sb.Clear(); } } } #endregion #region while循环更新后续所有用户 while (!string.IsNullOrEmpty(fansopenids.next_openid)) { try { fansopenids = UserApi.Get(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret), fansopenids.next_openid); } catch (Exception ex) { LogWriter.Error(string.Format("获取MpID为{0}的openid报错,nextopenid为{1},错误信息:{2}", mpId, fansopenids.next_openid, ex)); fansopenids = UserApi.Get(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret, true), fansopenids.next_openid); } if (fansopenids.count > 0) { foreach (var id in fansopenids.data.openid) { UserInfoJson wxinfo = null; try { wxinfo = UserApi.Info(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret), id); } catch (Exception ex) { LogWriter.Error(string.Format("获取MpID为{0},openid为{1}的用户信息报错,错误信息:{2}", mpId, id, ex)); wxinfo = UserApi.Info(await _accessTokenContainer.TryGetAccessTokenAsync(model.AppId, model.AppSecret, true), id); } sb.AppendFormat(fanssavestr, mpId, id, DbTool.ToSqlParamString(wxinfo.nickname), wxinfo.sex, DbTool.ToSqlParamString(wxinfo.language), DbTool.ToSqlParamString(wxinfo.city), DbTool.ToSqlParamString(wxinfo.province), DbTool.ToSqlParamString(wxinfo.country), DbTool.ToSqlParamString(wxinfo.headimgurl), DateTimeHelper.GetDateTimeFromXml(wxinfo.subscribe_time), DbTool.ToSqlParamString(wxinfo.unionid), DbTool.ToSqlParamString(wxinfo.remark), wxinfo.groupid, wxinfo.subscribe); stoptick++; if (stoptick % stopcount == 0 || stoptick == fansopenids.count) { if (sb.Length > 0) { await StaticObjects.db.ExcuteNonQueryAsync(sb.ToString(), null, false); } sb.Clear(); } } } } #endregion #warning 该方法不够严谨 //没更新到的用户设为取消关注 sb.AppendFormat("update MpFans set IsFans='0' where MpID='{0}' and UpdateTime<'{1}'", mpId, now.AddDays(-1)); #endregion LogWriter.Info(sb.ToString()); if (sb.Length > 0) { await StaticObjects.db.ExcuteNonQueryAsync(sb.ToString(), null, false); } LogWriter.Info(string.Format("更新数量{0},更新完毕", stoptick)); }