コード例 #1
0
        public async Task <IActionResult> ExecuteSuccess(string paymentID, string token, string payerID, [FromServices] IServiceProvider serviceProvider)
        {
            _logger.LogInformation("Executing the payment against the PAYPAL SDK");

            var paymentModel = await _functionalUnitOfWork.PaymentRepository.FirstOrDefault(p => p.PaymentReference == paymentID);

            PayPal.v1.Payments.Payment result = await ExecutePayment(payerID, paymentID);

            paymentModel.PayerID       = payerID;
            paymentModel.TokenId       = token;
            paymentModel.IsValidated   = true;
            paymentModel.ValidatedDate = DateTime.UtcNow;

            if (paymentModel.PaymentType == "Subscription")
            {
                var user = await _userManager.FindByIdAsync(paymentModel.UserId);

                var subscription = await _functionalUnitOfWork.SubscriptionRepository.FirstOrDefault(s => s.Id == paymentModel.Reference);

                subscription.Enable = true;
                await _functionalUnitOfWork.SubscriptionRepository.Update(subscription);

                var pack = await _functionalUnitOfWork.SubscriptionPackRepository.FirstOrDefault(p => p.Id == subscription.SubscriptionPackId);

                user.SubscriptionStartDate = user.SubscriptionEndDate;
                user.SubscriptionEndDate   = user.SubscriptionStartDate.Value.AddMonths(pack.Duration);
                await _userManager.UpdateAsync(user);

                _logger.LogInformation($"The paypal controller has a new response '{result}' from the Paypal API");

                await SendSubscriptionPaymentEmail(user, subscription.Id, EmailTemplateEnum.SubscriptionPayed, "subscription");

                return(Redirect($"{_configuration["Service:FrontOffice:Url"].TrimEnd('/')}/ConfirmPayment/Success/{subscription.Id}"));
            }
            else if (paymentModel.PaymentType == "Ad")
            {
                var ad = await _functionalUnitOfWork.AdRepository.FirstOrDefault(p => p.Id == paymentModel.Reference);

                ad.IsValid      = true;
                ad.ValidateDate = DateTime.Now;
                await _functionalUnitOfWork.AdRepository.Update(ad);

                _logger.LogInformation($"The paypal controller has a new response '{result}' from the Paypal API");
                return(Redirect($"{_configuration["Service:FrontOffice:Url"].TrimEnd('/')}/ConfirmPayment/Success"));
            }

            return(BadRequest());
        }
コード例 #2
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));
            }
        }
コード例 #3
0
        private async Task <PayPal.v1.Payments.Payment> ProcessPayment(PaymentModel model)
        {
            var mode = _configuration["Service:Paypal:Mode"];
            PayPalHttpClient client = null;

            switch (mode)
            {
            case "production":
            {
                var environment = new LiveEnvironment(_configuration["Service:Paypal:ClientId"], _configuration["Service:Paypal:ClientSecret"]);
                client = new PayPalHttpClient(environment);
                break;
            }

            case "sandbox":
            {
                var environment = new SandboxEnvironment(_configuration["Service:Paypal:ClientId"], _configuration["Service:Paypal:ClientSecret"]);
                client = new PayPalHttpClient(environment);
                break;
            }
            }

            var payment = new PayPal.v1.Payments.Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", model.TotalTTc)
                                    .Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "."), Details = new AmountDetails
                            {
                                Subtotal = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", model.SubTotal),
                                Tax      = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", model.TotalTax)
                            },
                            Currency = "EUR"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = $"{_configuration["Service:FrontOffice:Url"].TrimEnd('/')}/api/paypal/cancel",
                    ReturnUrl = $"{_configuration["Service:FrontOffice:Url"].TrimEnd('/')}/api/paypal/success"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

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

                var statusCode = response.StatusCode;

                PayPal.v1.Payments.Payment result = response.Result <PayPal.v1.Payments.Payment>();
                model.PaymentReference = result.Id;

                await _functionalUnitOfWork.PaymentRepository.Update(model);

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

                throw;
            }
        }
コード例 #4
0
        public static string CreatePaymentRequest(string price)
        {
            //var environment = new LiveEnvironment("AbsLlwBzsLwTvG-6awsiklgFPeDNWlGctQ9MukFQl-VimUpPwBtTLpR5SX8Wyu0U_R8pg6mGxgrpzYiA", "EIFw-teU8tWyH7UBXgI7UftSXuJoB1aG51jkZMiRb23x39OaTd9kLOcKSVtb6FWK5vj1sSypW1kC9xUB");
            var environment = new SandboxEnvironment("ARXuDzN7ArL3ZiTG0_ebn-4u53kqetWWQSkM5UoVk5KZ_ClhTjSueiVJTnDuFvYtf4TnPxxJDRSJryWJ", "EL6FuAA6ocMA6rFtSWg7Ck-mZYMCq4W-G-huZPVsiOIT9zyI9z2Wh_-_Elv9GiiWP00S8fn28I5G-NFm");

            var client = new PayPalHttpClient(environment);

            var payment = new PayPal.v1.Payments.Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = price,
                            Currency = "EUR"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    ReturnUrl = "https://localhost:44353/Invoice/InvoiceComplete",
                    //ReturnUrl = "https://www.spartanboosting.com/Invoice/InvoiceComplete",
                    CancelUrl = "https://www.spartanboosting.com"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            System.Net.HttpStatusCode statusCode;

            try
            {
                BraintreeHttp.HttpResponse response = client.Execute(request).Result;
                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)
                {
                    // Didn't find an approval_url in response.Links
                    //await context.Response.WriteAsync("Failed to find an approval_url in the response!");
                }
                else
                {
                    return(redirectUrl);
                }
            }
            catch (BraintreeHttp.HttpException ex)
            {
                statusCode = ex.StatusCode;
                var debugId = ex.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                //await context.Response.WriteAsync("Request failed!  HTTP response code was " + statusCode + ", debug ID was " + debugId);
            }

            return("");
        }
コード例 #5
0
        public async Task <string> ProcessPayment(PayPalTestViewModel model)
        {
            var environment = new SandboxEnvironment(_configuration["PayPal:SandBox:ClientId"], _configuration["PayPal:SandBox:ClientSecret"]);
            var client      = new PayPalHttpClient(environment);

            var payment = new PayPal.v1.Payments.Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = model.Amount,
                            Currency = "INR"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    ReturnUrl = _urlHelper.Action("Done", "Test", new { amt = model.Amount }, _context.HttpContext.Request.Scheme, _context.HttpContext.Request.Host.ToString()),
                    CancelUrl = _urlHelper.Action("Cancel", "Test", new { amt = model.Amount }, _context.HttpContext.Request.Scheme, _context.HttpContext.Request.Host.ToString())
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            System.Net.HttpStatusCode statusCode;

            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)
            {
                // Didn't find an approval_url in response.Links
                return(null);
            }
            else
            {
                return(redirectUrl);
            }
        }