Exemplo n.º 1
0
        // Methods
        public PaymentResult SubmitPayment(Payment payment)
        {
            PaymentResult paymentResult = new PaymentResult();

            try
            {
                TransactionRequest request = new TransactionRequest
                {
                    Amount = payment.Amount,
                    CreditCard = new TransactionCreditCardRequest
                    {
                        Number = payment.CCNumber,
                        CVV = payment.CVV,
                        ExpirationMonth = payment.ExpirationMonth,
                        ExpirationYear = payment.ExpirationYear
                    },
                    Options = new TransactionOptionsRequest
                    {
                        SubmitForSettlement = true
                    }
                };

                Result<Transaction> result = authentication.GetGateway().Transaction.Sale(request);

                if (result.IsSuccess())
                {
                    Transaction transaction = result.Target;
                    paymentResult.IsSuccess = true;
                    paymentResult.TransactionId = transaction.Id;
                }
                else if (result.Transaction != null)
                {
                    paymentResult.IsSuccess = false;
                    paymentResult.PaymentError = new PaymentError();

                    paymentResult.PaymentError.ErrorType = PaymentErrorTypeEnum.ProcessingError;
                    paymentResult.PaymentError.ErrorMessage = "Message: " + result.Message;
                    Transaction transaction = result.Transaction;
                    paymentResult.TransactionId = transaction.Id;

                    paymentResult.PaymentError.ErrorMessage += "\n\nError processing transaction:" +
                        "\n  Status: " + transaction.Status +
                        "\n  Code: " + transaction.ProcessorResponseCode +
                        "\n  Text: " + transaction.ProcessorResponseText;
                }
                else
                {
                    paymentResult.IsSuccess = false;
                    paymentResult.PaymentError = new PaymentError();

                    paymentResult.PaymentError.ErrorType = PaymentErrorTypeEnum.NoTransaction;
                    paymentResult.PaymentError.ErrorMessage = "Message: " + result.Message;

                    foreach (ValidationError error in result.Errors.DeepAll())
                    {
                        paymentResult.PaymentError.ErrorMessage += "\n\nAttribute: " + error.Attribute +
                        "\n  Code: " + error.Code +
                        "\n  Message: " + error.Message;
                    }
                }
            }
            catch (Exception e)
            {
                paymentResult.IsSuccess = false;
                paymentResult.PaymentError = new PaymentError();

                paymentResult.PaymentError.ErrorType = PaymentErrorTypeEnum.ApplicationError;
                paymentResult.PaymentError.ErrorMessage = e.Message;
            }

            return paymentResult;
        }
