Beispiel #1
0
        public SmsContent SendCode(string phone, IBntWebModule module = null, string type = null)
        {
            var code = "0000";

            if (!Debug)
            {
                Random rad   = new Random();
                int    value = rad.Next(1000, 10000);
                code = value.ToString();
            }

            var message    = $"您的短信验证码是:{code}";
            var smsContent = SmsContent.Create(phone, message);

            if (module != null)
            {
                smsContent.Module = module;
            }
            if (type != null)
            {
                smsContent.InnerType = type;
            }

            smsContent.KeyValues.Add("Code", code);

            return(Send(smsContent));
        }
Beispiel #2
0
        public void ExtractVariables()
        {
            if (!string.IsNullOrWhiteSpace(EmailContent))
            {
                var startIndexes = EmailContent.IndexesOf("{");
                var endIndexes   = EmailContent.IndexesOf("}");

                GetTemplateVariableNames(startIndexes, endIndexes, EmailContent);
            }

            if (!string.IsNullOrWhiteSpace(SmsContent))
            {
                var startIndexes = SmsContent.IndexesOf("{");
                var endIndexes   = SmsContent.IndexesOf("}");

                GetTemplateVariableNames(startIndexes, endIndexes, SmsContent);
            }
        }
        public async Task <IActionResult> SmsAll([FromRoute] int eventInfoId, [FromBody] SmsContent sms)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var recipients    = "";
            var errors        = "";
            var registrations = await _registrationService.GetRegistrations(eventInfoId);

            foreach (var reg in registrations)
            {
                try
                {
                    await _smsSender.SendSmsAsync(reg.User.PhoneNumber, sms.Content);

                    recipients += $@"""{reg.User.Name}"" <{reg.User.PhoneNumber}>; ";
                }
                catch (Exception exc)
                {
                    errors += exc.Message + Environment.NewLine;
                }
            }

            var result = "";

            if (errors == "")
            {
                result = "Alle SMS sendt!";
            }
            else
            {
                result = "Sendte SMS. Men fikk noen feil: " + Environment.NewLine + errors;
            }

            await _messageLog.AddAsync(eventInfoId, recipients, sms.Content, "SMS", "Twilio", result);

            return(Ok(result.Replace(Environment.NewLine, "<br />")));
        }
Beispiel #4
0
        public static SmsContent GetSmsTemplateWithValues(DeviceAlarmType deviceAlarmType, object Model)
        {
            SmsContent sc = new SmsContent();

            try
            {
                string FileNameToRead = string.Empty;

                string AlarmTypeStr = deviceAlarmType.ToString();

                string fileContent = string.Empty;

                if (!SmsSubjectTemplate.ContainsKey(AlarmTypeStr))
                {
                    fileContent = string.Empty;
                    fileContent = System.IO.File.ReadAllText(@"Templates\Sms\" + AlarmTypeStr + @"Subject.txt");
                    SmsSubjectTemplate.Add(AlarmTypeStr, fileContent);
                }

                if (!SmsPlainTemplate.ContainsKey(AlarmTypeStr))
                {
                    fileContent = string.Empty;
                    fileContent = System.IO.File.ReadAllText(@"Templates\Sms\" + AlarmTypeStr + @"Plain.txt");
                    SmsPlainTemplate.Add(AlarmTypeStr, fileContent);
                }

                sc.Subject   = SmsSubjectTemplate[AlarmTypeStr];
                sc.PlainText = SmsPlainTemplate[AlarmTypeStr];

                sc.Subject   = Engine.Razor.RunCompile(sc.Subject, AlarmTypeStr + "SmsSubject", null, Model);
                sc.PlainText = Engine.Razor.RunCompile(sc.PlainText, AlarmTypeStr + "SmsPlain", null, Model);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(sc);
        }
        public IActionResult InfoSendSms([FromBody] SmsInfoBookingInputViewModel infoInput)
        {
            int YearNow  = DateTime.Now.Year;
            int MonthNow = DateTime.Now.Month;
            //danh sach goi sms su dung
            var packages = _context.Query <SmsPackagesDistribute>()
                           .Where(pd => pd.HealthFacilitiesId == infoInput.healthFacilitiesId &&
                                  ((pd.YearStart < YearNow && pd.YearEnd == YearNow && pd.MonthEnd <= MonthNow) ||
                                   (pd.YearStart <YearNow && pd.YearEnd> YearNow) ||
                                   (pd.YearStart == YearNow && pd.YearEnd == YearNow && pd.MonthEnd >= MonthNow && pd.MonthStart <= MonthNow) ||
                                   (pd.YearStart == YearNow && pd.YearEnd > YearNow && pd.MonthStart <= MonthNow)) &&
                                  pd.IsDelete == false && pd.IsActive == true)
                           .Select(u => new PackageDistributeViewModel(u, _connectionString)).ToList();

            if (packages.Count == 0)
            {
                SaveInfoSmsBookingError(_connectionString, infoInput, "Không thể gửi tin do không sử dụng gói sms nào");
                if (infoInput.type == 4)
                {
                    return(Json(new ActionResultDto {
                        Result = ""
                    }));
                }
                else
                {
                    return(StatusCode(406, _excep.Throw(406, "Không thể gửi tin do số lượng tin nhắn vượt quá gói SMS hiện tại. Mời bạn mua thêm gói SMS")));
                }
            }

            long totalSms     = 0;
            int  totalSmsSend = infoInput.lstMedicalHealthcareHistories.Count;

            foreach (var s in packages)
            {
                totalSms += s.SmsPackageUsed != null ? s.SmsPackageUsed.Quantityused : 0;
            }

            if (totalSms < totalSmsSend)
            {
                SaveInfoSmsBookingError(_connectionString, infoInput, "Không thể gửi tin do số lượng tin nhắn vượt quá gói SMS hiện tại");
                if (infoInput.type == 4)
                {
                    return(Json(new ActionResultDto {
                        Result = ""
                    }));
                }
                else
                {
                    return(StatusCode(406, _excep.Throw(406, "Không thể gửi tin do số lượng tin nhắn vượt quá gói SMS hiện tại. Mời bạn mua thêm gói SMS")));
                }
            }

            //Xu ly tin nhan
            string code         = "";
            string content      = "";
            int    templateId   = 0;
            string templateCode = "";
            int    indexM       = 0;
            int    indexUsed    = 0;

            switch (infoInput.type)
            {
            case 1:
                code = "A01.SMSTAIKHAM";
                break;

            case 2:
                code = "A02.SMSSINHNHAT";
                break;

            case 4:
                code = "A06.SMSDATKHAM";
                break;
            }

            if (string.IsNullOrEmpty(infoInput.content))
            {
                var config = _context.Query <HealthFacilitiesConfigs>().Where(hp => hp.Code == code).FirstOrDefault();
                //templateId = config != null ? config.Values : 0;
                templateCode = config != null ? config.Values : "";
                //var template = _context.Query<SmsTemplate>().Where(t => t.Id == templateId).FirstOrDefault();
                var template = _context.Query <SmsTemplate>().Where(t => t.SmsTemplateCode == templateCode).FirstOrDefault();
                content = template != null ? template.SmsContent : "";
            }
            else
            {
                //templateId = infoInput.smsTemplateId.Value;
                templateCode = infoInput.SmsTemplateCode;
                content      = infoInput.content;
            }
            //danh sach sms content
            List <SmsContent> lstContent = new List <SmsContent>();

            foreach (var m in infoInput.lstMedicalHealthcareHistories)
            {
                indexM++;
                if (packages[indexUsed].SmsPackageUsed != null && indexM > packages[indexUsed].SmsPackageUsed.Quantityused)
                {
                    indexM = 0;
                    indexUsed++;
                }

                SmsContent scontent = new SmsContent();
                scontent.SmsBrand    = packages[indexUsed].SmsBrand;
                scontent.Message     = ReplaceContentBookingSms(content, m, packages[indexUsed].PackageName);
                scontent.PhoneNumber = m.PhoneNumber;

                scontent.HealthFacilitiesId      = infoInput.healthFacilitiesId.Value;
                scontent.SmsTemplateId           = templateId;
                scontent.SmsTemplateCode         = templateCode;
                scontent.SmsPackagesDistributeId = packages[indexUsed].Id;
                scontent.SmsPackageUsedId        = packages[indexUsed].SmsPackageUsed != null ? packages[indexUsed].SmsPackageUsed.SmsPackageUsedId : 0;
                scontent.PatientHistoriesId      = 0;

                scontent.PatientId  = m.PatientId;
                scontent.objectType = infoInput.objectType;

                lstContent.Add(scontent);
            }

            var sendSMS = Utils.SendListSMS(lstContent, infoInput.type);
            var infoSms = SMS.SaveInfoSMS(_connectionString, sendSMS, infoInput.type);

            return(Json(new ActionResultDto {
                Result = infoSms
            }));
        }
Beispiel #6
0
        public void Invalid(string phone, IBntWebModule module = null, string type = null)
        {
            var key = SmsContent.GetKey(phone, module, type);

            Invalid(key);
        }
Beispiel #7
0
        public SmsContent Send(SmsContent smsContent)
        {
            Resend : var sms = _cacheManager.Get(smsContent.Key, ctx =>
            {
                ctx.Monitor(_clock.When(TimeSpan.FromMinutes(EffectiveTime)));
                ctx.Monitor(_signals.When($"{ctx.Key}-changed"));

                try
                {
                    var smsLog = new SmsLog
                    {
                        Id         = KeyGenerator.GetGuidKey(),
                        ModuleKey  = smsContent.Module.InnerKey,
                        ModuleName = smsContent.Module.InnerDisplayName,
                        Message    = smsContent.Message,
                        Phone      = smsContent.Phone,
                        UserId     = smsContent.SendToUser?.Id,
                        UserName   = smsContent.SendToUser?.UserName,
                        CreateTime = DateTime.Now
                    };

                    smsContent.SendTime = DateTime.Now;
                    if (!Debug)
                    {
                        Logger.Warning("开始发送短信");
                        //发送到短信接口
                        //var url =
                        // $"{HostUrl}/HttpSendSM?account={Account}&pswd={Password}&mobile={smsContent.Phone}&msg={smsContent.Message}&needstatus=true";
                        var sign    = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("10010312" + "sef78f42cv1c124s8z2s", "MD5").ToLower();
                        var content = HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(smsContent.Message)));
                        var url     = $"http://ysms.game2palm.com:8899/smsAccept/sendSms.action?sid=710312&mobi={smsContent.Phone}&sign={sign}&msg={content}";
                        Logger.Warning("短信链接" + url);
                        Uri uri            = new Uri(url);
                        WebRequest webreq  = WebRequest.Create(uri);
                        webreq.Method      = "post";
                        webreq.ContentType = "application/x-www-form-urlencoded";
                        Stream stream      = webreq.GetResponse().GetResponseStream();

                        Logger.Warning("短信结果:" + stream);
                        if (stream != null)
                        {
                            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
                            string returnString       = streamReader.ReadToEnd();
                            var returnCode            = returnString.Split('|')[0];

                            if (returnCode == "1000")
                            {
                                _currencyService.Create(smsLog);
                            }
                            else
                            {
                                throw new Exception($"短信发送失败,错误码:{returnCode}");
                            }
                        }
                        else
                        {
                            throw new Exception("短信发送失败,获取接口返回数据失败");
                        }
                    }
                    else
                    {
                        _currencyService.Create(smsLog);
                    }

                    smsContent.SendStatus = SmsSendStatus.Success;
                }
                catch (Exception ex)
                {
                    smsContent.ErrorMessage = ex.Message;

                    Logger.Error(ex, $"发送手机短信出错,手机号{smsContent.Phone},内容{smsContent.Message}");
                }

                if (smsContent.SendStatus == SmsSendStatus.Failed)
                {
                    //短信发送失败了,更新缓存
                    _signals.Trigger($"{ctx.Key}-changed");
                }

                return(smsContent);
            });

            if (sms.SendTime.AddMinutes(Interval) < DateTime.Now)
            {
                _signals.Trigger($"{sms.Key}-changed");
                goto Resend;
            }

            return(sms);
        }
Beispiel #8
0
        public bool VerifyCode(string phone, string code, IBntWebModule module = null, string type = null, bool invalid = true)
        {
            var key = SmsContent.GetKey(phone, module, type);

            return(VerifyCodeWithKey(key, code, invalid));
        }