Пример #1
0
        private static async Task <string> SendSingleTextualSmsAsync(List <string> to)
        {
            Console.WriteLine("-------------------------------");
            Console.WriteLine("Sending single textual message...");

            SendSingleTextualSms smsClient = new SendSingleTextualSms(BASIC_AUTH_CONFIGURATION);
            SMSTextualRequest    request   = new SMSTextualRequest
            {
                From = FROM,
                To   = to,
                Text = MESSAGE_TEXT
            };
            SMSResponse smsResponse = await smsClient.ExecuteAsync(request);

            Console.WriteLine("Sending single textual message complete.");

            SMSResponseDetails sentMessageInfo = smsResponse.Messages[0];

            Console.WriteLine("-------------------------------");
            Console.WriteLine("Message ID: " + sentMessageInfo.MessageId);
            Console.WriteLine("Receiver: " + sentMessageInfo.To);
            Console.WriteLine("Message status: " + sentMessageInfo.Status.Name);
            Console.WriteLine("-------------------------------");

            return(sentMessageInfo.MessageId);
        }
Пример #2
0
        public async Task <SMSResponse> ExecuteAsync(SMSTextualRequest bodyObject)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                string endpoint = path;

                string      requestJson = JsonConvert.SerializeObject(bodyObject, Settings);
                HttpContent content     = new StringContent(requestJson, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(endpoint, content);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <SMSResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Пример #3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            //if (model.Aviso == false)
            //{
            //    ViewBag.showSuccessAlert = true;
            //    ModelState.AddModelError("", "¡Oops! Aun no has aceptado el aviso de privacidad.");
            //}

            if (string.IsNullOrWhiteSpace(model.Email) && string.IsNullOrWhiteSpace(model.PhoneNumber) || string.IsNullOrEmpty(model.Password) && string.IsNullOrEmpty(model.ConfirmPassword))
            {
                ModelState.AddModelError("", "¡Oops! Aun te queda información por capturar. Inténtalo de nuevo");
            }
            else
            {
                // Validamos estructura del password ingresado.
                var mayus  = model.Password.Any(c => char.IsUpper(c));
                var min    = model.Password.Any(c => char.IsLower(c));
                var num    = model.Password.Any(c => char.IsDigit(c));
                var symbol = model.Password.Any(c => char.IsLetterOrDigit(c));
                if (mayus == false || min == false || num == false || symbol == false)
                {
                    ModelState.AddModelError("", "¡Oops! la contraseña no cumple con los requisitos: Necesitas una minúscula, una mayúscula y un número. Inténtalo de nuevo.");
                }



                if (ModelState.IsValid)
                {
                    //var Correo = from[""];
                    //var correo = Convert.ToInt32(model.Email);


                    if (string.IsNullOrWhiteSpace(model.Email))  // Válidación de usuario por # de telefono.
                    {
                        String NumberPhone = model.PhoneNumber.Substring(0, 10);
                        String Voice       = model.PhoneNumber.Substring(10);
                        String ValidaVoz   = ConfigurationManager.AppSettings["ClaveVoz"];
                        Voice.ToLower();

                        var userphone = new ApplicationUser {
                            UserName = NumberPhone, PhoneNumber = NumberPhone
                        };
                        userphone.PhoneNumberConfirmed = true;
                        userphone.Email = userphone.PhoneNumber + "@p.com";

                        var resultphone = await UserManager.CreateAsync(userphone, model.Password);

                        if (resultphone.Succeeded)
                        {
                            // Generar el token y enviarlo

                            var code = await UserManager.GenerateChangePhoneNumberTokenAsync(userphone.Id, NumberPhone);

                            var phone = userphone.PhoneNumber.ToString();

                            List <string> Destino = new List <string>(1)
                            {
                                ConfigurationManager.AppSettings["Lada"] + phone
                            };

                            if (Voice == ValidaVoz)                      // Indicador de mensaje de voz al candidato.
                            {
                                string[] result = Regex.Split(code, ""); // Separamos los numeros del codigo obtenido para enviarlos al mensaje de voz.
                                string   Codigo = "";
                                for (int i = 0; i < result.Length; i++)
                                {
                                    if (i > 0 && i < 7)
                                    {
                                        Codigo = Codigo + result[i] + "    ";
                                    }
                                }

                                var client       = new RestClient("https://api.infobip.com/tts/3/single");
                                var requestvoice = new RestRequest(Method.POST);
                                requestvoice.AddHeader("accept", "application/json");
                                requestvoice.AddHeader("content-type", "application/json");
                                requestvoice.AddHeader("authorization", "Basic " + ConfigurationManager.AppSettings["InfobipToken"]);
                                requestvoice.AddParameter("application/json", "{\n  \"from\": \"523323053385\",\n  \"to\": \"" + ConfigurationManager.AppSettings["Lada"] + phone + "\",\n  \"text\": \"Tu código es:  " + Codigo + "      Tu código es:  " + Codigo + "\",\n  \"language\": \"" + ConfigurationManager.AppSettings["LanguajeCode"] + "\"\"speechRate\": 0.5,\n}", ParameterType.RequestBody);
                                IRestResponse response = client.Execute(requestvoice);
                            }
                            else
                            {
                                // Msj con SMS.

                                BasicAuthConfiguration BASIC_AUTH_CONFIGURATION = new BasicAuthConfiguration(ConfigurationManager.AppSettings["BaseUrl"], ConfigurationManager.AppSettings["UserInfobip"], ConfigurationManager.AppSettings["PassInfobip"]);

                                SendSingleTextualSms smsClient = new SendSingleTextualSms(BASIC_AUTH_CONFIGURATION);

                                SMSTextualRequest request = new SMSTextualRequest
                                {
                                    From = "Damsa",
                                    To   = Destino,
                                    Text = ConfigurationManager.AppSettings["NameAppMsj"] + " te envia tu código de verificacion: " + code
                                };

                                // Msj de voz.

                                SMSResponse smsResponse = await smsClient.ExecuteAsync(request); // Manda el mensaje con código.

                                SMSResponseDetails sentMessageInfo = smsResponse.Messages[0];
                            }

                            return(RedirectToAction("ConfirmPhone", "Account", new { PhoneNumber = NumberPhone, idtf = userphone.Id }));


                            //if (UserManager.SmsService != null)
                            //{
                            //    var message = new IdentityMessage
                            //    {
                            //        Destination = model.PhoneNumber,
                            //        Body = "Su código de seguridad es: " + code
                            //    };
                            //    await UserManager.SmsService.SendAsync(message);
                            //}

                            //return RedirectToAction("VerifyPhone", "Account");

                            //return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.PhoneNumber });
                            //return RedirectToAction("Confirm", "Account", new { Email = user.Email });
                            //return RedirectToAction("RegistrarNumero", "Account");
                        }
                    }
                    else  // Validación de usuario por e-mail.
                    {
                        var user = new ApplicationUser {
                            UserName = model.Email, Email = model.Email
                        };
                        user.Email       = model.Email;
                        user.PhoneNumber = model.PhoneNumber;

                        //user.EmailConfirmed = true;
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(
                                new System.Net.Mail.MailAddress("*****@*****.**", "DAMSA Registro"),
                                new System.Net.Mail.MailAddress(user.Email));
                            m.Subject = "Confirmación  Email";

                            //m.Body = string.Format("<BR/>Gracias por su registro, por favor haga clic en el siguiente enlace para completar su registro: <a href=\"{0}\" title=\"User Email Confirm\">{0}</a>", "http://sagainn.com.mx:" + puerto + "/DatosContacto/" + user.Id);
                            m.Body       = string.Format("Para {0}<BR/>Gracias por su registro, por favor haga clic en el siguiente enlace para completar su registro: <a href=\"{1}\" title=\"User Email Confirm\">{1}</a>", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.Email }, Request.Url.Scheme));
                            m.IsBodyHtml = true;
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["SmtpDamsa"], Convert.ToInt16(ConfigurationManager.AppSettings["SMTPPort"]));
                            smtp.EnableSsl   = true;
                            smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserDamsa"], ConfigurationManager.AppSettings["PassDamsa"]);
                            smtp.Send(m);
                            return(RedirectToAction("Confirm", "Account", new { Email = user.Email }));
                        }
                        else
                        {
                            AddErrors(result);
                        }
                    }
                }
            }
            // If we got this far, something failed, redisplay form
            //return RedirectToAction("VerifyPhoneNumber2", "Account");
            return(View(model));

            //return RedirectToAction("AddPhoneNumber", "Account");
        }