private static void HandleGainLoanerRepaymentSuccess(DateTime gainAt, int repaymentTaskId, int loanerUserId, decimal amount) { var context = new Agp2pDataContext(); var loaner = context.dt_users.Single(u => u.id == loanerUserId); var task = context.li_repayment_tasks.Single(r => r.id == repaymentTaskId); var repayTaskCount = task.li_projects.li_repayment_tasks.Count(ta => ta.status != (int)Agp2pEnums.RepaymentStatusEnum.Invalid); var smsContent = $"你已于 {gainAt.ToString("yyyy-MM-dd HH:mm")} 成功还款 {amount} 到项目{task.li_projects.title} 的第 {task.term}/{repayTaskCount} 期,包括本金:{task.repay_principal},利息:{task.repay_interest}"; try { var errorMsg = string.Empty; if (!SMSHelper.SendTemplateSms(loaner.mobile, smsContent, out errorMsg)) { context.AppendAdminLogAndSave("LoanerRepaySuccessHint", $"发送还款成功信息失败:{errorMsg}(借款人:{loaner.GetFriendlyUserName()},项目名称:{task.li_projects.title})"); } } catch (Exception ex) { context.AppendAdminLogAndSave("LoanerRepaySuccessHint", $"发送还款成功信息失败:{ex.GetSimpleCrashInfo()}(借款人:{loaner.GetFriendlyUserName()},项目名称:{task.li_projects.title})"); } }
public bool getCode() { var smsHelper = new SMSHelper(); string mobile, code = ""; try { UserBll uBll = new UserBll(); mobile = Request.Params["mobile"].ToString(); if (uBll.CheckCanSendSms(mobile)) { code = DateTime.Now.ToString("ssff"); //code = "1234"; Session["generate_code"] = code; smsHelper.SendSms(mobile, code); SMSLog smsLog = new SMSLog() { telephone = mobile, content = code, Browser = Request.Browser.Browser, ip = Request.UserHostAddress, kdate = DateTime.Now }; uBll.AddUserSMSLog(smsLog); } return(true); } catch (Exception) { return(false); } }
public Task SendAsync(IdentityMessage message) { SMSHelper.SendSMS(new SmsSendMessageDTO { Mobile = "18210201837", SmsContent = string.Format("您的验证码是: {0}, 请立即使用", "2342"), Type = SmsType.Captcha }); return(Task.FromResult(0)); }
private IHttpActionResult SendVerifyCode(string mobile, string templateContent, string reason) { templateContent = templateContent ?? "您的验证码为:{code},{valid}分钟内有效。"; var strcode = Utils.Number(4); //随机验证码 var siteConfig = ConfigLoader.loadSiteConfig(); var regSmsExpired = ConfigLoader.loadUserConfig().regsmsexpired; //替换标签 var msgContent = templateContent .Replace("{webname}", siteConfig.webname) .Replace("{weburl}", siteConfig.weburl) .Replace("{webtel}", siteConfig.webtel) .Replace("{code}", strcode) .Replace("{valid}", regSmsExpired.ToString()); //发送短信 string tipMsg; if (Utils.IsDebugging()) { Debug.WriteLine(msgContent); } else if (!SMSHelper.SendSmsCode(mobile, msgContent, out tipMsg)) { return(InternalServerError(new Exception("发送失败," + tipMsg))); } MemoryCache.Default.Set(reason + ":" + mobile, strcode, DateTime.Now.AddMinutes(regSmsExpired)); return(Ok("发送短信验证码成功")); }
private static void HandleHuoqiWithdraw(int userId, int projectId, decimal amount) { var context = new Agp2pDataContext(); // 找出所有需要赎回的债权,判断中间人的余额是否足够支付,并提醒中间人 var needTransferClaims = context.li_claims.Where(c => c.profitingProjectId == projectId && c.status == (int)Agp2pEnums.ClaimStatusEnum.NeedTransfer && !c.Children.Any()).ToList(); needTransferClaims.GroupBy(c => c.dt_users_agent).ToDictionary(g => g.Key, g => g.Sum(c => c.principal)).ForEach( pair => { var msgContent = $"有用户进行了活期转出,目前总转出金额为 {pair.Value},您的余额为 {pair.Key.li_wallets.idle_money},请于一日内保证账号内的余额足以赎回活期债权"; try { var errorMsg = string.Empty; if (!SMSHelper.SendTemplateSms(pair.Key.mobile, msgContent, out errorMsg)) { context.AppendAdminLogAndSave("Huoqi", $"发送活期转出提醒失败:{errorMsg},中间人:{pair.Key.GetFriendlyUserName()},短信内容:{msgContent}"); } } catch (Exception ex) { context.AppendAdminLogAndSave("Huoqi", $"发送活期转出提醒失败:{ex.GetSimpleCrashInfo()},中间人:{pair.Key.GetFriendlyUserName()},短信内容:{msgContent}"); } }); }
public async Task <ResponseModel> RegisterAsync(UserRegisterModel userRegisterModel) { var user = await _userRepository.FetchFirstAsync(x => x.Mobile == userRegisterModel.Mobile); if (user != null) { return(new ResponseModel() { StatusCode = System.Net.HttpStatusCode.BadRequest, Message = "Số điện thoại đã được đăng kí. Sử dụng chức năng quên mật khẩu để lấy lại!"// TODO: multi language }); } else { user = AutoMapper.Mapper.Map <User>(userRegisterModel); userRegisterModel.Password.GeneratePassword(out string saltKey, out string hashPass); user.Password = hashPass; user.PasswordSalt = saltKey; var verifyCode = SMSHelper.GenerateVerifyNumber(); user.VerifyCode = verifyCode; SMSHelper.SendMessage(verifyCode, user.Mobile); return(await _userRepository.InsertAsync(user)); } }
public bool InitiateSignUpProcess(UserSignUp signupdetails) { try { bool isSignin = this._signUpDA.InitiateSignUpProcess(signupdetails); if (isSignin && signupdetails.UserType == 2) { this._signInDA = new SignInDataAccess(); var objEmail = this._signInDA.GetEmailData("GET_PWD_CSR"); objEmail.Body = string.Format(objEmail.Body, signupdetails.FirstName); EmailHelper.SendEmail(objEmail, signupdetails.EmailAddress); objEmail = this._signInDA.GetEmailData("GET_PWD_CSR_SMS"); objEmail.Body = string.Format(objEmail.Body, signupdetails.FirstName); SMSHelper.SendSMS(objEmail, signupdetails.PhoneNumber); } return(isSignin); } catch (Exception ex) { //Log throw ex; } finally { //Log } }
public async Task <ResponseModel> ResendCodeAsync(Guid userId) { var user = await _userRepository.GetByIdAsync(userId); if (user == null) { return(new ResponseModel() { StatusCode = System.Net.HttpStatusCode.NotFound, Message = "User không tồn tại trong hệ thống. Vui lòng kiểm tra lại!" }); } else { var verifyCode = SMSHelper.GenerateVerifyNumber(); user.VerifyCode = verifyCode; await _userRepository.UpdateAsync(user); SMSHelper.SendMessage(verifyCode, user.Mobile); return(new ResponseModel() { StatusCode = System.Net.HttpStatusCode.OK, Message = "Đã gửi mã xác nhận tới số điện thoại đăng ký!" }); } }
public UserAccessCodeResponse GetAccessCode(UserLogin user) { try { var userAccessCodeResponse = this._signInDA.GetAccessCode(user); if (user.GetCodeMethod.ToLower() == "email") { var objEmail = this._signInDA.GetEmailData("GET_ACCESS_CODE"); objEmail.Body = string.Format(objEmail.Body, userAccessCodeResponse.AccessCode); EmailHelper.SendEmail(objEmail, userAccessCodeResponse.EmailAddress); } else { var objEmail = this._signInDA.GetEmailData("GET_ACCESS_CODE_SMS"); objEmail.Body = string.Format(objEmail.Body, userAccessCodeResponse.AccessCode); SMSHelper.SendSMS(objEmail, userAccessCodeResponse.PhoneNumber); } return(userAccessCodeResponse); } catch (Exception ex) { return(new UserAccessCodeResponse { ErrorMessage = ex.Message }); } finally { } }
public async Task <bool> Approve(int id) { Withdraw withdraw = await GetByIdAsync <Withdraw>(id); if (withdraw.Status == WithdrawStatus.APPROVED) { return(true); } Member member = await GetByIdAsync <Member>(withdraw.MemberId); if (member.Score < withdraw.Score) { return(false); } withdraw.Status = WithdrawStatus.APPROVED; withdraw.OperateTime = DateTime.Now; WithdrawType withdrawType = await GetDbSet <WithdrawType>().Where(o => o.Id == withdraw.WithdrawTypeId).FirstOrDefaultAsync(); PayRecordHelper payRecordHelper = new PayRecordHelper(); await payRecordHelper.SaveAsycn(withdraw, withdrawType, member); string strMsg = string.Empty; SMSHelper.SendPay(member.Phone, withdraw.Score - withdraw.Score * withdraw.TaxPercentage, withdrawType.Name, out strMsg); MemberHelper memberHelper = new MemberHelper(); await memberHelper.AddScore(member, -withdraw.Score, withdrawType.Name + "提现", true); return(await SaveChangesAsync()); }
public async Task <IActionResult> Mobile([FromServices] IConfiguration configuration, [FromQuery] string phone, [FromQuery] string code) { var option = configuration.GetSection(nameof(SMSOptions)).Get <SMSOptions>(); var auth = SMSHelper.Validate(phone, code, option.MD5Key); HttpContext.Log(phone, auth); if (auth) { var user = UserHelper.Retrieves().FirstOrDefault(u => u.UserName == phone); if (user == null) { user = new User() { ApprovedBy = "Mobile", ApprovedTime = DateTime.Now, DisplayName = "手机用户", UserName = phone, Password = code, Icon = "default.jpg", Description = "手机用户", App = option.App }; UserHelper.Save(user); // 根据配置文件设置默认角色 var roles = RoleHelper.Retrieves().Where(r => option.Roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id); RoleHelper.SaveByUserId(user.Id, roles); } } return(auth ? await SignInAsync(phone, true, MobileSchema) : View("Login", new LoginModel() { AuthFailed = true })); }
public static CreateMessageOptions Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { string requestBody = new StreamReader(req.Body).ReadToEndAsync().Result; // the string is coming through with extra escape characters in the string. string fixedBody = Regex.Unescape(requestBody); fixedBody = fixedBody.Substring(1); fixedBody = fixedBody.Substring(0, fixedBody.Length - 1); log.LogInformation($"Message Body: {fixedBody}"); var predictionNotification = JsonConvert.DeserializeObject <PredictionNotification>(fixedBody); var message = new CreateMessageOptions(predictionNotification.ToPhoneNumber) { Body = SMSHelper.FormatSMS(predictionNotification), From = fromPhoneNumber, }; return(message); } catch (Exception ex) { log.LogError(ex, "Error sending SMS Message."); } return(null); }
private string GetSmsCount() { string code = string.Empty; int count = SMSHelper.GetAccountQuantity(out code); if (code == "115") { return("查询出错:请完善账户信息"); } else if (code != "100") { if (code == "-2") { code = "失败"; } else if (code == "-1") { code = "用户名或者密码不正确"; } else if (code == "-9") { code = "没有url提交权限"; } return("错误信息:" + code); } return(count + " 条"); }
/// <summary> /// 获取手机验证码 /// </summary> public void GetSMSCode() { using (ProxyBE p = new ProxyBE()) { try { string phone = Request["phone"]; if (string.IsNullOrEmpty(phone)) { throw new Exception("手机号不能为空"); } string smsCode = SMSHelper.GetRandom(6); bool isComplete = false; //短信验证码限制:小于等于 1天/5次 5条/小时 累计10条/天 string message = SMSHelper.SendMessage(phone, smsCode, out isComplete, "SMS_134320239"); if (isComplete) { // 将手机验证码存入session SetCacheSMSCode(smsCode); } else { throw new Exception("发送失败," + message); } WriteMessage(1, "发送成功"); } catch (Exception ex) { WriteError(ex.Message, ex); } } }
private bool SendEmailInvitation(AuctionDetails auctiondetails, ArrayList recipients, ref int failedcount, ref int successcount) { bool success = false; string subject = "Trans-Asia / Commnunications : Invitation to Auction"; failedcount = 0; successcount = 0; try { for (int i = 0; i < recipients.Count; i++) { AuctionParticipant p = (AuctionParticipant)recipients[i]; if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(), MailHelper.ChangeToFriendlyName(auctiondetails.Creator, auctiondetails.CreatorEmail), MailHelper.ChangeToFriendlyName(p.Name, p.EmailAddress), subject, CreateInvitationBody(auctiondetails, p), MailTemplate.GetTemplateLinkedResources(this))) { // if sending failed failedcount++; LogHelper.EventLogHelper.Log("Auction > Send Invitation : Sending Failed to " + p.EmailAddress, System.Diagnostics.EventLogEntryType.Error); } else { // if sending successful successcount++; LogHelper.EventLogHelper.Log("Auction > Send Invitation : Email Sent to " + p.EmailAddress, System.Diagnostics.EventLogEntryType.Information); // update sent mail count SqlHelper.ExecuteNonQuery(connstring, "sp_SendEmailInvitation", new SqlParameter[] { new SqlParameter("@ParticipantId", p.ID) }); } } success = true; } catch (Exception ex) { success = false; LogHelper.EventLogHelper.Log("Auction > Send Invitation : " + ex.Message, System.Diagnostics.EventLogEntryType.Error); } try { for (int j = 0; j < recipients.Count; j++) { AuctionParticipant p = (AuctionParticipant)recipients[j]; if (SMSHelper.AreValidMobileNumbers(p.MobileNo.Trim())) { SMSHelper.SendSMS(new SMSMessage(CreateSMSInvitationBody(auctiondetails, p).Trim(), p.MobileNo.Trim())).ToString(); } } } catch (Exception ex) { LogHelper.EventLogHelper.Log("Auction > Send SMS Invitation : " + ex.Message, System.Diagnostics.EventLogEntryType.Error); } return(success); }
/// <summary> /// 抢优惠券 /// </summary> /// <param name="id">优惠券种类Id</param> /// <returns></returns> public ActionResult couponOwn(int id) { if (_workContext.CurrentUser == null) { return(Redirect("http://www.iyookee.cn/#/user/login")); } var couponCategory = _couponCategoryService.GetCouponCategoryById(id); var condition = new CouponSearchCondition { CouponCategoryId = id, Status = 0 }; var coupon = _couponService.GetCouponByCondition(condition).FirstOrDefault(); _couponOwnerService.CreateRecord(_workContext.CurrentUser.Id, coupon.Id); coupon.Status = EnumCouponStatus.Owned; _couponService.Update(coupon); couponCategory.Count = couponCategory.Count - 1; _couponCategoryService.UpdateCouponCategory(couponCategory); var brand = _productBrandService.GetProductBrandById(couponCategory.BrandId); var CouponOwn = new CouponCategoryModel { Name = couponCategory.Name, Number = coupon.Number, BrandName = brand.Bname }; var phone = _brokerService.GetBrokerByUserId(_workContext.CurrentUser.Id).Phone; //短信发送 SMSHelper.Sending(phone, "优惠券为:" + brand.Bname + ",券号为:" + coupon.Number + " 【优客惠】"); return(View(CouponOwn)); }
private static void HandleProjectFinancingFailMsg(int projectId) { var context = new Agp2pDataContext(); var project = context.li_projects.Single(p => p.id == projectId); // 查出所有已经退款的投资者 TODO 排除自己退款的投资者 var investors = project.li_project_transactions.Where( ptr => ptr.type == (int)Agp2pEnums.ProjectTransactionTypeEnum.Invest && ptr.status == (int)Agp2pEnums.ProjectTransactionStatusEnum.Rollback) .GroupBy(ptr => ptr.dt_users).Select(g => g.Key); var sendTime = DateTime.Now; //找出模板 var smsModel = context.dt_sms_template.SingleOrDefault(te => te.call_index == "project_financing_fail"); if (smsModel == null) { throw new InvalidOperationException("找不到流标提醒模板: project_financing_fail"); } var msgContent = smsModel.content .Replace("{project}", project.title) .Replace("{date}", sendTime.ToString("yyyy-MM-dd HH:mm")); // 通知投资者项目流标 investors.ForEach(investor => { try { //发送站内消息 var userMsg = new dt_user_message { type = 1, post_user_name = "", accept_user_name = investor.user_name, title = smsModel.title, content = msgContent, post_time = sendTime, receiver = investor.id }; context.dt_user_message.InsertOnSubmit(userMsg); context.SubmitChanges(); var errorMsg = string.Empty; if (!SMSHelper.SendTemplateSms(investor.mobile, msgContent, out errorMsg)) { context.AppendAdminLogAndSave("ProjectFinancingFailSms", string.Format("发送项目流标提醒失败:{0}(客户ID:{1},项目名称:{2})", errorMsg, investor.user_name, project.title)); } } catch (Exception ex) { context.AppendAdminLogAndSave("ProjectFinancingFailSms", string.Format("发送项目流标提醒失败:{0}(客户ID:{1},项目名称:{2})", ex.GetSimpleCrashInfo(), investor.user_name, project.title)); } }); }
public async Task <ActionResult> ForgotPassword([FromBody] ForgotPasswordModel data) { try { string OTP; var checkUser = MH.CheckForDatas("UserName", data.UserName, null, null, "Authentication", "Authentication"); var filter = Builders <BsonDocument> .Filter.Eq("UserName", data.UserName); var user = MH.GetSingleObject(filter, "Authentication", "Authentication").Result; if (user != null) { var userData = BsonSerializer.Deserialize <RegisterModel>(user); VerificationModel smsModel = new VerificationModel(); smsModel.UserName = data.UserName; if (data.UserLocation == "IN") { Random codeGenerator = new Random(); OTP = codeGenerator.Next(0, 1000000).ToString("D6"); smsModel.VerificationCode = OTP; SMSHelper.SendSMS(data.UserName, OTP); } else { OTP = Guid.NewGuid().ToString(); string link = GlobalHelper.GetIpConfig() + data.UserName + "/" + OTP + "/yes"; await EmailHelper.SendEmail(userData.FullName, data.UserName, link); } var update = Builders <BsonDocument> .Update.Set("Status", "Not Verified").Set("OTPExp", DateTime.UtcNow.AddMinutes(2)) .Set("VerificationCode", smsHasher.HashPassword(smsModel, OTP)); var result = MH.UpdateSingleObject(filter, "Authentication", "Authentication", update).Result; return(Ok(new ResponseData { Code = "200", Message = "Success", Data = null })); } else { return(BadRequest(new ResponseData { Code = "404", Message = "User not found", Data = null })); } } catch (Exception ex) { LoggerDataAccess.CreateLog("AuthController", "ForgetPassword", "ForgetPassword", ex.Message); return(BadRequest(new ResponseData { Code = "400", Message = "Failed", Data = null })); } }
private void sendNewTradePwd(string mobile, string newTradePwd, Action <int, string> callback) { if (string.IsNullOrWhiteSpace(mobile)) { callback((int)HttpStatusCode.PreconditionFailed, "请先验证手机号"); return; } // last_send_ran_trade_pwd_at : DateTime? // 限制发送时间间隔 var lastSendVerifyingSMSAt = (DateTime?)SessionHelper.Get("last_send_ran_trade_pwd_at"); if (lastSendVerifyingSMSAt != null && DateTime.Now.Subtract(lastSendVerifyingSMSAt.Value).TotalSeconds < 600) { callback(429, "发送重置交易密码的短信的间隔为 10 分钟,您刚才已经发送过啦,休息一下再来吧!"); return; } SessionHelper.Set("last_send_ran_trade_pwd_at", DateTime.Now); //获得短信模版内容 var smsModel = new sms_template().GetModel("reset_trade_pwd"); if (smsModel == null) { callback((int)HttpStatusCode.Gone, "短信发送失败,短信模板不存在!"); return; } //替换模板内容 var siteConfig = new BLL.siteconfig().loadConfig(); var msgContent = smsModel.content.Replace("{webtel}", siteConfig.webtel).Replace("{code}", newTradePwd); try { //发送短信 var tipMsg = string.Empty; bool result = false; /*if (Utils.IsDebugging()) * { * Debug.WriteLine("向手机 {0} 发送短信:{1}", mobile, msgContent); * result = true; * } * else*/ result = SMSHelper.SendSmsCode(mobile, msgContent, out tipMsg); if (result) { callback((int)HttpStatusCode.OK, "短信发送成功,请查收!"); } else { callback((int)HttpStatusCode.InternalServerError, tipMsg); } } catch { callback((int)HttpStatusCode.InternalServerError, "短信发送失败,请联系本站管理员!"); } }
private void SendMessage(SmsRequest request) { var toPhone = "0000000000"; //example of sending an sms message directly (not as a response to a webhook, as above) var success = SMSHelper.SendSmsMessage(new List <string> { toPhone }, request.Body + "\nFrom: " + request.From); }
private void btnAddData_Click(object sender, EventArgs e) { bool checkvalidate = validation(); string performDate = DateTime.Now.ToString("yyyy-MM-dd"); if (checkvalidate == false) { return; } DailyAnnaDanamModel dailyAnna = new DailyAnnaDanamModel { Name = txtName.Text, PhoneNumber = txtPhoneNumber.Text, Gothram = txtGothram.Text, VillageName = txtVillageName.Text, DonatedDate = performDate }; TokenPrint oTokenPrint = new TokenPrint { Name = txtName.Text, PhoneNumber = txtPhoneNumber.Text, Gothram = txtGothram.Text, VillageName = txtVillageName.Text, DonatedDate = performDate, ServiceType = "Nithya Annadanam" }; lstTokenPrint.Add(oTokenPrint); var checkIfExists = gothramRepo.checkIfGothramExists(txtGothram.Text); //If Gothra doesn't exist and if user has entered a Gothram if (checkIfExists == null && txtGothram.Text != string.Empty) { string insrtGothra = gothramRepo.insertNewGothraName(txtGothram.Text); } string strInsertStatus = dailyAnnaRepo.insertDonorInformation(dailyAnna); var bindServiceType = serviceTypeRepo.GetAllAsQuerable(10); List <int> serviceTypeValue = bindServiceType.Select(p => p.Cost).ToList(); string smsMessage = "Thanks " + dailyAnna.Name + " we have recieved an amount of Rs." + serviceTypeValue[0] + "/- towards Daily Annadanam"; if (strInsertStatus == "Success") { MessageBox.Show("Data inserted successfully."); oPrintHelper.PrintTokens(lstTokenPrint, this, _PrinterName, _ShowPrintPreview); CleareAllcontrolsRecursive(); loadGothramAutoComplete(); SMSHelper smsHelp = new SMSHelper(); smsHelp.sendSMS("91" + dailyAnna.PhoneNumber, smsMessage); //this.Close(); } }
/// <summary> /// HandleSecureDemand /// </summary> /// <param name="demand"></param> private static void HandleSecureDemand(Demands demand) { string message = $"User.FirstName & User.LastName Catégorie: Demand.DemandType User." + $"Ville Voici le lien afin de confirmer votre participation LINK Merci de participer au soutien collectif via Ping-Flood"; string phoneNumber = demand.SeekerUsers.Phone; SMSHelper.SendSMS(phoneNumber, $"+1{message}"); }
public HttpResponseMessage couponOwn(int id) { if (_workContext.CurrentUser == null) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "请先登录优客惠"))); } var couponCategory = _couponCategoryService.GetCouponCategoryById(id); //检测是否已经抢过 var sech = new CouponOwnerSearchCondition { userId = _workContext.CurrentUser.Id }; var list = _couponOwnerService.GetCouponOwnByCondition(sech).Select(p => p.CouponId).ToArray(); if (list.Any()) { var sech2 = new CouponSearchCondition { CouponCategoryId = id, IdArray = list }; var count = _couponService.GetCouponCount(sech2); if (count != 0) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "您已经抢过这家的优惠券了"))); } } var condition = new CouponSearchCondition { CouponCategoryId = id, Status = 0 }; var coupon = _couponService.GetCouponByCondition(condition).FirstOrDefault(); _couponOwnerService.CreateRecord(_workContext.CurrentUser.Id, coupon.Id); coupon.Status = EnumCouponStatus.Owned; _couponService.Update(coupon); couponCategory.Count = couponCategory.Count - 1; _couponCategoryService.UpdateCouponCategory(couponCategory); var brand = _productBrandService.GetProductBrandById(couponCategory.BrandId); var CouponOwn = new CouponCategoryModel { Name = couponCategory.Name, Number = coupon.Number, BrandName = brand.Bname }; var model = _brokerService.GetBrokerByUserId(_workContext.CurrentUser.Id); //短信发送 SMSHelper.Sending(model.Phone, "优惠券为:" + brand.Bname + ",券号为:" + coupon.Number + " 【优客惠】"); return(PageHelper.toJson(CouponOwn)); }
public ActionResult SendCode(string id) { string strMsg = string.Empty; if (SMSHelper.SendCode(id, out strMsg)) { return(Success()); } return(Faild(strMsg)); }
/// <summary> /// 发送短信(短信类型) /// </summary> /// <param name="smstype">短信类型(修改密码=1,找回密码=2,添加银行卡=3,佣金提现=4,)</param> /// <returns>发送短信结果状态信息</returns> public HttpResponseMessage SendSmsForbroker([FromBody] string smstype) { var user = (UserBase)_workContext.CurrentUser; if (user != null) { var broker = _brokerService.GetBrokerByUserId(user.Id); //获取当前经纪人 if (broker == null) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "获取用户失败,请检查是否登陆"))); } var messageConfigName = Enum.GetName(typeof(MessageConfigTypeEnum), Convert.ToInt32(smstype)); //获取短信模版名称 var messageTemplate = _messageConfigService.GetMessageConfigByName(messageConfigName).Template; //获取到的短信模版 string messages; if (messageConfigName == "推荐经纪人") //不需要生成数字验证码 { messages = string.Format(messageTemplate, ""); //更改模版 //添加到短信表中去 AddMessageDetails(new MessageDetailEntity { Content = messages, Mobile = broker.Phone, Sender = broker.Phone, Title = messageConfigName, Addtime = DateTime.Now }); return(PageHelper.toJson(SMSHelper.Sending(broker.Phone, messages))); } var strNumber = new Random().Next(100000, 1000000).ToString(); //生成大于等于100000,小于等于999999的随机数,也就是六位随机数 var nowTimestr = DateTime.Now.ToLongTimeString(); var strs = EncrypHelper.Encrypt(strNumber + "$" + nowTimestr, "Hos2xNLrgfaYFY2MKuFf3g=="); //EMS 加密短信验证码 messages = string.Format(messageTemplate, strNumber); //更改模版 //添加到短信表中去 AddMessageDetails(new MessageDetailEntity { Content = messages, Mobile = broker.Phone, Sender = broker.Phone, Title = messageConfigName, Addtime = DateTime.Now }); //返回到前台的加密内容 和短信发送返回值 return(PageHelper.toJson(new { Desstr = strs, Message = SMSHelper.Sending(broker.Phone, messages) })); } return(PageHelper.toJson(PageHelper.ReturnValue(false, "获取用户失败,请检查是否登陆"))); }
public MethodResult sendSMSGeneric(string countryCode, string mobileNumber, int messageType, string otp, string hostname, string eventName) { try { return(SMSHelper.sendSMSGeneric(countryCode, mobileNumber, messageType, otp, hostname, eventName)); } catch (Exception) { throw; } }
public async Task <dynamic> SendSMS(string checkcode, string phonenumber) { try { if (checkcode.IsNullOrEmpty() || phonenumber.IsNullOrEmpty()) { return(new { result = -1, message = "内部错误" }); } if (HttpContext.Session.TryGetValue("checkcode", out var value) && value.ConvertFromBytes(Encoding.ASCII) == checkcode.ToLower()) { var users = context.UserInfo.Where(x => (x.MobilephoneNumber == phonenumber)); if (users.Count() == 0) { return(new { result = -3, message = "不存在该用户" }); } var user = users.First(); var userid = user.UserID; HttpContext.Session.Remove("checkcode"); if (user.SendSMSDate.Date != DateTime.Now.Date) { user.SendSMSTimes = 0; } if (user.SendSMSTimes >= 3) { return(new { result = -4, message = "你今天发送的短信过多,请明天再试" }); } user.SendSMSDate = DateTime.Now; user.SendSMSTimes++; context.SaveChanges(); var code = await SMSHelper.SendCheckCode(phonenumber); if (code != 0) { var currenttime = DateTime.Now.Ticks; var data = new byte[] { (byte)(code >> 8), (byte)code, (byte)(currenttime >> 56), (byte)(currenttime >> 48), (byte)(currenttime >> 40), (byte)(currenttime >> 32), (byte)(currenttime >> 24), (byte)(currenttime >> 16), (byte)(currenttime >> 8), (byte)currenttime, (byte)(userid >> 24), (byte)(userid >> 16), (byte)(userid >> 8), (byte)(userid) }; HttpContext.Session.Set("smscode", data); return(new { result = 1 }); } else { return(new { result = -5, message = "发送短信失败" }); } } else { return(new { result = -2, message = "验证码错误" }); } } catch { return(new { result = -1, message = "内部错误" }); } }
/// <summary> /// 获取手机验证码 /// </summary> public void GetSMSCode() { using (ProxyBE p = new ProxyBE()) { try { string phone = Request["phone"]; if (string.IsNullOrEmpty(phone)) { throw new Exception("手机号不能为空"); } Partner partnerModel = p.Client.GetPartnerByMobile(SenderUser, phone); if (partnerModel != null) { throw new Exception("该手机号码已经被注册"); } string smsCode = SMSHelper.GetRandom(6); bool isComplete = false; //短信验证码限制:小于等于 1天/5次 5条/小时 累计10条/天 string message = SMSHelper.SendMessage(phone, smsCode, out isComplete); if (isComplete) { // 将手机验证码存入session SetCacheSMSCode(smsCode); //记录手机注册短信到数据库表 SMSLog smsLog = new SMSLog() { ID = Guid.NewGuid(), Phone = phone, Message = smsCode, Created = DateTime.Now, Status = true }; SaveSMSLogArgs args = new SaveSMSLogArgs(); args.SMSLog = smsLog; p.Client.SaveSMSLog(SenderUser, args); //短信日志 WriteSuccess(); } else { throw new Exception("发送失败," + message); } } catch (Exception ex) { WriteError(ex.Message, ex); } } }
/// <summary> /// 放款 /// </summary> /// <param name="projectId"></param> private static void HandleProjectInvestCompletedMsg(int projectId) { //找出所有投资记录,计算收益(收益以还款记录为准,投资记录收益作为账单参考) var context = new Agp2pDataContext(); var project = context.li_projects.SingleOrDefault(p => p.id == projectId); Debug.Assert(project != null, "project != null"); //查询所有投资记录 var investTrans = project.li_project_transactions.Where( t => t.type == (int)Agp2pEnums.ProjectTransactionTypeEnum.Invest && t.status == (int)Agp2pEnums.ProjectTransactionStatusEnum.Success).ToList(); var finalProfitRate = project.GetFinalProfitRate(DateTime.Now); investTrans.ForEach(pt => { pt.interest = pt.principal * finalProfitRate; }); context.SubmitChanges(); //满标则发满标通知,否则发截标通知 var dtSmsTemplate = project.financing_amount == project.investment_amount ? context.dt_sms_template.FirstOrDefault(t => t.call_index == "project_financing_success") : context.dt_sms_template.FirstOrDefault(t => t.call_index == "project_financing_success_cut"); if (dtSmsTemplate == null) { return; } //发送通知给每个投资者 investTrans.Select(ptr => ptr.dt_users).Distinct().ForEach(user => { var msgContent = dtSmsTemplate.content.Replace("{date}", DateTime.Now.ToString("yyyy年MM月dd日")) .Replace("{project}", project.title); try { string errorMsg; if (!SMSHelper.SendTemplateSms(user.mobile, msgContent, out errorMsg)) { context.AppendAdminLogAndSave("WithdrawSms", "发送放款/截标通知失败:" + errorMsg + "(客户ID:" + user.user_name + ")"); } } catch (Exception ex) { context.AppendAdminLogAndSave("WithdrawSms", "发送放款/截标通知失败:" + ex.GetSimpleCrashInfo() + "(客户ID:" + user.user_name + ")"); } }); }
public void SendVerifyMessage(int cid) { var customerInfo = _customerDal.Find <CustomerInfoEntity>(cid); var mobile = customerInfo.Mobile; Random rd = new Random(); var r = rd.Next(1000, 9999).ToString(); string msg = "验证码:" + r + " 有效期10分钟,请输入验证码完成重新绑定手机。"; string sendType = "手工";//"手机验证码发送"; RedisManager.Set(r.ToString(), CacheKeyEnum.CustomerMobileVerifyCode + mobile, new TimeSpan(0, 15, 0)); SMSHelper.SMSSendMessage(mobile, msg, sendType); }