Exemplo n.º 2
0
        public ActionResult CreateTransaction(FormCollection collection)
        {
            string resultMessage = "The transaction could not be processed.";

            // FormCollection is needed in order to use client-side encryption.
            if (collection.Count <= 1)
            {
                // Encryption failed / form not valid - go to failure page
                LogTransaction("Form fields not received.", false);
                return RedirectToResult(resultMessage, false);
            }

            var packageHolder = TempData["Package"];

            if (packageHolder == null)
            {
                // Go to failure page - card not charged
                LogTransaction("No package information received.", false);
                return RedirectToResult(resultMessage, false);
            }

            Order order;
            Payment payment;
            package = (Package)packageHolder;

            try
            {
                // Get ApplicationUser
                Result<ApplicationUser> userResult = userService.GetApplicationUserById(WebSecurity.CurrentUserId);

                if (userResult.Status != ResultEnum.Success)
                {
                    // Go to failure page - card not charged
                    LogTransaction("Unable to get user details.", false);
                    return RedirectToResult(resultMessage, false);
                }

                user = userResult.Data;

                // Create Order
                Result<Order> orderResult = orderService.AddOrder(new Order
                {
                    PackageId = package.PackageId,
                    Amount = package.Amount,
                    CustomerId = WebSecurity.CurrentUserId,
                    DateBooked = DateTime.Now,
                    Paid = false
                });

                if (orderResult.Status != ResultEnum.Success)
                {
                    // Go to failure page - card not charged
                    LogTransaction("Unable to get order details.", false);
                    return RedirectToResult(resultMessage, false);
                }

                order = orderResult.Data;
            }
            catch (Exception e)
            {
                // Go to failure page - card not charged
                LogTransaction(e.Message, false);
                return RedirectToResult(resultMessage, false);
            }

            // Submit Payment
            try
            {
                payment = new Payment
                {
                    CCNumber = collection["number"],
                    CVV = collection["cvv"],
                    ExpirationMonth = collection["month"],
                    ExpirationYear = collection["year"],
                    Amount = package.Amount,
                    PackageId = package.PackageId,
                    PackageName = package.Name
                };

                IPaymentService paymentService = UtilityFactory.GetBrainTreeService(Authentication.GetBrainTreeAuthentication());
                paymentResult = paymentService.SubmitPayment(payment);
                if (!paymentResult.IsSuccess)
                {
                    LogTransaction("Error submitting payment.", false);
                    return RedirectToResult(resultMessage, false);
                }
            }
            catch (Exception e)
            {
                LogTransaction(e.Message, false);
                return RedirectToResult(resultMessage, false);
            }

            // Payment Successful
            resultMessage = "Your transaction has been processed. Enjoy your holiday!";

            try
            {
                // Update Order
                order.Paid = true;
                order.TransactionId = paymentResult.TransactionId;

                ResultEnum result = orderService.UpdateOrder(order);

                if (result != ResultEnum.Success)
                {
                    // Payment succeeded, but database update failed.
                    LogTransaction("Failed to update database.", true);
                }
            }
            catch (Exception e)
            {
                // Payment succeeded, but database update failed.
                LogTransaction(e.Message, true);
                resultMessage = "Your transaction has been processed. Please contact us about your trip.";
            }

            try
            {
                // Send SMS
                string phoneNumber = PhoneValidation.ValidateMobileNumber(user.Phone);

                if (phoneNumber != null)
                {
                    string smsMessage = String.Format(
                        "Hi {0}, Congratulations on your successful order of our {1} package. Enjoy your trip!",
                        user.FirstName,
                        package.Name);

                    GrandeTravel.Utility.IPhoneService commClient =
                        UtilityFactory.GetPhoneService(Authentication.GetTwilioAuthentication());

                    commClient.SendSMSAsync(phoneNumber, smsMessage);
                }

                // Send Email
                IEmailService emailService = UtilityFactory.GetEmailService(Authentication.GetDefaultEmailAuthentication());

                string crlf = "<br />";
                DateTime expiryDate = DateTime.Today.AddMonths(3);

                Email email = new Email
                {
                    // Unique voucher code, package details, and expiry date which are 3 months from the date of payment.
                    From = Authentication.GetDefaultEmailSenderAddress(),
                    To = WebSecurity.CurrentUserName,
                    Subject = "Grande Travel Package Details",

                    Body = String.Format(
                        "Hi {1}, {0}{0}" +
                        "Your payment of {2} for our {3} package has been successful. {0}" +
                        "Your credit card transaction code is {4}. {0}{0}" +
                        "Your Grande Travel voucher code is {5}, which is redeemable until {6}.{0}",
                        crlf,
                        user.FirstName,
                        String.Format("{0:c}", package.Amount),
                        package.Name,
                        order.TransactionId,
                        order.VoucherCode.ToString("00000000"),
                        expiryDate.ToLongDateString())
                };

                emailService.SendEmailAsync(email);
            }
            catch (Exception e)
            {
                // Email or Sms failed - but this will not catch async errors.
                LogTransaction(e.Message, true);
                resultMessage = "Your transaction has been processed. <br /> Please contact us about your trip.";
                return RedirectToResult(resultMessage, true);
            }

            LogTransaction("Successful Purchase.", true);
            return RedirectToResult(resultMessage, true);
        }