Esempio n. 1
0
        public async Task <PaymentServiceResponseDTO> CreateInvoice(Domain.Order order)
        {
            var environment = new SandboxEnvironment("AdV4d6nLHabWLyemrw4BKdO9LjcnioNIOgoz7vD611ObbDUL0kJQfzrdhXEBwnH8QmV-7XZjvjRWn0kg", "EPKoPC_haZMTq5uM9WXuzoxUVdgzVqHyD5avCyVC1NCIUJeVaNNUZMnzduYIqrdw-carG9LBAizFGMyK");
            var client      = new PayPalHttpClient(environment);

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = "10",
                            Currency = "USD"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = "https://example.com/cancel",
                    ReturnUrl = "https://example.com/return"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                return(new PaymentServiceResponseDTO()
                {
                    PaymentUrl = result.Links.FirstOrDefault(link => link.Rel == APPROVAL_URL).Href
                });
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(null);
            }
        }
Esempio n. 2
0
        public async Task <string> ExecutePayment(string paymentId, string token, string payerId, string email)
        {
            var environment = new SandboxEnvironment("AV8B5CBqWFqiUEBdhbe2rBVqX0RwNjY74nORYSEI3P8WZ-rRzRxXd1H0pA_qrywn0MCZuXzg3x-WwDeY", "EL-1QQduQKljgE0uHFs6WKAM4JtYrbf8CzOisxNCczPvdnkQYQDT1-rCM1W1dYM3Dhu8L9AcwqwhKdZH");
            var client      = new PayPalHttpClient(environment);
            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

            request.RequestBody(new PaymentExecution()
            {
                PayerId = payerId
            });


            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                //PayerId en payment opslaan in DB
                var employee = _context.Employees.Find(email);
                employee.Balance = employee.Balance + 10;
                Models.Transaction transaction = new Models.Transaction()
                {
                    Amount                = 10,
                    DateTime              = DateTime.UtcNow,
                    Employee              = employee,
                    employeeEmail         = email,
                    ProviderName          = "PayPal",
                    ProviderTransactionId = paymentId,
                    TransactionType       = "ExternalTopUp"
                };
                try
                {
                    _context.Add(transaction);
                    _context.Update(employee);
                    await _context.SaveChangesAsync();

                    return("Complete");
                }
                catch (SqlException error)
                {
                    _logger.LogError("While running this error showed up:", error);
                    return("Failed");
                }
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return("Failed");
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> ConfirmAsync([FromRoute] string id)
        {
            string webroot     = HttpContext.Request.Scheme;
            string webroot1    = HttpContext.Request.Host.ToUriComponent();
            string pathReturn  = "http://" + webroot1 + "/paypal/execute-payment";
            string pathCancel  = "http://" + webroot1 + "/paypal/cancel";
            var    environment = new SandboxEnvironment("Acc2-UPp-z25_Olh73h5VZB3XjR16eUKtL2lHoIc27IJn8-2f5R8-Kish229pYjzdy18KR8khHJRQO5Q", "EIb_0hbZQPAEioCGLAzVpn87zRswB7zLAoRtda06Oc4IhrDAmtGYAI2z6xYplX6TdARnsuVh2TC3tHNM");
            var    client      = new PayPalHttpClient(environment);
            string idUser      = id;
            var    payment     = new Payment()
            {
                Intent       = "sale",
                Transactions = GetTransactionsList(id),
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = pathCancel,
                    ReturnUrl = pathReturn
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                },
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);
            var path = CreateExcelOrder.Create(_context.Orders.Where(m => m.UserId == id).Where(m => m.IsConfirm == false).ToList(), id, _environment);

            try
            {
                BraintreeHttp.HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                LinkDescriptionObject approvalLink = PaypalHelpers.findApprovalLink(result.Links);
                var orders = _context.Orders.Include(m => m.Product).Where(m => m.UserId == id).Where(m => m.IsConfirm == false);
                await orders.ForEachAsync(m => m.Paymentid = result.Id);

                await _context.SaveChangesAsync();

                return(Ok(new ConfirmModel {
                    confirmPath = approvalLink.Href.ToString(), excelPath = path
                }));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(NoContent());
            }
        }
        private async Task <Order> CaptureOrder(string OrderId, bool debug = false)
        {
            var request = new OrdersCaptureRequest(OrderId);

            request.Prefer("return=representation");
            request.RequestBody(new OrderActionRequest());
            var response = await _client.Execute(request);

            var result = response.Result <Order>();


            if (debug)
            {
                Console.WriteLine("Status: {0}", result.Status);
                Console.WriteLine("Order Id: {0}", result.Id);
                Console.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
                Console.WriteLine("Links:");
                foreach (LinkDescription link in result.Links)
                {
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
                Console.WriteLine("Capture Ids: ");
                foreach (PurchaseUnit purchaseUnit in result.PurchaseUnits)
                {
                    foreach (Capture capture in purchaseUnit.Payments.Captures)
                    {
                        Console.WriteLine("\t {0}", capture.Id);
                    }
                }
                AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
                Console.WriteLine("Buyer:");
                Console.WriteLine("\tEmail Address: {0}\n\tName: {1} {2}\n",
                                  result.Payer.Email,
                                  result.Payer.Name.GivenName,
                                  result.Payer.Name.Surname);
            }

            return(result);
        }
Esempio n. 5
0
        public async Task <PayPalDto> GetPaymentAsync(string orderId, CancellationToken token)
        {
            var captureRequest = new OrdersCaptureRequest(orderId);

            captureRequest.RequestBody(new OrderActionRequest());
            token.ThrowIfCancellationRequested();
            var response3 = await _client.Execute(captureRequest);

            var result       = response3.Result <Order>();
            var purchaseUnit = result.PurchaseUnits[0];

            return(new PayPalDto(purchaseUnit.ReferenceId, decimal.Parse(purchaseUnit.Payments.Captures[0].Amount.Value)));
        }
Esempio n. 6
0
        public async Task <InvoicePaymentProvider> CreateUriForPayment(Invoice invoice, Domain.Entities.Orders.Order order, Plan plan)
        {
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var payment = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        CustomId            = invoice.Id.ToString(),
                        Description         = plan.Description,
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = Currency.CurrencyValue.USD.ToString(),
                            Value        = Convert.ToInt32(plan.PlanPrices.Single(x => x.Currency.Code == Currency.CurrencyValue.USD).Price).ToString()
                        }
                    }
                },
                ApplicationContext = CreateApplicationContext()
            };

            //https://developer.paypal.com/docs/api/orders/v2/#orders_create
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var result = response.Result <PaypalOrder>();
                var uri    = new Uri(result.Links.Single(l => l.Rel == "approve").Href);

                return(new InvoicePaymentProvider
                {
                    InvoceId = invoice.Id,
                    Link = uri,
                    Transaction = result.Id,
                    PaymentProvider = new PaymentProvider(PaymentProvider.PaymentProviderValue.Paypal)
                });
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                throw httpException;
            }
        }
