Exemplo n.º 1
0
        public Message AddMessage(string apiKey, string senderUri, string recipientUri, string senderAccountId, double amount, string comments, string messageType,
                                  string securityPin, double latitude, double longitude, string recipientFirstName, string recipientLastName, string recipientImageUri)
        {
            User sender = null;

            URIType recipientUriType = GetURIType(recipientUri);
            URIType senderUriType    = GetURIType(senderUri);

            if (recipientUriType == URIType.MobileNumber)
            {
                recipientUri = _formattingServices.RemoveFormattingFromMobileNumber(recipientUri);
            }

            if (senderUriType == URIType.MobileNumber)
            {
                senderUri = _formattingServices.RemoveFormattingFromMobileNumber(senderUri);
            }

            if (!(messageType.ToUpper() == "PAYMENT" || messageType.ToUpper() == "PAYMENTREQUEST"))
            {
                throw new ArgumentException(String.Format("Invalid Message Type.  Message Type must be Payment or PaymentRequest"));
            }

            MessageType type = MessageType.Payment;

            if (messageType.ToUpper() == "PAYMENT")
            {
                type = MessageType.Payment;
            }

            if (messageType.ToUpper() == "PAYMENTREQUEST")
            {
                type = MessageType.PaymentRequest;
            }

            try
            {
                sender = _userServices.GetUser(senderUri);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Debug, String.Format("Exception getting Sender {0}. {1}", senderUri, ex.Message));

                throw new ArgumentException(String.Format("Sender {0} Not Found", senderUri));
            }

            if (sender == null)
            {
                var message = String.Format("Unable to find sender {0}", senderUri);
                _logger.Log(LogLevel.Debug, message);

                throw new Exception(message);
            }

            if (!sender.SetupSecurityPin || !(sender.SecurityPin.Equals(_securityServices.Encrypt(securityPin))))
            {
                var message = String.Format("Invalid Security Pin");
                _logger.Log(LogLevel.Info, message);
                _logger.Log(LogLevel.Info, String.Format("{0} - {1}", sender.SecurityPin, _securityServices.Encrypt(securityPin)));

                throw new Exception(message);
            }

            if (recipientUriType == URIType.MobileNumber && _validationService.AreMobileNumbersEqual(sender.MobileNumber, recipientUri))
            {
                var message = String.Format("Sender and Recipient are the same");
                _logger.Log(LogLevel.Debug, message);

                throw new InvalidOperationException(message);
            }

            PaymentAccount senderAccount = null;

            try
            {
                senderAccount = GetAccount(sender, senderAccountId);
            }
            catch (Exception ex)
            {
                var message = String.Format("Exception getting Sender Account {0}. {1}", senderAccountId, ex.Message);

                _logger.Log(LogLevel.Debug, message);

                throw new Exception(message);
            }

            if (senderAccount == null)
            {
                var message = String.Format("The senderAccountId is invalid.");
                _logger.Log(LogLevel.Debug, message);

                throw new ArgumentException(message);
            }

            //TODO: validate application in request
            Application application = null;

            try
            {
                application = _applicationServices.GetApplication(apiKey);;
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Debug, String.Format("Exception getting application {0}. {1}", apiKey, ex.Message));

                throw ex;
            }

            if (application == null)
            {
                var message = String.Format("Application {0} was not found.", apiKey);

                _logger.Log(LogLevel.Debug, String.Format("Exception getting application {0}. {1}", apiKey, message));

                throw new InvalidOperationException(message);
            }

            Domain.User recipient = null;
            if (recipientUriType == URIType.MECode)
            {
                var meCode = _context.MECodes
                             .FirstOrDefault(m => m.MeCode.Equals(recipientUri));

                if (meCode == null)
                {
                    throw new ArgumentException("MECode not found.");
                }

                recipient = meCode.User;
            }

            if (recipientUriType == URIType.EmailAddress)
            {
                recipient = _userServices.FindUserByEmailAddress(recipientUri);
            }
            if (recipientUriType == URIType.MobileNumber)
            {
                recipient = _userServices.FindUserByMobileNumber(recipientUri);
            }
            if (recipientUriType == URIType.FacebookAccount)
            {
                recipient = _userServices.GetUser(recipientUri);
            }
            //TODO: confirm recipient is valid???

            //TODO: confirm amount is within payment limits

            //TODO: try to add message
            Domain.Message messageItem;

            _logger.Log(LogLevel.Info, "Adding Message");

            if (sender == null || senderAccount == null)
            {
                _logger.Log(LogLevel.Info, "Sender or Sender Account Not Set");
                throw new Exception("Sender or Sender Account Not Set");
            }

            try
            {
                MessageStatus messageStatus = MessageStatus.Submitted;

                messageItem = _context.Messages.Add(new Message()
                {
                    Amount             = amount,
                    Application        = application,
                    ApiKey             = application.ApiKey,
                    Comments           = comments,
                    CreateDate         = System.DateTime.Now,
                    Id                 = Guid.NewGuid(),
                    MessageStatus      = MessageStatus.Pending,
                    MessageStatusValue = (int)messageStatus,
                    MessageType        = type,
                    MessageTypeValue   = (int)type,
                    RecipientUri       = recipientUri,
                    SenderUri          = senderUri,
                    Sender             = sender,
                    SenderId           = sender.UserId,
                    SenderAccount      = senderAccount,
                    SenderAccountId    = senderAccount.Id,
                    Latitude           = latitude,
                    Longitude          = longitude,
                    recipientFirstName = (recipient != null && !String.IsNullOrEmpty(recipient.FirstName) ? recipient.FirstName : recipientFirstName),
                    recipientLastName  = (recipient != null && !String.IsNullOrEmpty(recipient.LastName) ? recipient.LastName : recipientLastName),
                    recipientImageUri  = recipientImageUri
                });

                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                var message = String.Format("Exception adding message. {0}", ex.Message);

                throw new Exception(message);
            }

            return(messageItem);
        }
