public void Search_ByExternalReference_Success()
        {
            PaymentCreateRequest request = BuildCreateRequest(true, "approved");
            Payment createdPayment       = client.Create(request);

            Thread.Sleep(3000);

            var searchRequest = new AdvancedSearchRequest
            {
                Limit     = 1,
                Offset    = 0,
                Sort      = "date_created",
                Criteria  = "desc",
                Range     = "date_created",
                BeginDate = DateTime.Now.Date,
                EndDate   = DateTime.Now.AddDays(1).AddMilliseconds(-1),
                Filters   = new Dictionary <string, object>
                {
                    ["external_reference"] = createdPayment.ExternalReference,
                },
            };
            ResultsResourcesPage <Payment> results = client.Search(searchRequest);

            Assert.NotNull(results);
            Assert.NotNull(results.Paging);
            Assert.Equal(1, results.Paging.Total);
            Assert.NotNull(results.Results);
            Assert.Equal(createdPayment.Id, results.Results.First().Id);
        }
Beispiel #2
0
        public async Task <Payment> CreatePayment(string intent, string paymentMethod = "credit_card", string invoiceNumber = null)
        {
            string ClientID    = this.configuration.GetSection("ClientID").Get <string>();
            string Secret      = this.configuration.GetSection("Secret").Get <string>();
            var    environment = new SandboxEnvironment(ClientID, Secret);

            var client  = new PayPalHttpClient(environment);
            var request = new PaymentCreateRequest();

            request.RequestBody(BuildRequestBody(intent, paymentMethod, invoiceNumber));

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

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                return(result);
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(new Payment());
            }
        }
Beispiel #3
0
        public async Task <string> ExecutePayment(Payment payment)
        {
            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;
                        // saving the paymentID in the key guid
                    }
                }
                return(paypalRedirectUrl);
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return("fail");
            }
        }
Beispiel #4
0
        public static async Task <Payment> CreatePayment(string baseUrl, string intent)
        {
            var client = PayPalConfiguration.GetClient();

            var payment = new Payment()
            {
                Intent = intent,    // `sale` or `authorize`
                Payer  = new Payer()
                {
                    PaymentMethod = "paypal"
                },
                Transactions = GetTransactionsList(),
                RedirectUrls = GetReturnUrls(baseUrl, intent)
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                //TODO - ASYNC
                HttpResponse response = await client.Execute(request);

                var statusCode = response.StatusCode;
                return(response.Result <Payment>());
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                throw httpException;
            }
        }
Beispiel #5
0
 private static async Task <BraintreeHttp.HttpResponse> ExecutePayPalRequest(
     PayPalHttpClient client,
     PaymentCreateRequest request)
 {
     SynchronizationContext.SetSynchronizationContext(null);
     return(await client.Execute(request).ConfigureAwait(false));
 }