Esempio n. 7
0
        public async Task <string> PayPalPaymentAsync(int orderPrice)
        {
            var environment = new SandboxEnvironment("AR_Hs07d93iQYwXhs9EQ6IDyzPfQEglNyWASQy0ge5LzeFgBa_KCcLefYAH1k-AhbiFxYM9R812rrTQT", "EHvkxwY2zbqtPEVtzs5lzsuLU1nBOP3mdndiM_iPnZt0A1gLuDdUjXW3GBrdXpaXpxGscjCZ37VMcCk-");
            var client      = new PayPalHttpClient(environment);

            var payment = new Payment
            {
                Intent = "order",

                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = orderPrice.ToString(),
                            Currency = "USD"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = "https://example.com/cancel",
                    ReturnUrl = "https://example.com/return"
                },

                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                return(response.StatusCode.ToString());
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(statusCode.ToString());
            }
        }
Esempio n. 8
0
        public async Task <Payment> CreatePayment()
        {
            var    environment = new SandboxEnvironment("AfCRA5WhUKekcea2LHhTYMHVsDNixBuPFeqygJ9W3m6IkfKHrmp8JHryqWe_XMVXH1TJnaHIphmYJg6Z", "EL00PS-mY7IzkA-_NsGkHxTdBFE2Wz2jPh8NnaDjkIbCUJJSY-6iOA73q12Gpwuw0cn3Kb6e8z76PlVF");
            var    client      = new PayPalHttpClient(environment);
            string intent      = "sale";

            var payment = new Payment()
            {
                Intent = intent,

                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = "10",
                            Currency = "VND",
                        }
                    }
                },

                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = "https://example.com/cancel",
                    ReturnUrl = "https://example.com/return"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal",
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                return(result);
            }
            catch (Exception exception)
            {
                return(null);
            }
        }
Esempio n. 9
0
        public async Task CancelInvoice(string paypalOrderId)
        {
            PayPalCheckoutSdk.Core.PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var request = new OrderDeleteRequest(paypalOrderId);

            try
            {
                await client.Execute(request);
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
            }
        }
Esempio n. 10
0
        public async Task CancelInvoice(InvoicePaymentProvider invoice)
        {
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var request = new OrderDeleteRequest(invoice.Transaction);

            try
            {
                await client.Execute(request);
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
            }
        }
Esempio n. 11
0
        public async Task CreatePaymentAsync(Amount amount, ShippingAddress shippingAddress, Item article)
        {
            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount   = amount,
                        ItemList = new ItemList()
                        {
                            Items = new List <Item>()
                            {
                                article
                            },
                            //ShippingAddress = shippingAddress
                        }
                    }
                },
                //RedirectUrls = new RedirectUrls()
                //{
                //    CancelUrl = "https://example.com/cancel",
                //    ReturnUrl = "https://example.com/return"
                //},
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await _paypalClient.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
            }
        }