Exemplo n.º 2
0
        public void SendSMS(Guid apiKey, string mobileNumber, string message)
        {
            if (apiKey == null || String.IsNullOrEmpty(mobileNumber) || String.IsNullOrEmpty(message))
            {
                throw new ArgumentNullException(String.Format("You must specify an APIKey, mobile number and Message to send an SMS"));
            }

            var application = _applicationService.GetApplication(apiKey.ToString());

            //Log Request
            var smsLog = _smsLogService.AddSMSLog(apiKey, mobileNumber, message, Domain.SMSStatus.Pending, null);

            // SMSified API endpoint.
            string webTarget = "https://api.smsified.com/v1/smsmessaging/outbound/{0}/requests";

            // Parameters to send with API request.
            string webPost = "address={0}&message={1}";

            // SMSified credentials.
            string userName     = "******";
            string password     = "******";
            string senderNumber = "2892100266";

            //format to number
            string toMobileNumber = _formattingServices.RemoveFormattingFromMobileNumber(mobileNumber);

            //var aliases = _ctx.MobileDeviceAliases
            //    .FirstOrDefault(m => m.MobileNumber == mobileNumber);

            //if (aliases != null)
            //{
            //    _logger.Log(LogLevel.Info, String.Format("Alias found for {0}", mobileNumber));
            //    toMobileNumber = String.Format("{0}{1}", "1", aliases.MobileNumberAlias.Replace(@"-", @""));
            //}

            _logger.Log(LogLevel.Info, String.Format("Sending SMS Message to {0}", toMobileNumber));

            // Create new HTTP request.
            string         url = String.Format(webTarget, senderNumber);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] postData = Encoding.ASCII.GetBytes(String.Format(webPost, toMobileNumber, message));
            req.ContentLength = postData.Length;

            // Set HTTP authorization header.
            string authInfo = userName + ":" + password;

            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            req.Headers["Authorization"] = "Basic " + authInfo;

            // Send HTTP request.
            Stream PostStream = req.GetRequestStream();

            PostStream.Write(postData, 0, postData.Length);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            // Evaluate result of HTTP request.
            if (res.StatusCode == HttpStatusCode.Created)
            {
                smsLog.SMSStatus = Domain.SMSStatus.Sent;
                smsLog.SentDate  = System.DateTime.Now;

                _smsLogService.UpdateSMSLog(smsLog);
            }
            else
            {
                smsLog.SMSStatus = Domain.SMSStatus.Failed;

                _smsLogService.UpdateSMSLog(smsLog);
            }
        }