Beispiel #6
0
        public async Task <object> Process(PaymentModel.Payment payment)
        {
            if (_paypalSettings == null)
            {
                throw new NullReferenceException("Paypal settings cannot be null.");
            }

            var env            = new SandboxEnvironment(_paypalSettings.ClientId, _paypalSettings.ClientSecret);
            var client         = new PayPalHttpClient(env);
            var paymentDetails = new PaymentMapper(payment).GetPaymentDetails();
            var request        = new PaymentCreateRequest();

            request.RequestBody(paymentDetails);

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

                var result = response.Result <PayPal.v1.Payments.Payment>();
                var json   = JsonConvert.SerializeObject(result);
                return(result);
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Beispiel #7
0
        public async Task <ActionResult> CreatePayment()
        {
            var hostingDomain = Request.Host.Value;
            var accessToken   = await GetAccessToken();

            var currentUser = await _workContext.GetCurrentUser();

            var cart = await _cartService.GetCart(currentUser.Id);

            var regionInfo          = new RegionInfo(CultureInfo.CurrentCulture.LCID);
            var experienceProfileId = await CreateExperienceProfile(accessToken);

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var paymentCreateRequest = new PaymentCreateRequest
            {
                experience_profile_id = experienceProfileId,
                intent = "sale",
                payer  = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new Transaction[]
                {
                    new Transaction {
                        amount = new Amount
                        {
                            total    = cart.OrderTotal.ToString(),
                            currency = regionInfo.ISOCurrencySymbol,
                            details  = new Details
                            {
                                subtotal = cart.SubTotalWithDiscount.ToString(),
                                tax      = cart.TaxAmount.ToString(),
                                shipping = cart.ShippingAmount.ToString()
                            }
                        }
                    }
                },
                redirect_urls = new Redirect_Urls
                {
                    cancel_url = $"http://{hostingDomain}/PaypalExpress/Cancel",  //Haven't seen it being used anywhere
                    return_url = $"http://{hostingDomain}/PaypalExpress/Success", //Haven't seen it being used anywhere
                }
            };

            var response = await httpClient.PostJsonAsync($"https://api{_setting.Value.EnvironmentUrlPart}.paypal.com/v1/payments/payment", paymentCreateRequest);

            var responseBody = await response.Content.ReadAsStringAsync();

            dynamic payment = JObject.Parse(responseBody);

            if (response.IsSuccessStatusCode)
            {
                string paymentId = payment.id;
                return(Ok(new { PaymentId = paymentId }));
            }

            return(BadRequest(responseBody));
        }
Beispiel #8
0
        public async Task <Payment> CreatePaymentAsync(PaypalTransaction transaction)
        {
            PayPalEnvironment environment;

            if (isSandboxMode)
            {
                environment = new SandboxEnvironment(clientId, clientSecret);
            }
            else
            {
                environment = new LiveEnvironment(clientId, clientSecret);
            }
            var client = new PayPalHttpClient(environment);

            try
            {
                var payment = CreatePayment(transaction);
                var request = new PaymentCreateRequest().RequestBody(payment);

                var response = await client.Execute(request);

                var statusCode = response.StatusCode;
                var result     = response.Result <Payment>();
                return(result);
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(null);
            }
        }
Beispiel #9
0
        public async Task <string> PaypalPayment(double total)
        {
            var environment = new SandboxEnvironment(configuration["PayPal:clientId"], configuration["PayPal:secret"]);
            var client      = new PayPalHttpClient(environment);

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = total.ToString(),
                            Currency = "USD"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = configuration["PayPal:cancelUrl"],
                    ReturnUrl = configuration["PayPal:returnUrl"]
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);
            string paypalRedirectUrl = null;

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

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                var     links      = result.Links.GetEnumerator();
                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;
                    }
                }
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
            }
            return(paypalRedirectUrl);
        }
        public async Task <PaymentServiceResponseDTO> CreateInvoice(Domain.Order order)
        {
            var environment = new SandboxEnvironment("AZTu0aTctY3TsQRanLBGIjRYVhzo7rc25etnkVduypxV38zDdRja0Z6_adpN7nakww62w667wNh4_OKT", "EPT6TcCPEuAbNrCatN0_FyrWFTGtO6-1c77lhSj_pMrIx3o2V09BnpZnhLe3CfGO0wtW0IULHGI4yrGc");
            var client      = new PayPalHttpClient(environment);

            int totalPrice = 0;

            foreach (var product in order.ProductsInOrder)
            {
                totalPrice += product.Product.Price;
            }

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        ItemList = new ItemList(),
                        Amount   = new Amount()
                        {
                            Total    = totalPrice.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(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);
            }
        }
Beispiel #11
0
        public async Task <ActionResult <ProductInvoiceViewModel> > PayProductInvoice(int id,
                                                                                      [FromBody] PaymentModel paymentModel)
        {
            ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(id);

            if (productInvoice is null)
            {
                return(NotFound($"No existe ninguna factura de producto con el código {id}"));
            }

            productInvoice.CalculateTotal();

            PaymentCreateRequest paymentCreateRequest = new PaymentCreateRequest
            {
                Token             = paymentModel.Token,
                PaymentMethodId   = paymentModel.PaymentMethodId,
                TransactionAmount = productInvoice.Total,
                Description       = $"Pay for product invoice {id}",
                Installments      = 1,
                Payer             = new PaymentPayerRequest
                {
                    FirstName = productInvoice.Client.FirstName,
                    LastName  = productInvoice.Client.LastName,
                    Email     = paymentModel.Email
                }
            };

            Payment payment = await _paymentClient.CreateAsync(paymentCreateRequest);

            if (payment.Status == PaymentStatus.Rejected)
            {
                return(BadRequest("El pago no pudo ser procesado."));
            }

            productInvoice.PublishEvent(new PaidInvoice(productInvoice));
            productInvoice.State         = InvoiceState.Paid;
            productInvoice.PaymentDate   = DateTime.Now;
            productInvoice.PaymentMethod = PaymentMethod.CreditCard;

            _productInvoicesRepository.Update(productInvoice);

            try
            {
                await _unitWork.SaveAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductInvoiceExists(id))
                {
                    return(NotFound(
                               $"Error de actualizacón. No existe ninguna factura de producto con el código {id}."));
                }

                throw;
            }

            return(_mapper.Map <ProductInvoiceViewModel>(productInvoice));
        }