Esempio n. 12
0
        public async Task <Uri> CreateUriForPayment(OrderCreateInputModel inputModel)
        {
            var options = paypalOptions.CurrentValue;
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var payment = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        CustomId            = inputModel.OrderId.ToString(),
                        Description         = inputModel.Description,
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = inputModel.Price.Currency.ToString(),
                            Value        = inputModel.Price.Amount.ToString(CultureInfo.InvariantCulture)
                        }
                    }
                },
                ApplicationContext = CreateApplicationContext()
            };

            //https://developer.paypal.com/docs/api/orders/v2/#orders_create
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var statusCode = response.StatusCode;
                var result     = response.Result <Order>();
                return(new Uri(result.Links.Single(l => l.Rel == "approve").Href));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                logger.LogError($"Il tentativo di reindirizzare l'utente alla pagina di pagamento è fallito con status code {statusCode} e debugId {debugId}");
                throw new PaymentException();
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> Execute(string attemptId, [FromQuery] string payerID, string paymentId)
        {
            var clientId = this.configuration.GetSection("PayPal").GetSection("clientId").Value;
            var secret   = this.configuration.GetSection("PayPal").GetSection("secret").Value;

            var environment = new SandboxEnvironment(clientId, secret);
            var client      = new PayPalHttpClient(environment);

            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

            request.RequestBody(new PaymentExecution()
            {
                PayerId = payerID,
            });

            var response = await client.Execute <PaymentExecuteRequest>(request);

            var statusCode = response.StatusCode;

            if (statusCode.ToString() == "OK")
            {
                var attempt = await this.paymentsService.GetPaymentAttempt(attemptId);

                var userId     = attempt.StudentId;
                var semesterId = attempt.SemesterId;
                var semester   = await this.paymentsService
                                 .GetSemester <PaymentSemesterViewModel>(semesterId);

                await this.paymentsService.RegisterUserToSemesterAsync(userId, semesterId);

                foreach (var subject in semester.Subjects)
                {
                    await this.paymentsService.RegisterUserToSubjectAsync(userId, subject.Id);
                }

                await this.paymentsService.CreatePaymentAsync(userId, semesterId);

                this.TempData["message"] = $"Payment status code {statusCode}";
                return(this.RedirectToAction("Index", "Home"));
            }
            else
            {
                // Delete paymentAttmept
                this.TempData["message"] = $"Payment status code {statusCode}";
                return(this.RedirectToAction("Index", "Home"));
            }
        }
Esempio n. 14
0
        public async Task <string> CaptureOrderAsync(PayPalCaptureOrderRequestInput input)
        {
            var request = new OrdersCaptureRequest(input.OrderId);

            request.RequestBody(new OrderActionRequest());

            var response = await _client.Execute(request);

            var payment = response.Result <Order>();

            if (payment.Status != "COMPLETED")
            {
                throw new UserFriendlyException(L("PaymentFailed"));
            }

            return(payment.Id);
        }
Esempio n. 15
0
        public static TransactionResult ProcessRefund(TransactionRequest request, PaypalWithRedirectSettings settings)
        {
            var order = request.Order;

            var refund = new RefundRequest()
            {
                Amount = new Amount()
                {
                    Total    = (request.Amount ?? order.OrderTotal).ToString("N"),
                    Currency = order.CurrencyCode
                },
                Reason = "Admin Initiated Refund",
            };
            var saleRefundRequest = new SaleRefundRequest(request.Parameters["saleId"].ToString());

            saleRefundRequest.RequestBody(refund);
            var environment = GetEnvironment(settings);

            var client            = new PayPalHttpClient(environment);
            var transactionResult = new TransactionResult();

            try
            {
                var response = client.Execute(saleRefundRequest).Result;
                var result   = response.Result <DetailedRefund>();
                transactionResult.Success            = true;
                transactionResult.NewStatus          = result.State == "approved" || result.State == "pending" ? PaymentStatus.Refunded : PaymentStatus.OnHold;
                transactionResult.OrderGuid          = order.Guid;
                transactionResult.TransactionAmount  = result.Amount.Total.GetDecimal();
                transactionResult.ResponseParameters = new Dictionary <string, object>()
                {
                    { "id", result.Id },
                    { "parentPayment", result.ParentPayment },
                    { "createTime", result.CreateTime },
                    { "state", result.State },
                    { "updateTime", result.UpdateTime },
                };
            }
            catch (BraintreeHttp.HttpException ex)
            {
                transactionResult.Exception = ex;
            }

            return(transactionResult);
        }
Esempio n. 16
0
        public async Task <Payment> CreatePayment(string successUrl, string ErrorUrl, Transaction objTransaction, string note_to_player = "Web ban giay BMT")
        {
            var    client          = new PayPalHttpClient(environment);
            string intent          = "sale";
            var    listTransaction = new List <Transaction>();

            listTransaction.Add(objTransaction);
            var payment = new Payment()
            {
                Intent       = intent,
                NoteToPayer  = note_to_player,
                Transactions = listTransaction,
                //CreateTime=DateTime.Now.ToString(),


                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = ErrorUrl,
                    ReturnUrl = successUrl
                },

                Payer = new Payer()
                {
                    PaymentMethod = "paypal",
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                return(result);
            }
            catch (Exception objException)
            {
                throw objException;
            }
        }
