public override List <string> Push(U_AccessToken accessTokenModel, List <U_Content> contentModels) { //获取AccessToken List <string> rtnList = new List <string>(); bool result = SetCorpAccount(accessTokenModel); if (result) { string postUrl = string.Format(_sendUrl, _accessToken); //获取推送内容Json string json = GetPushJson(null, contentModels); //推送 string pushResult = PostWebRequest(postUrl, json, Encoding.UTF8); rtnList.Add(pushResult); foreach (var contentModel in contentModels) { UpdatePushStatus(contentModel); } } else { rtnList.Add("推送失败!"); } return(rtnList); }
/// <summary> /// 删除微信通讯录人员 /// </summary> /// <returns></returns> public bool DeleteWeChatData(U_AccessToken accessTokenModel, List <V_UserNotexistsmiddata> personList) { bool result = false; string isSuccessDelete = string.Empty; bool isGetAccessToken = SetCorpAccount(accessTokenModel); if (isGetAccessToken) { foreach (var item in personList) { isSuccessDelete = DeleteWeChatPerson(item.UserID); U_WeChatResult resultModel = JsonHelper.JsonToModel <U_WeChatResult>(isSuccessDelete); if (resultModel.errcode == 0) { result = true; } else { LogManager.WriteLog(LogFile.Error, "删除微信通讯录人员Logic:" + resultModel.errcode + resultModel.errmsg); result = false; return(result); } } } return(result); }
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { //获取AccessToken bool result = SetCorpAccount(accessTokenModel); //如果有素材需要上传,则上传素材,否则返回null U_UploadResult uploadResult = UpLoadSource(accessTokenModel, contentModel); if (result) { string postUrl = string.Format(_sendUrl, _accessToken); //获取推送内容Json string json = GetPushJson(uploadResult, contentModel); //推送 string pushResult = PostWebRequest(postUrl, json, Encoding.UTF8); U_WeChatResult resultModel = JsonHelper.JsonToModel <U_WeChatResult>(pushResult); if (resultModel.errcode == 0) { UpdatePushStatus(contentModel); UpdateIsReadStatus(contentModel, resultModel.invaliduser); } return(pushResult); } else { return("推送失败!"); } }
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { //获取AccessToken bool result = SetCorpAccount(accessTokenModel); //如果有素材需要上传,则上传素材,否则返回null U_UploadResult uploadResult = UpLoadSource(accessTokenModel, contentModel); //获取微信用户详细信息 List <U_WeChatUser> weChatUserList = SearchWeChatUserList(); //比较微信用户列表与要推送人员列表 List <U_WeChatUser> pushPersonListOk = weChatUserList.Join(contentModel.PushObject, c => c.mobile, b => b.PhoneNumber, (c, b) => c).ToList(); if (result) { string postUrl = string.Format(_sendUrl, _accessToken); //获取推送内容Json string json = GetPushJson(uploadResult, contentModel); //推送 string pushResult = PostWebRequest(postUrl, json, Encoding.UTF8); U_WeChatResult resultModel = JsonHelper.JsonToModel <U_WeChatResult>(pushResult); if (resultModel.errcode == 0) { UpdatePushStatus(contentModel); } return(pushResult); } else { return("推送失败!"); } }
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { //获取AccessToken bool result = SetCorpAccount(accessTokenModel); //如果有素材需要上传,则上传素材,否则返回null U_UploadResult uploadResult = UpLoadSource(accessTokenModel, contentModel); if (!result) { return("推送失败!"); } string pushResult; try { string postUrl = string.Format(_sendUrl, _accessToken); //获取推送内容Json string json = GetPushJson(uploadResult, contentModel); //推送 pushResult = PostWebRequest(postUrl, json, Encoding.UTF8); U_WeChatResult resultModel = JsonHelper.JsonToModel <U_WeChatResult>(pushResult); if (resultModel.errcode != 0) { LogManager.WriteLog(LogFile.Error, "协议推送:" + resultModel.errcode + resultModel.errmsg); } } catch (Exception ex) { LogManager.WriteLog(LogFile.Error, ex.ToString()); pushResult = "推送失败!"; } UpdatePushStatus(contentModel); UpdateIsReadStatus(contentModel); return(pushResult); }
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { //获取AccessToken bool result = SetCorpAccount(accessTokenModel); //如果有素材需要上传,则上传素材,否则返回null U_UploadResult uploadResult = new U_UploadResult(); //比较微信用户列表与要推送人员列表 //List<U_WeChatUser> pushPersonListOk = weChatUserList.Join(contentModel.PushObject, c => c.mobile, b => b.PhoneNumber, (c, b) => c).ToList(); if (result) { string postUrl = string.Format(_sendUrl, _accessToken); //获取推送内容Json string json = GetPushJson(uploadResult, contentModel); //推送 string pushResult = PostWebRequest(postUrl, json, Encoding.UTF8); U_WeChatResult resultModel = JsonHelper.JsonToModel <U_WeChatResult>(pushResult); UpdatePushStatus(contentModel); if (resultModel.errcode == 0) { UpdateIsReadStatus(contentModel, resultModel.invaliduser); } else { LogManager.WriteLog(LogFile.Error, "文本推送" + resultModel.errcode + resultModel.errmsg); } return(pushResult); } else { return("推送失败!"); } }
/// <summary> /// 获取公司AccessToken /// </summary> /// <returns></returns> public static string GetAccessoken(U_AccessToken accessToken) { //获取AccessTokenUrl string tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}"; string respText = ""; //获取josn数据 string url = string.Format(tokenUrl, accessToken.UserKey, accessToken.UserPassword); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream resStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(resStream, Encoding.Default); respText = reader.ReadToEnd(); resStream.Close(); reader.Close(); } try { JavaScriptSerializer Jss = new JavaScriptSerializer(); Dictionary <string, object> respDic = (Dictionary <string, object>)Jss.DeserializeObject(respText); //通过键access_token获取值 return(respDic["access_token"].ToString()); } catch (Exception ex) { LogManager.WriteLog(LogFile.Error, ex.Message); return(""); } }
/// <summary> /// 上传素材 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> protected override U_UploadResult UpLoadSource(U_AccessToken accessTokenModel, U_Content contentModel) { string url = string.Format(_uploadUrl, _accessToken, "image"); string resultaa = UpLoadMediaFile.HttpUploadFile(url, contentModel.Message); U_UploadResult uploadResult = new U_UploadResult(); uploadResult = Common.JsonHelper.JsonToModel <U_UploadResult>(resultaa); return(uploadResult); }
public override List <string> Push(U_AccessToken accessTokenModel, List <U_Content> contentModels) { List <string> rtnList = new List <string>(); foreach (var contentModel in contentModels) { string rtn = Push(accessTokenModel, contentModel); rtnList.Add(rtn); } return(rtnList); }
/// <summary> /// 同步人员数据 /// </summary> public static void UpdatePersonData() { while (true) { bool result = false; int time = 0; if (DateTime.Now.Hour == 3)//时间为三点的时候time初始化 { time = 0; } if (DateTime.Now.Hour == 2 && time == 0)//时间为凌晨两点并且time为0的时候执行同步操作 { // LogManager.WriteLog(LogFile.Trace, DateTime.Now.ToString("yyyy-MM-dd") + "开始启动定时同步离职人员服务"); try { U_AccessToken accessTokenModel = new U_AccessToken(); accessTokenModel.UserKey = ConfigSugar.GetAppString("WeChatCorpID"); accessTokenModel.UserPassword = ConfigSugar.GetAppString("WeChatSecret"); UpdatePersonLogic _updatePersonLogic = new UpdatePersonLogic(); List <V_UserNotexistsmiddata> personList = new List <V_UserNotexistsmiddata>(); personList = _updatePersonLogic.GetPeosonList(); //获取离职人员列表(存在于Person表而不存在与middata表的人员列表) _updatePersonLogic.UpdateStatus2Focus(personList); //首先将人员状态改为已关注 if (personList.Count >= 10) { result = _updatePersonLogic.UpdatePersonStatus(personList, 3); //状态更改为未匹配 } else if (personList.Count > 0) { result = _updatePersonLogic.DisableWeChatData(accessTokenModel, personList); //同时将微信禁用 if (result) { result = _updatePersonLogic.UpdatePersonStatus(personList, 4); //状态更改为已离职 } } // result = _updatePersonLogic.DeletePersonData(personList); //if (result) //{ // //删除微信通讯录中人员 // result = _updatePersonLogic.DeleteWeChatData(accessTokenModel, personList); //} // LogManager.WriteLog(LogFile.Trace, DateTime.Now.ToString("yyyy-MM-dd") + "定时同步离职人员服务启动完成"); } catch (Exception exp) { LogManager.WriteLog(LogFile.Error, "同步离职人员数据:" + result + "/n" + exp.ToString()); } time++; } } }
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { SetCorpAccount(accessTokenModel); U_UploadResult uploadResult = UpLoadSource(accessTokenModel, contentModel); string postUrl = string.Format(_sendUrl, _accessToken); string json = GetPushJson(uploadResult, contentModel); //推送 string pushResult = PostWebRequest(postUrl, json, Encoding.UTF8); U_WeChatResult resultModel = JsonHelper.JsonToModel <U_WeChatResult>(pushResult); if (resultModel.errcode == 0) { UpdatePushStatus(contentModel); } return(pushResult); }
/// <summary> /// 发送短信验证码 /// </summary> /// <param name="accessTokenModel">授权对象</param> /// <param name="contentModel">消息模板</param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { HttpClient httpClient = new HttpClient(); //将服务凭证转换为Base64编码格式 byte[] auth = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", ConfigSugar.GetAppString("SMSAppKey"), ConfigSugar.GetAppString("MasterSecret"))); String auth64 = Convert.ToBase64String(auth); //创建并指定服务凭证,认证方案为Basic httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", auth64); U_Notification_Teamp_Para ntp = new U_Notification_Teamp_Para(); //将短信营收实体转换微信 ntp.Notification = contentModel.Message; /*U_Temp_Para tp = new U_Temp_Para();*/ U_Para para = new U_Para(); para.mobile = contentModel.PushObject[0].PhoneNumber.Trim(); para.temp_id = Convert.ToInt32(ConfigSugar.GetAppString("Notification_Temp_ID")); para.temp_para = ntp; string json = Common.JsonHelper.ModelToJson <U_Para>(para); System.Net.Http.StringContent sc = new System.Net.Http.StringContent(json); sc.Headers.Remove("Content-Type"); sc.Headers.Add("Content-Type", "application/json"); Task <HttpResponseMessage> taskHrm = httpClient.PostAsync(_noticeUrl, sc); Task.WaitAll(taskHrm); Task <string> taskStr = taskHrm.Result.Content.ReadAsStringAsync(); Task.WaitAll(taskStr); UpdatePushStatus(contentModel); return(taskStr.Result); }
/// <summary> /// 发送短信验证码 /// </summary> /// <param name="accessTokenModel">授权对象</param> /// <param name="contentModel">消息模板</param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { HttpClient httpClient = new HttpClient(); //将服务凭证转换为Base64编码格式 byte[] auth = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", ConfigSugar.GetAppString("SMSAppKey"), ConfigSugar.GetAppString("MasterSecret"))); String auth64 = Convert.ToBase64String(auth); //创建并指定服务凭证,认证方案为Basic httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", auth64); ///发送短信验证码参数 U_Para para = new U_Para(); para.mobile = contentModel.PushObject[0].PhoneNumber.Trim(); para.temp_id = 1; //将参数转换为Json字符串 string json = para.ModelToJson(); //构造HTTP 字符内容对象 System.Net.Http.StringContent sc = new System.Net.Http.StringContent(json); //移除Content-Type内容 sc.Headers.Remove("Content-Type"); //Content-Type内容设置为JSON类型 sc.Headers.Add("Content-Type", "application/json"); //发送短信 Task <HttpResponseMessage> taskHrm = httpClient.PostAsync(_verificationCodeUrl, sc); Task.WaitAll(taskHrm); //获取返回值 Task <string> taskStr = taskHrm.Result.Content.ReadAsStringAsync(); Task.WaitAll(taskStr); httpClient.Dispose(); UpdatePushStatus(contentModel); return(taskStr.Result); }
/// <summary> /// 从微信后台获取人员的状态,并且将状态同步至数据库中 /// </summary> public static void UpdatePersonStatus() { bool result = false; int time = 0; while (true) { if (DateTime.Now.Hour == 2) { time = 0; } if (DateTime.Now.Hour != 1 || time != 0) { continue; //时间为凌晨1点并且time为0的时候执行同步操作 } try { U_AccessToken accessTokenModel = new U_AccessToken(); accessTokenModel.UserKey = ConfigSugar.GetAppString("WeChatCorpID"); accessTokenModel.UserPassword = ConfigSugar.GetAppString("WeChatSecret"); var accessToken = WeChatTools.GetAccessoken(accessTokenModel); var departments = WeChatTools.GetDepartment(accessToken); //获取所有的部门 UpdatePersonLogic _updatePersonLogic = new UpdatePersonLogic(); foreach (var item in departments.department) { var users = WeChatTools.GetUsers(accessToken, item.id.ToString()); //根据部门获取所有的人员 result = _updatePersonLogic.UpdatePersonStatus(users.userlist); } } catch (Exception exp) { LogManager.WriteLog(LogFile.Error, "同步人员状态:" + result + "/n" + exp); } time++; } }
/// <summary> /// 获取公司账号信息 /// (获取企业号AccessToken) /// </summary> /// <returns></returns> protected bool SetCorpAccount(U_AccessToken accessToken) { string respText = ""; bool result = false; //获取josn数据 string url = string.Format(_tokenUrl, accessToken.UserKey, accessToken.UserPassword); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream resStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(resStream, Encoding.Default); respText = reader.ReadToEnd(); resStream.Close(); } try { JavaScriptSerializer Jss = new JavaScriptSerializer(); Dictionary <string, object> respDic = (Dictionary <string, object>)Jss.DeserializeObject(respText); //通过键access_token获取值 _accessToken = respDic["access_token"].ToString(); if (!string.IsNullOrEmpty(_accessToken)) { result = true; } } catch (Exception ex) { LogManager.WriteLog(LogFile.Error, "获取AccessToken PushWeChat.cs:" + ex.ToString() + "/n" + ex.StackTrace); } return(result); }
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { //获取AccessToken bool isSuccess = SetCorpAccount(accessTokenModel); if (isSuccess) { var listRedPacket = new List <Business_Redpacket_Push_Information>(); //List<U_WeChatUser> weChatUserList = SearchWeChatUserList(); //string pushObject = GetPushObject(contentModel, weChatUserList);//13788907365|15618738991|18301914615 string pushObject = GetPushObject(contentModel); string[] pushObjs = pushObject.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); //推送的人数 int[] redPacket = new int[pushObjs.Length - 1]; try { //固定金额红包推送 总金额固定,按照人数计算每个红包金额(每个红包金额需一致) // 注:如果无法平均分配,则最后一人多出(例:10元分给3人,则金额为3.3、3.3、3.4) if (contentModel.RedpacketType == 1) { int money = (int)(contentModel.RedpacketMoney * 100); //总金额(分) redPacket = GetAvgRedPacket(pushObjs.Length, money); } else if (contentModel.RedpacketType == 2) //红包总金额(RMB),推送给每人的金额随机。 { int money = (int)(contentModel.RedpacketMoney * 100); //总金额(分) redPacket = GetRandomRedPacket(pushObjs.Length, money); } else if (contentModel.RedpacketType == 3) //输入单个红包随机金额区间(RMB),发给每人红包的金额在此区间内 { int moneyFrom = (int)(contentModel.RedpacketMoneyFrom * 100); int moneyTo = (int)(contentModel.RedpacketMoneyTo * 100); redPacket = GetSingleRandomRedPacket(pushObjs.Length, moneyFrom, moneyTo); } for (int i = 0; i < pushObjs.Length; i++) { WxPayData data = new WxPayData(); Business_Redpacket_Push_Information redpacketPushInfo = new Business_Redpacket_Push_Information(); redpacketPushInfo.Business_WeChatPushVguid = contentModel.VGUID; //推送主键 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 var outTradeNo = WxPayApi.GenerateOutTradeNo(); redpacketPushInfo.OrderNumber = outTradeNo; data.SetValue("mch_billno", outTradeNo); //商户订单号 data.SetValue("mch_id", WxPayConfig.MCHID); //商户号 data.SetValue("wxappid", WxPayConfig.APPID); //公众账号ID data.SetValue("sender_name", "大众交通出租分公司"); //商户名称 //string filePath = AppDomain.CurrentDomain.BaseDirectory + "logo.png"; //string mediaid = UploadTempResource(filePath); data.SetValue("sender_header_media_id", "1G6nrLmr5EC3MMb_-zK1dDdzmd0p7cNliYu9V5w7o8K0"); //发送者头像,此id为微信默认的头像 string openid = ConvertToOpenidByUserId(_accessToken, pushObjs[i]); var openInfo = JsonHelper.JsonToModel <U_OpenInfo>(openid); JsonConvert.DeserializeObject <U_OpenInfo>(openid); data.SetValue("re_openid", openInfo.openid); //用户openid data.SetValue("total_amount", redPacket[i]); //付款金额,单位分 redpacketPushInfo.RedpacketMoney = (decimal)(redPacket[i] * 1.0 / 100); //红包金额 data.SetValue("wishing", contentModel.Message); //红包祝福语 data.SetValue("act_name", contentModel.Title); //活动名称 data.SetValue("remark", "快来抢"); //备注 data.SetValue("scene_id", "PRODUCT_4"); //场景(金额大于200元时必填) data.SetValue("workwx_sign", data.MakeWorkWxSign("redPacket")); //企业微信签名 data.SetValue("sign", data.MakeSign()); //微信支付签名 redpacketPushInfo.UserID = pushObjs[i]; //红包接收人的微信号 string xml = data.ToXml(); const string postUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendworkwxredpack"; //发送企业红包接口地址 string response = PostWebRequest(postUrl, xml, Encoding.UTF8, true); //调用HTTP通信接口提交数据到API WxPayData result = new WxPayData(); result.FromXml(response); if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { redpacketPushInfo.RedpacketStatus = 2; //已发送待领取 } else { redpacketPushInfo.RedpacketStatus = 3; //发送失败 redpacketPushInfo.Reson = result.GetValue("err_code_des").ToString(); LogManager.WriteLog(LogFile.Error, result.GetValue("err_code") + ":" + result.GetValue("err_code_des")); } redpacketPushInfo.VGUID = Guid.NewGuid(); redpacketPushInfo.CreatedDate = DateTime.Now; redpacketPushInfo.CreatedUser = "******"; listRedPacket.Add(redpacketPushInfo); } } catch (Exception ex) { LogManager.WriteLog(LogFile.Error, ex.ToString()); return("推送失败!"); } UpdatePushStatus(contentModel); InsertRedPacketInfo(listRedPacket); return("推送成功!"); } return("推送失败!"); }
protected override U_UploadResult UpLoadSource(U_AccessToken accessTokenModel, U_Content contentModel) { U_UploadResult uploadResult = new U_UploadResult(); return(uploadResult); }
/// <summary> /// 微信推送或者短信推送 /// </summary> /// <param name="accessTokenModel">授权对象</param> /// <param name="contentModel">消息</param> /// <returns></returns> public abstract string Push(U_AccessToken accessTokenModel, U_Content contentModel);
/// <summary> /// 微信推送或者短信推送 /// </summary> /// <param name="accessTokenModel">授权对象</param> /// <param name="contentModels">消息</param> /// <returns></returns> public abstract List <string> Push(U_AccessToken accessTokenModel, List <U_Content> contentModels);
protected override U_UploadResult UpLoadSource(U_AccessToken accessTokenModel, U_Content contentModel) { return(null); }
/// <summary> /// 重写Push方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override List <string> Push(U_AccessToken accessTokenModel, List <U_Content> contentModels) { throw new NotImplementedException(); }
/// <summary> /// 重写Push方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { throw new NotImplementedException(); }
/// <summary> /// 上传素材 /// </summary> /// <returns></returns> protected abstract U_UploadResult UpLoadSource(U_AccessToken accessTokenModel, U_Content contentModel);
/// <summary> /// 重写推送方法 /// </summary> /// <param name="accessTokenModel"></param> /// <param name="contentModel"></param> /// <returns></returns> public override string Push(U_AccessToken accessTokenModel, U_Content contentModel) { //获取AccessToken bool isSuccess = SetCorpAccount(accessTokenModel); // var isOk = 0; if (isSuccess) { var payments = new List <Business_Enterprisepayment_Information>(); string postUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/paywwsptrans2pocket"; //List<U_WeChatUser> weChatUserList = SearchWeChatUserList(); //string pushObject = GetPushObject(contentModel, weChatUserList);//13788907365|15618738991|18301914615 string pushObject = GetPushObject(contentModel); string[] pushObjs = pushObject.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); //推送的人数 int money = (int)(contentModel.RedpacketMoney * 100); //总金额(分) var redPacket = Enumerable.Repeat(money, pushObjs.Length).ToArray(); for (int i = 0; i < pushObjs.Length; i++) { var payment = new Business_Enterprisepayment_Information(); payment.Business_WeChatPushVguid = contentModel.VGUID; WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); //公众账号ID data.SetValue("mch_id", WxPayConfig.MCHID); //商户号 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 var outTradeNo = WxPayApi.GenerateOutTradeNo(); payment.OrderNumber = outTradeNo; data.SetValue("partner_trade_no", outTradeNo); //商户订单号 string openid = ConvertToOpenidByUserId(_accessToken, pushObjs[i]); var openInfo = openid.JsonToModel <U_OpenInfo>(); data.SetValue("openid", openInfo.openid); //商户appid下,某用户的openid data.SetValue("check_name", "NO_CHECK"); //校验用户姓名选项(NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓名) //data.SetValue("re_user_name", "刘洋"); //收款用户真实姓名。 如果check_name设置为FORCE_CHECK,则必填用户真实姓名 data.SetValue("amount", redPacket[i]); //金额,单位为分 payment.RedpacketMoney = (decimal)(redPacket[i] * 1.0 / 100); //红包金额 data.SetValue("desc", contentModel.Message); //付款说明 data.SetValue("spbill_create_ip", "192.168.0.1"); //Ip地址 data.SetValue("ww_msg_type", "NORMAL_MSG"); //付款消息类型 data.SetValue("act_name", contentModel.Title); //项目名称 data.SetValue("workwx_sign", data.MakeWorkWxSign("payment")); //企业微信签名 data.SetValue("sign", data.MakeSign()); //微信支付签名 payment.UserID = pushObjs[i]; //红包接收人的微信号 string xml = data.ToXml(); string response = PostWebRequest(postUrl, xml, Encoding.UTF8, true); //调用HTTP通信接口提交数据到API WxPayData result = new WxPayData(); result.FromXml(response); if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { payment.RedpacketStatus = 1; //成功 var paymentTime = result.GetValue("payment_time").ToString(); payment.CreatedDate = DateTime.Parse(paymentTime); } else { payment.RedpacketStatus = 2; //失败 payment.Reson = result.GetValue("err_code_des").ToString(); LogManager.WriteLog(LogFile.Error, result.GetValue("err_code") + ":" + result.GetValue("err_code_des")); } payment.VGUID = Guid.NewGuid(); payment.CreatedDate = DateTime.Now; payment.CreatedUser = "******"; payments.Add(payment); } InsertPaymentInfos(payments); UpdatePushStatus(contentModel); return("推送成功!"); } return("推送失败!"); }
/// <summary> /// 推送(短信、微信) /// </summary> public static void PushContentFunction() { try { while (true) { PushServer ps = new PushServer(); U_AccessToken accessTokenModel = new U_AccessToken(); accessTokenModel.UserKey = ConfigSugar.GetAppString("WeChatCorpID"); accessTokenModel.UserPassword = ConfigSugar.GetAppString("WeChatSecret"); string responseMsg = ""; bool result = false; #region 推送图文 List <Business_WeChatPush_Information> listImgPush = ps.GetImgPushList();//获取要推送的数据 List <U_Content> contentList = new List <U_Content>(); foreach (var imgPush in listImgPush) { //主表信息 U_Content content = new U_Content(); content.Message = imgPush.Message; content.MessageType = imgPush.MessageType; content.Title = imgPush.Title; content.CoverDescption = imgPush.CoverDescption; content.CoverImg = imgPush.CoverImg; content.PushType = imgPush.PushType; content.VGUID = imgPush.VGUID; content.RevenueType = 0; content.PushObject = ps.GetPushUserWeChat(imgPush);//获取推送信息接收者信息列表 contentList.Add(content); //子表信息 var moreGraphicList = ps.GetMoreGraphicList(imgPush.VGUID); PushFunction.PushFunction pf = PushFunctionFactory.PushFunc(PushMode.WeChat, MsgType.SingleTextAndImg); foreach (var item in moreGraphicList) { U_Content contentGraphic = new U_Content(); contentGraphic.Message = item.Message; contentGraphic.Title = item.Title; contentGraphic.CoverDescption = item.CoverDescption; contentGraphic.CoverImg = item.CoverImg; contentGraphic.VGUID = item.VGUID; contentGraphic.RevenueType = item.Ranks; contentList.Add(contentGraphic); } var pushPersonList = contentList[0].PushObject; //如果发送对象超过1000个则需要分批发送 if (pushPersonList.Count > 1000) { int pushCount = (pushPersonList.Count / 1000) + 1;//分批发送(发送次数) for (int i = 0; i < pushCount; i++) { contentList[0].PushObject = pushPersonList.Skip(i * 1000).Take(1000).ToList(); //定时发送 if (contentList[0].TimedSendTime != null) { if (DateTime.Now >= contentList[0].TimedSendTime) { pf.Push(accessTokenModel, contentList); } } else { pf.Push(accessTokenModel, contentList); } } } else { //定时发送 if (contentList[0].TimedSendTime != null) { if (DateTime.Now >= contentList[0].TimedSendTime) { pf.Push(accessTokenModel, contentList); } } else { pf.Push(accessTokenModel, contentList); } } } #endregion List <Business_WeChatPush_Information> pushList = ps.GetPushList();//获取要推送的数据 //循环推送数据列表(获取要推送人员列表) foreach (var item in pushList) { try { PushFunction.PushFunction pf = PushFunctionFactory.PushFunc((PushMode)item.PushType, (MsgType)item.MessageType); if (item.PushType == 1)//微信 { U_Content content = new U_Content(); //content.PushObject = "@all"; //content.Message = "D:\\567925.png"; content.Message = item.Message; content.ExercisesVGUID = item.ExercisesVGUID; content.MessageType = item.MessageType; content.Title = item.Title; content.CoverDescption = item.CoverDescption; content.CoverImg = item.CoverImg; content.PushType = item.PushType; content.VGUID = item.VGUID; content.RevenueType = item.RevenueType; content.RedpacketMoney = item.RedpacketMoney; content.RedpacketType = item.RedpacketType; content.RedpacketMoneyFrom = item.RedpacketMoneyFrom; content.RedpacketMoneyTo = item.RedpacketMoneyTo; List <Business_Personnel_Information> pushPersonList = ps.GetPushUserWeChat(item);//获取推送信息接收者信息列表 content.PushObject = pushPersonList; //如果发送对象超过1000个则需要分批发送 if (pushPersonList.Count > 1000) { int pushCount = (pushPersonList.Count / 1000) + 1;//分批发送(发送次数) for (int i = 0; i < pushCount; i++) { content.PushObject = pushPersonList.Skip(i * 1000).Take(1000).ToList(); //定时发送 if (item.TimedSendTime != null) { if (DateTime.Now >= item.TimedSendTime) { pf.Push(accessTokenModel, content); } } else { pf.Push(accessTokenModel, content); } } } else { //定时发送 if (item.TimedSendTime != null) { if (DateTime.Now >= item.TimedSendTime) { pf.Push(accessTokenModel, content); } } else { pf.Push(accessTokenModel, content); } } } else//短信 { List <Business_Personnel_Information> pushPersonList = ps.GetPushUserSms(item);//获取推送信息接收者信息列表 List <U_Content> uCountList = new List <U_Content>(); foreach (var person in pushPersonList) { U_Content content = new U_Content(); content.Message = item.Message; content.MessageType = item.MessageType; content.Title = item.Title; content.CoverDescption = item.CoverDescption; content.CoverImg = item.CoverImg; content.PushType = item.PushType; content.VGUID = item.VGUID; content.PushObject = new List <Business_Personnel_Information>(); content.PushObject.Add(person); uCountList.Add(content); } //定时发送 if (item.TimedSendTime != null) { if (DateTime.Now >= item.TimedSendTime) { pf.Push(accessTokenModel, uCountList); } } else { pf.Push(accessTokenModel, uCountList); } } } catch (Exception ex) { LogManager.WriteLog(LogFile.Error, ex.ToString()); } } Thread.Sleep(5 * 1000); } } catch (Exception ex) { Console.WriteLine(ex.Message); LogManager.WriteLog(LogFile.Error, ex.ToString()); } }