Beispiel #12
0
        public async Task <string> CreateInvoice(Basket basket)
        {
            var environment = new SandboxEnvironment("AUcBbHNGlkF8pMud0Imkq_lEkvMeN2ebB3_fDS7-NIfvndr5x7maf6ol2WczTBEG5d4qoXHckCMqID5u", "EH8ICa3Sh-oEy_DXHDAzRpl8pjLWD2bphuGoUJeO39U-AqYr3ycFSi_icSjfz6lgz4O28VEuH91Ps33K");
            var client      = new PayPalHttpClient(environment);

            int totalPrice = 0;

            foreach (var product in basket.Products.ToList())
            {
                totalPrice += product.Cost;
            }

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        ItemList = new ItemList(),
                        Amount   = new Amount()
                        {
                            Total    = totalPrice.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(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);
            }
        }
Beispiel #13
0
        public async Task <IActionResult> Create([FromBody] PaymentCreateRequest request)
        {
            var result = await _paymentService.Create(request);

            if (!result.IsSuccess)
            {
                return(BadRequest(result));
            }
            return(Ok(result));
        }
Beispiel #14
0
        //public static async Task<CreditCard>  CreateCreditCard(CardModel card)
        //{
        //    // ### Api Context
        //    // Pass in a `APIContext` object to authenticate
        //    // the call and to send a unique request id
        //    // (that ensures idempotency). The SDK generates
        //    // a request id if you do not pass one explicitly.
        //    var environment = new SandboxEnvironment("AXBzX3BK0EIKIf87NiLs0FF56f6CBINvplAEI-eGQA5UCzlpzpsu1GwG3Jbz_0UaMcGVn6QF9xifYafT", "EHX5uun_f-IokPZKeziZPr8bP_S7NScvdqpw13mXaaHJz2TSVlNhsY8TjHqM3PTSzeZnDjkjtc4SlvtR");
        //    var client = new PayPalHttpClient(environment);
        //    // Payment Resource
        //    var creditCard = new CreditCard()
        //    {
        //        BillingAddress = new Address()
        //        {
        //            City = card.City,
        //            CountryCode = card.Country,
        //            Line1 = card.Address1,
        //            Line2 = card.Address2,
        //        },
        //        Cvv2 = card.CVC,
        //        ExpireMonth = card.Exp_Month,
        //        ExpireYear = card.Exp_Year,
        //        LastName = card.Name,
        //        Number = card.CardNumber,
        //        Type = card.Type
        //    };
        //    FundingInstrument fundInstrument = new FundingInstrument();
        //    fundInstrument.CreditCard = creditCard;

        //    List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
        //    fundingInstrumentList.Add(fundInstrument);
        //    client.
        //    PaymentCreateRequest request = new PaymentCreateRequest();
        //    request.RequestBody(payment);
        //    // Create a payment using a valid APIContext
        //    try
        //    {
        //        HttpResponse response = await client.Execute(request);
        //        var statusCode = response.StatusCode;
        //        Payment result = response.Result<Payment>();
        //        return result;
        //    }
        //    catch (HttpException httpException)
        //    {
        //        var statusCode = httpException.StatusCode;
        //        var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
        //    }

        //}

        public static async Task <Payment> ExecutePayment(string paymentId, string payerId)
        {
            var environment = new SandboxEnvironment("AXBzX3BK0EIKIf87NiLs0FF56f6CBINvplAEI-eGQA5UCzlpzpsu1GwG3Jbz_0UaMcGVn6QF9xifYafT", "EHX5uun_f-IokPZKeziZPr8bP_S7NScvdqpw13mXaaHJz2TSVlNhsY8TjHqM3PTSzeZnDjkjtc4SlvtR");
            var client      = new PayPalHttpClient(environment);
            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.

            // Payment Resource
            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);
            // Create a payment using a valid APIContext
            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                return(result);
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
            }
            return(null);
        }
        public async Task CreateAsync_Approved_Success()
        {
            PaymentCreateRequest request = await BuildCreateRequestAsync(true, "approved");

            Payment payment = await client.CreateAsync(request);

            Assert.NotNull(payment);
            Assert.NotNull(payment.Id);
            Assert.True(payment.Captured);
            Assert.Equal(request.ExternalReference, payment.ExternalReference);
        }
        public void Create_Approved_Success()
        {
            PaymentCreateRequest request = BuildCreateRequest(true, "approved");

            Payment payment = client.Create(request);

            Assert.NotNull(payment);
            Assert.NotNull(payment.Id);
            Assert.True(payment.Captured);
            Assert.Equal(request.ExternalReference, payment.ExternalReference);
        }
        public async Task <string> PayPalPaymentAsync(int orderPrice)
        {
            const string CLIENT_ID     = "Ab8zPbxBbiYu1TuE-3jyw0M6m41tBR4mhjXNDP1ZzQMEJ4JfQ9yJJy3qLT2LrO0oIrf-qpm7beMLAAXD";
            const string CLIENT_SECRET = "EMSYp9szDMBOMFd-nag3_VbHHm7LieAVIFK4FZNtidyRfGpIQwhcnEfdwPlophxERxgkhHsUMRngbm09";

            var environment = new SandboxEnvironment(CLIENT_ID, CLIENT_SECRET);
            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());
            }
        }