Esempio n. 17
0
        public static async Task <string> CreateProfile()
        {
            SandboxEnvironment environment = new SandboxEnvironment(
                "AcsZudPzaw7QNmu68Q15SdtKMCM0HJMKO-q-Lp1IXgLwqe-Dt9CWOYqsBtZ_QiS2hVVL0o50BK8xW0Dk",
                "EJo0Vn_JKFf5qq4pN6zOKm50fmYN4dI8ZTeB5j2vl5YtWRnKeAPOvXK2WZ4faxGA8QaUM1KhVj-kF8kr");

            _client = new PayPalHttpClient(environment);


            WebProfileCreateRequest request = new WebProfileCreateRequest();
            WebProfile profile = new WebProfile
            {
                Name         = "WebProfil",
                Presentation = new Presentation
                {
                    BrandName  = "eTeatar",
                    LocaleCode = "US",
                    LogoImage  = "https://www.paypal.com/"
                },
                InputFields = new InputFields
                {
                    AddressOverride = 0,
                    AllowNote       = false,
                    NoShipping      = 1
                },
                FlowConfig = new FlowConfig
                {
                    BankTxnPendingUrl   = "https://www.paypal.com/",
                    LandingPageType     = "billing",
                    UserAction          = "commit",
                    ReturnUriHttpMethod = "POST"
                },
                Temporary = true
            };

            request.RequestBody(profile);


            HttpResponse response = await _client.Execute(request);

            WebProfile result = response.Result <WebProfile>();

            return(result.Id);
        }
Esempio n. 18
0
        public ActionResult About()
        {
            var clientId = "";
            var secret   = "";

            //Creating a sandbox environment
            PayPalEnvironment environment = new SandboxEnvironment(clientId, secret);

            // Creating a client for the environment
            PayPalHttpClient client = new PayPalHttpClient(environment);
            var request             = new OrdersGetRequest("");
            var task       = client.Execute(request);
            var response   = task.Result;
            var statusCode = response.StatusCode;

            ViewBag.Message = response.StatusCode.ToString();

            return(View(statusCode));
        }
Esempio n. 19
0
        public async Task <string> GetPaymentUrlAsync(CoursePayInputModel inputModel)
        {
            OrderRequest order = new()
            {
                CheckoutPaymentIntent = "CAPTURE",
                ApplicationContext    = new ApplicationContext()
                {
                    ReturnUrl          = inputModel.ReturnUrl,
                    CancelUrl          = inputModel.CancelUrl,
                    BrandName          = options.CurrentValue.BrandName,
                    ShippingPreference = "NO_SHIPPING"
                },
                PurchaseUnits = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        CustomId            = $"{inputModel.CourseId}/{inputModel.UserId}",
                        Description         = inputModel.Description,
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = inputModel.Price.Currency.ToString(),
                            Value        = inputModel.Price.Amount.ToString(CultureInfo.InvariantCulture) // 14.50
                        }
                    }
                }
            };

            PayPalEnvironment env    = GetPayPalEnvironment(options.CurrentValue);
            PayPalHttpClient  client = new PayPalHttpClient(env);

            OrdersCreateRequest request = new();

            request.RequestBody(order);
            request.Prefer("return=representation");

            HttpResponse response = await client.Execute(request);

            Order result = response.Result <Order>();

            LinkDescription link = result.Links.Single(link => link.Rel == "approve");

            return(link.Href);
        }
        public async Task <string> ExecutePaymentAsync(PayPalExecutePaymentRequestInput input)
        {
            var request = new PaymentExecuteRequest(input.PaymentId);

            request.RequestBody(new PaymentExecution()
            {
                PayerId = input.PayerId
            });

            var response = await _client.Execute(request);

            var payment = response.Result <Payment>();

            if (payment.State != "approved")
            {
                throw new UserFriendlyException(L("PaymentFailed"));
            }

            return(payment.Id);
        }
Esempio n. 21
0
        public async Task <IActionResult> Complete([FromBody] PayPalTransactionCompleteInput input)
        {
            _logger.LogInformation(input.ToString());
            try
            {
                OrdersGetRequest request = new OrdersGetRequest(input.OrderId);
                // Call PayPal to get the transaction
                var response = await _paypalClient.Execute(request);

                // Save the transaction in your database. Implement logic to save transaction to your database for future reference.
                var result     = response.Result <Order>();
                var resultJson = JsonConvert.SerializeObject(result);
                _logger.LogInformation("支付结果:" + resultJson);
                return(Json(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "支付失败");
                return(BadRequest());
            }
        }
Esempio n. 22
0
        public async Task <PaypalOrder> CaptureOrder(string transaction)
        {
            PayPalCheckoutSdk.Core.PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var request = new OrdersCaptureRequest(transaction);

            request.Prefer("return=representation");
            request.RequestBody(new OrderActionRequest());
            try
            {
                HttpResponse response = await client.Execute(request);

                PaypalOrder order = response.Result <PaypalOrder>();

                return(order);
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                throw httpException;
            }
        }
Esempio n. 23
0
        public static string FetchWebProfile(PaypalWithRedirectSettings paypalSettings)
        {
            if (!paypalSettings.CheckoutProfileId.IsNullEmptyOrWhiteSpace())
            {
                return(paypalSettings.CheckoutProfileId);
            }

            var webProfileRequest = new WebProfileCreateRequest();

            webProfileRequest.RequestBody(new WebProfile()
            {
                Temporary   = false,
                InputFields = new InputFields()
                {
                    NoShipping      = 1,
                    AddressOverride = 1
                },
                Name = Guid.NewGuid().ToString()
            });
            var environment = GetEnvironment(paypalSettings);
            var client      = new PayPalHttpClient(environment);

            try
            {
                var response = client.Execute(webProfileRequest).Result;
                var result   = response.Result <WebProfile>();
                var id       = result.Id;
                paypalSettings.CheckoutProfileId = id;
                var settingService = DependencyResolver.Resolve <ISettingService>();
                settingService.Save(paypalSettings, ApplicationEngine.CurrentStore.Id);
                return(id);
            }
            catch (BraintreeHttp.HttpException ex)
            {
                return(null);
            }
        }
Esempio n. 24
0
        public async Task <IActionResult> Pay([FromQuery] string attemptId)
        {
            var attempt = await this.paymentsService.GetPaymentAttempt(attemptId);

            var clientId = this.configuration.GetSection("PayPal").GetSection("clientId").Value;
            var secret   = this.configuration.GetSection("PayPal").GetSection("secret").Value;

            var environment = new SandboxEnvironment(clientId, secret);
            var client      = new PayPalHttpClient(environment);

            var portocol = this.HttpContext.Request.Scheme;
            var host     = this.HttpContext.Request.Host;

            var returnUrl = $"{portocol}://{host}/Payments/Execute/{attempt.Id}";
            var cancelUrl = $"{portocol}://{host}/Homes/Index";

            var payment = new PayPal.v1.Payments.Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = attempt.Price.ToString("G", CultureInfo.InvariantCulture),
                            Currency = "USD",
                        },
                    },
                },
                RedirectUrls = new RedirectUrls()
                {
                    ReturnUrl = returnUrl,
                    CancelUrl = cancelUrl,
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal",
                },
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            System.Net.HttpStatusCode statusCode;

            try
            {
                BraintreeHttp.HttpResponse response = await client.Execute(request);

                statusCode = response.StatusCode;
                Payment result = response.Result <Payment>();

                string redirectUrl = null;
                foreach (LinkDescriptionObject link in result.Links)
                {
                    if (link.Rel.Equals("approval_url"))
                    {
                        redirectUrl = link.Href;
                    }
                }

                if (redirectUrl == null)
                {
                    return(this.Json("Failed to find an approval_url in the response!"));
                }
                else
                {
                    return(this.Redirect(redirectUrl));
                }
            }
            catch (BraintreeHttp.HttpException ex)
            {
                statusCode = ex.StatusCode;
                var debugId = ex.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(this.Json("Request failed!  HTTP response code was " + statusCode + ", debug ID was " + debugId));
            }
        }
Esempio n. 25
0
        public async Task <PayPalPaymentCreationResultDto> CreatePayPalPaymentAsync(string amountToPay)
        {
            var environment = new SandboxEnvironment(_payPalSettings.ClientId, _payPalSettings.ClientSecret);
            var client      = new PayPalHttpClient(environment);

            var steamUser = _steamUserService.GetCurrentRequestSteamUser();

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = amountToPay,
                            Currency = "USD"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    ReturnUrl = $"{_hostString}/{_multiTenantContext.TenantInfo.Identifier}/payment/ExecutePayPalPayment",
                    CancelUrl = $"{_hostString}/{_multiTenantContext.TenantInfo.Identifier}/payment/PaymentFailed"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                },
                NoteToPayer = _configuration["BuyerNotes"]
            };

            PaymentCreateRequest paymentCreateRequest = new PaymentCreateRequest();

            paymentCreateRequest.RequestBody(payment);

            _logger.LogInformation($"Preparation for payment creation against PayPal API");

            HttpStatusCode responseStatusCode;

            try
            {
                BraintreeHttp.HttpResponse paymentCreateRequestResult = await client.Execute(paymentCreateRequest);

                _logger.LogInformation($"PayPal payment creation result, {nameof(paymentCreateRequestResult)}: {JsonConvert.SerializeObject(paymentCreateRequestResult)}");

                responseStatusCode = paymentCreateRequestResult.StatusCode;

                if (responseStatusCode != HttpStatusCode.Created)
                {
                    return(null);
                }

                Payment paymentResult = paymentCreateRequestResult.Result <Payment>();

                await _payPalCreatedPaymentService.CreateAsync(paymentResult);

                return(new PayPalPaymentCreationResultDto {
                    State = PaymentCreationResultEnum.Success, PaymentDetails = paymentResult
                });
            }
            catch (BraintreeHttp.HttpException e)
            {
                responseStatusCode = e.StatusCode;
                var debugId = e.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                _logger.LogError(e, $"PayPal payment creation: Failed\nSteamUserID: {steamUser.Id}\nSteamUserUID: {steamUser.Uid}\nDebugId: {debugId}\nStatusCode: {responseStatusCode}");

                return(new PayPalPaymentCreationResultDto
                {
                    State = PaymentCreationResultEnum.Failed,
                    FailedReason = debugId
                });
            }
        }