Beispiel #18
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);
            }
        }
Beispiel #19
0
        public async Task <PaymentServiceResponseDTO> CreateInvoice(Domain.Order order)
        {
            var environment = new SandboxEnvironment("AVKtkv3o13BU3eqJMpxTDJepdIsPUy1wwZNItREABfTzfc5pVhunjudf5LhzctAPw_WTC6Vvgaap5HSu", "EFCsGNXXcPrxCGkyuJM5d4Ge-fKzBeBtvE6tcDk4LOAGAFghMXDIPai8hMWKah5LLmz2ZaIPzG69fyzY");
            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);
            }
        }
Beispiel #20
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());
            }
        }
Beispiel #21
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);
            }
        }
Beispiel #22
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());
            }
        }
        public void Cancel_PendingPayment_Success()
        {
            // Creates a pending payment
            PaymentCreateRequest request = BuildCreateRequest(true, "pending");
            Payment payment = client.Create(request);

            Thread.Sleep(3000);

            // Cancels the payment
            payment = client.Cancel(payment.Id.GetValueOrDefault());

            Assert.NotNull(payment);
            Assert.Equal(PaymentStatus.Cancelled, payment.Status);
        }
        public void Get_Success()
        {
            // Creates a payment
            PaymentCreateRequest request = BuildCreateRequest(true, "approved");
            Payment createdPayment       = client.Create(request);

            Thread.Sleep(3000);

            // Gets the payment
            Payment payment = client.Get(createdPayment.Id.GetValueOrDefault());

            Assert.NotNull(payment);
            Assert.Equal(createdPayment.Id, payment.Id);
        }
        public async Task CancelAsync_PendingPayment_Success()
        {
            // Creates a pending payment
            PaymentCreateRequest request = await BuildCreateRequestAsync(true, "pending");

            Payment payment = await client.CreateAsync(request);

            await Task.Delay(3000);

            // Cancels the payment
            payment = await client.CancelAsync(payment.Id.GetValueOrDefault());

            Assert.NotNull(payment);
            Assert.Equal(PaymentStatus.Cancelled, payment.Status);
        }
        public async Task GetAsync_Success()
        {
            // Creates a payment
            PaymentCreateRequest request = await BuildCreateRequestAsync(true, "approved");

            Payment createdPayment = await client.CreateAsync(request);

            await Task.Delay(3000);

            // Gets the payment
            Payment payment = await client.GetAsync(createdPayment.Id.GetValueOrDefault());

            Assert.NotNull(payment);
            Assert.Equal(createdPayment.Id, payment.Id);
        }
        public void Refund_Total_Success()
        {
            // Creates a payment
            PaymentCreateRequest request = BuildCreateRequest(true, "approved");
            Payment createdPayment       = client.Create(request);

            Thread.Sleep(7000);

            PaymentRefund refund =
                client.Refund(createdPayment.Id.GetValueOrDefault());

            Assert.NotNull(refund);
            Assert.NotNull(refund.Id);
            Assert.Equal(createdPayment.Id, refund.PaymentId);
        }
        public async Task RefundAsync_Total_Success()
        {
            // Creates a payment
            PaymentCreateRequest request = await BuildCreateRequestAsync(true, "approved");

            Payment createdPayment = await client.CreateAsync(request);

            await Task.Delay(7000);

            PaymentRefund refund =
                await client.RefundAsync(createdPayment.Id.GetValueOrDefault());

            Assert.NotNull(refund);
            Assert.NotNull(refund.Id);
            Assert.Equal(createdPayment.Id, refund.PaymentId);
        }
Beispiel #29
0
        public async Task <IActionResult> Create(PaymentCreateRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            var result = await _paymentApiClient.CreatePayment(request);

            if (result.IsSuccess)
            {
                TempData["result"] = "Thêm phương thức thành công";
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", result.Message);
            return(View(request));
        }
        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;
            }
        }