Esempio n. 26
0
        public async Task <PayPalPaymentExecuteResultDto> ExecutePayPalPaymentAsync(string paymentId, string token, string payerId)
        {
            var environment = new SandboxEnvironment(_payPalSettings.ClientId, _payPalSettings.ClientSecret);
            var client      = new PayPalHttpClient(environment);

            var steamUser = _steamUserService.GetCurrentRequestSteamUser();

            PaymentExecution paymentExecution = new PaymentExecution()
            {
                PayerId = payerId
            };
            PaymentExecution payment = new PaymentExecution()
            {
                PayerId = payerId
            };
            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

            request.RequestBody(payment);

            HttpStatusCode statusCode;
            Payment        paymentExecutionResult = null;

            _logger.LogInformation($"Preparation for payment execution against PayPal API");

            HttpStatusCode responseStatusCode;

            try
            {
                BraintreeHttp.HttpResponse response = await client.Execute(request);

                statusCode             = response.StatusCode;
                paymentExecutionResult = response.Result <Payment>();

                await _payPalExecutedPaymentService.CreateAsync(paymentExecutionResult);

                _logger.LogInformation($"PayPal payment execution result, {nameof(paymentExecutionResult)}: {JsonConvert.SerializeObject(paymentExecutionResult)}");
            }
            catch (BraintreeHttp.HttpException e)
            {
                responseStatusCode = e.StatusCode;
                var debugId = e.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                _logger.LogError(e, $"PayPal payment execution: Failed\nSteamUserID: {steamUser.Id}\nSteamUserUID: {steamUser.Uid}\nDebugId: {debugId}\nStatusCode: {responseStatusCode}");
                return(new PayPalPaymentExecuteResultDto
                {
                    State = PaymentExecutionResultEnum.Failed,
                    FailedReason = debugId
                });
            }

            if (paymentExecutionResult.State == "approved")
            {
                var updateSteamUserShopBalanceResult = await AddFundsToSteamUserShopAsync(paymentExecutionResult);

                if (!updateSteamUserShopBalanceResult)
                {
                    return new PayPalPaymentExecuteResultDto
                           {
                               State        = PaymentExecutionResultEnum.Failed,
                               FailedReason = "Error on adding funds, please contact support!"
                           }
                }
                ;

                return(new PayPalPaymentExecuteResultDto
                {
                    State = PaymentExecutionResultEnum.Success,
                    AmountPaid = paymentExecutionResult
                                 .Transactions.First()
                                 .RelatedResources.First()
                                 .Sale.Amount.Total,
                    CurrentBalance = _steamUserService.GetCurrentRequestSteamUserShop().Balance
                });
            }

            return(new PayPalPaymentExecuteResultDto
            {
                State = PaymentExecutionResultEnum.Failed,
                FailedReason = "Payment has not been approved!"
            });
        }
Esempio n. 27
0
        public async Task <IActionResult> Checkout()
        {
            //SandboxEnvironment(clientId, clientSerect)
            string clientId     = "AYOwjSPbuM8boAckmyHBzPF3fS5jkqsE6-i-fd_2Y66bMFW7t9miYPklGgcNAdXweQa4ijsjCRQnElL1";
            string clientSecret = "EL485ImsKFuaWVHj8YqVRNwzc1-q8xsmFMaDnFyvBTwH5JT4zqyGe7dLT9F4-Q64-ebEaix79UYxnO4H";
            var    environment  = new SandboxEnvironment(clientId, clientSecret);
            var    client       = new PayPalHttpClient(environment);

            double UsdToVnd = 23211.67;

            //Đọc thông tin đơn hàng từ Session
            var itemList = new ItemList()
            {
                Items = new List <Item>()
            };

            double tongTien = Cart.Sum(p => p.TotalPrice) / UsdToVnd;

            foreach (var item in Cart)
            {
                itemList.Items.Add(new Item()
                {
                    Name     = item.Product.ProductName,
                    Currency = "USD",
                    Price    = (item.Product.UnitPrice / UsdToVnd).ToString("0.00"),
                    Quantity = item.Amount.ToString(),
                    Sku      = "sku",
                    Tax      = "0"
                });
            }


            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = tongTien.ToString("0.00"),
                            Currency = "USD",
                            Details  = new AmountDetails
                            {
                                Tax      = "0",
                                Shipping = "0",
                                Subtotal = tongTien.ToString("0.00")
                            }
                        },
                        ItemList      = itemList,
                        Description   = "Don hang A",
                        InvoiceNumber = DateTime.Now.Ticks.ToString()
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = "http://localhost:44370/paypal/fail",
                    ReturnUrl = "https://localhost:44370/paypal/Execute"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                var    links             = result.Links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    LinkDescriptionObject lnk = links.Current;
                    if (lnk.Rel.ToLower().Trim().Equals("approval_url"))
                    {
                        //saving the payapalredirect URL to which user will be redirected for payment
                        paypalRedirectUrl = lnk.Href;
                    }
                }

                return(Redirect(paypalRedirectUrl));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                string a = tongTien.ToString();

                return(RedirectToAction("Fail"));
            }
        }
Esempio n. 28
0
        //[Authorize]
        public async System.Threading.Tasks.Task <IActionResult> PaypalCheckout()
        {
            var environment = new SandboxEnvironment(_clientId, _secretKey);
            var client      = new PayPalHttpClient(environment);

            var cart = HttpContext.Session.Get <OrderHeader>("cart");

            #region Create Paypal Order

            var itemList = new ItemList()
            {
                Items = new List <Item>()
            };

            foreach (var item in cart.OrderDetails)
            {
                itemList.Items.Add(new Item()
                {
                    Name        = item.Product.Name,//"Trà sữa",
                    Currency    = "USD",
                    Price       = Math.Round(item.Product.Price.GetValueOrDefault() / TyGiaUSD, 2).ToString(),
                    Quantity    = item.Count.ToString(),
                    Description = "Số lượng: " + item.Count.ToString(),
                    Sku         = "sku",
                    Tax         = "0"
                });
            }
            var total = itemList.Items.Sum(x => double.Parse(x.Price) * int.Parse(x.Quantity));

            #endregion

            //var total = Math.Round(double.Parse(checkout[0].Total.ToString()) / 23000, 2) *itemList.Items.Count;

            var paypalOrderId = cart.Id;
            var hostname      = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = total.ToString(),
                            Currency = "USD",
                            Details  = new AmountDetails
                            {
                                Tax      = "0",
                                Shipping = "0",
                                Subtotal = total.ToString()
                            }
                        },
                        ItemList      = itemList,
                        Description   = $"Invoice #{paypalOrderId}",
                        InvoiceNumber = paypalOrderId.ToString()
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = $"{hostname}/Paypal/CheckoutFail",
                    ReturnUrl = $"{hostname}/Paypal/CheckoutSuccess"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();
            request.RequestBody(payment);
            var transaction = await _db.Database.BeginTransactionAsync();

            try
            {
                var code     = HttpContext.Session.Get <string>("discount");
                var discount = _db.Discounts.Where(x => (x.TimesUseLimit - x.TimesUsed) > 0 && x.DateExpired > DateTime.Now).FirstOrDefault(x => x.Code == code);
                if (discount != null)
                {
                    discount.TimesUsed++;
                    _db.SaveChanges();
                }
                #region Add cart
                cart.ApplicationUser = null;
                cart.PaymentStatus   = "Paid";
                var newlistOrderDetail = cart.OrderDetails.Select(x => new OrderDetail
                {
                    Count           = x.Count,
                    OrderHeaderId   = x.OrderHeaderId,
                    ProductId       = x.ProductId,
                    Price           = x.Price,
                    Id              = x.Id,
                    Status          = x.Status,
                    DeliveryDetails = new DeliveryDetail()
                    {
                        Address = x.DeliveryDetails.Address, DateEnd = x.DeliveryDetails.DateEnd, Price = x.DeliveryDetails.Price, DateStart = x.DeliveryDetails.DateStart, DeliveryId = x.DeliveryDetails.DeliveryId, Note = x.DeliveryDetails.Note, OrderDetailId = x.DeliveryDetails.OrderDetailId
                    }
                });
                cart.OrderDetails = newlistOrderDetail.ToList();


                foreach (var item in cart.OrderDetails)
                {
                    var objfromDb = _db.Products.Find(item.ProductId);
                    objfromDb.Quantity = objfromDb.Quantity - item.Count;
                    if (objfromDb.Quantity < 0)
                    {
                        throw new Exception("Lỗi đơn hàng " + objfromDb.Name + " chỉ còn " + (objfromDb.Quantity + item.Count));
                    }
                    else
                    {
                        _db.Update(objfromDb);
                        _db.SaveChanges();
                    }
                }
                _db.OrderHeaders.Add(cart);
                _db.SaveChanges();
                #endregion
                var response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                var    links             = result.Links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    LinkDescriptionObject lnk = links.Current;
                    if (lnk.Rel.ToLower().Trim().Equals("approval_url"))
                    {
                        //saving the payapalredirect URL to which user will be redirected for payment
                        paypalRedirectUrl = lnk.Href;
                    }
                }
                await transaction.CommitAsync();

                transaction.Dispose();
                HttpContext.Session.Remove("cart");
                HttpContext.Session.Remove("discount");
                return(Redirect(paypalRedirectUrl));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                transaction.Rollback();
                transaction.Dispose();
                HttpContext.Session.Remove("cart");
                HttpContext.Session.Remove("discount");
                //Process when Checkout with Paypal fails
                return(Redirect("/Paypal/CheckoutFail"));
            }
            catch (Exception)
            {
                transaction.Rollback();
                transaction.Dispose();
                HttpContext.Session.Remove("cart");
                HttpContext.Session.Remove("cart");
                return(Redirect("/Paypal/CheckoutFail"));
            }
        }
Esempio n. 29
0
        public async Task <IActionResult> Checkout(Orders order)
        {
            //SandboxEnvironment(clientId, clientSerect)
            var environment = new SandboxEnvironment("ATEyDHMWKozlcGDf5yNduG92WTeajJf9gqXc34Dd0AU7LbWgFvH3qY_8ImvFfZls5uZMzaoeZAdZBCrm", "EH1J-u4MfbsyBENy8zBoVHHOnU9DMsDRjGDaXwfZltNEVc3rv_t26ANZ_L2Z4eQlS12oRnUj_Zr8dizO");
            var client      = new PayPalHttpClient(environment);

            //Đọc thông tin đơn hàng từ Session
            var itemList = new ItemList()
            {
                Items = new List <Item>()
            };

            var AmountUSD = Cart.Sum(p => CurrencyConversion(p.Price, p.QuantityProduct));
            int?AmountVND = 0;

            foreach (var item in Cart)
            {
                AmountVND += item.Price;
                itemList.Items.Add(new Item()
                {
                    Name     = item.ProductName,
                    Currency = "USD",
                    Price    = CurrencyConversion(item.Price).ToString(),
                    Quantity = item.QuantityProduct.ToString(),
                    Tax      = "0"
                });
            }

            order.CreatedDate = DateTime.Now;

            // tính phí ship
            order.Total = AmountVND;
            var shipCostUSD = 0.00;

            if (AmountVND < 100000)
            {
                shipCostUSD    = 0.87;
                order.ShipCost = 20000;
            }
            else if (AmountVND < 500000)
            {
                shipCostUSD    = 0.52;
                order.ShipCost = 12000;
            }
            else
            {
                order.ShipCost = 0;
            }

            // kiểm tra người dùng có đăng nhập để lưu ID người dùng
            var info = HttpContext.Session.GetObject <Customer>("Customer");

            if (info != null)
            {
                order.CustomerId = info.CustomerId;
            }

            _context.Orders.Add(order);
            _context.SaveChanges();
            IdLasted = order.OrderId;
            foreach (var item in Cart)
            {
                OrderDetail orderDetail = new OrderDetail()
                {
                    OrderId   = IdLasted,
                    ProductId = item.ProductId,
                    Price     = item.Price,
                    Quantity  = item.QuantityProduct
                };
                _context.OrderDetail.Add(orderDetail);
                _context.SaveChanges();
            }

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = (AmountUSD + shipCostUSD).ToString(),
                            Currency = "USD",
                            Details  = new AmountDetails
                            {
                                Tax      = "0",
                                Shipping = shipCostUSD.ToString(),
                                Subtotal = AmountUSD.ToString(),
                            }
                        },
                        ItemList      = itemList,
                        Description   = "Don hang " + IdLasted,
                        InvoiceNumber = DateTime.Now.Ticks.ToString()
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + "/Paypal/Fail",
                    ReturnUrl = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + "/Paypal/Execute"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                var    links             = result.Links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    LinkDescriptionObject lnk = links.Current;
                    if (lnk.Rel.ToLower().Trim().Equals("approval_url"))
                    {
                        //saving the payapalredirect URL to which user will be redirected for payment
                        paypalRedirectUrl = lnk.Href;
                    }
                }

                return(Redirect(paypalRedirectUrl));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                return(RedirectToAction("Fail"));
            }
        }
Esempio n. 30
0
        public async System.Threading.Tasks.Task <IActionResult> PaypalCheckout()
        {
            var environment = new SandboxEnvironment(_clientId, _secretKey);
            var client      = new PayPalHttpClient(environment);

            #region Create Paypal Order
            var itemList = new ItemList()
            {
                Items = new List <Item>()
            };
            var total = Math.Round(Carts.Sum(p => p.ThanhTien) / TyGiaUSD, 2);
            foreach (var item in Carts)
            {
                itemList.Items.Add(new Item()
                {
                    Name     = item.TenHh,
                    Currency = "USD",
                    Price    = Math.Round(item.DonGia / TyGiaUSD, 2).ToString(),
                    Quantity = item.SoLuong.ToString(),
                    Sku      = "sku",
                    Tax      = "0"
                });
            }
            #endregion

            var paypalOrderId = DateTime.Now.Ticks;
            var hostname      = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
            var payment       = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = total.ToString(),
                            Currency = "USD",
                            Details  = new AmountDetails
                            {
                                Tax      = "0",
                                Shipping = "0",
                                Subtotal = total.ToString()
                            }
                        },
                        ItemList      = itemList,
                        Description   = $"Invoice #{paypalOrderId}",
                        InvoiceNumber = paypalOrderId.ToString()
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = $"{hostname}/GioHang/CheckoutFail",
                    ReturnUrl = $"{hostname}/GioHang/CheckoutSuccess"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                var    links             = result.Links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    LinkDescriptionObject lnk = links.Current;
                    if (lnk.Rel.ToLower().Trim().Equals("approval_url"))
                    {
                        //saving the payapalredirect URL to which user will be redirected for payment
                        paypalRedirectUrl = lnk.Href;
                    }
                }

                return(Redirect(paypalRedirectUrl));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                //Process when Checkout with Paypal fails
                return(Redirect("/GioHang/CheckoutFail"));
            }
        }