示例#1
0
        public async Task <IActionResult> Execute(string paymentId, string PayerId)
        {
            //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);


            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>();
                return(RedirectToAction("Success"));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(RedirectToAction("Fail"));
            }
        }
示例#2
0
        public async Task <Payment> ExecutePaymentAsync(PayVM payVM)
        {
            var paymentId = payVM.PaymentID;

            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

            var body = new PaymentExecution()
            {
                PayerId = payVM.PayerID
            };

            request.RequestBody(body);

            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);

            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());
            }
        }
示例#3
0
        public async Task <IActionResult> Execute(string paymentId, string PayerId)
        {
            var environment = new SandboxEnvironment("Acc2-UPp-z25_Olh73h5VZB3XjR16eUKtL2lHoIc27IJn8-2f5R8-Kish229pYjzdy18KR8khHJRQO5Q", "EIb_0hbZQPAEioCGLAzVpn87zRswB7zLAoRtda06Oc4IhrDAmtGYAI2z6xYplX6TdARnsuVh2TC3tHNM");
            var client      = new PayPalHttpClient(environment);

            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

            request.RequestBody(new PaymentExecution()
            {
                PayerId = PayerId
            });
            await _context.Orders.Where(m => m.Paymentid == paymentId).ForEachAsync(m => m.IsConfirm = true);

            await _context.SaveChangesAsync();

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

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                return(Redirect("sold"));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(BadRequest(debugId));
            }
        }
示例#4
0
        public async Task <IActionResult> Execute(string paymentId, string PayerId)
        {
            //SandboxEnvironment(clientId, clientSerect)
            string clientId     = "ATEyDHMWKozlcGDf5yNduG92WTeajJf9gqXc34Dd0AU7LbWgFvH3qY_8ImvFfZls5uZMzaoeZAdZBCrm";
            string clientSecret = "EH1J-u4MfbsyBENy8zBoVHHOnU9DMsDRjGDaXwfZltNEVc3rv_t26ANZ_L2Z4eQlS12oRnUj_Zr8dizO";
            var    environment  = new SandboxEnvironment(clientId, clientSecret);
            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>();
                return(RedirectToAction("Success"));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(RedirectToAction("Fail"));
            }
        }
        public async Task <IActionResult> ExecutePayment(string paymentId, string token, string PayerID)
        {
            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

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

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

                HttpStatusCode statusCode = response.StatusCode;
                Payment        result     = response.Result <Payment>();
                if (result.State == "approved")
                {
                    return(RedirectToAction(nameof(Success)));
                }
                else
                {
                    return(RedirectToAction(nameof(Error)));
                }
            }
            catch (HttpException httpException)
            {
                HttpStatusCode statusCode = httpException.StatusCode;
                string         debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(RedirectToAction(nameof(Error)));
            }
        }
示例#6
0
        public static TransactionResult ProcessExecution(Order order, PaymentReturnModel returnModel, PaypalWithRedirectSettings settings)
        {
            var transAmount = order.OrderTotal - order.StoreCreditAmount;
            var payment     = new PaymentExecution()
            {
                PayerId      = returnModel.PayerId,
                Transactions = new List <CartBase>()
                {
                    new CartBase()
                    {
                        Amount = new Amount()
                        {
                            Currency = order.CurrencyCode,
                            Total    = transAmount.ToString("N")
                        }
                    }
                }
            };
            var pcRequest = new PaymentExecuteRequest(returnModel.PaymentId);

            pcRequest.RequestBody(payment);

            var environment = GetEnvironment(settings);

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

            try
            {
                var response = client.Execute(pcRequest).Result;
                var result   = response.Result <Payment>();
                transactionResult.Success                 = true;
                transactionResult.NewStatus               = result.State == "approved" ? PaymentStatus.Complete : PaymentStatus.OnHold;
                transactionResult.OrderGuid               = order.Guid;
                transactionResult.TransactionAmount       = result.Transactions[0].Amount.Total.GetDecimal();
                transactionResult.TransactionGuid         = returnModel.PaymentId;
                transactionResult.TransactionCurrencyCode = result.Transactions[0].Amount.Currency;
                transactionResult.ResponseParameters      = new Dictionary <string, object>()
                {
                    { "id", result.Id },
                    { "payerId", returnModel.PayerId },
                    { "paymentId", returnModel.PaymentId },
                    { "createTime", result.CreateTime },
                    { "failureReason", result.FailureReason },
                    { "experienceProfileId", result.ExperienceProfileId },
                    { "noteToPayer", result.NoteToPayer },
                    { "intent", result.Intent },
                    { "state", result.State },
                    { "updateTime", result.UpdateTime },
                    { "saleId", result.Transactions[0].RelatedResources[0].Sale.Id }
                };
            }
            catch (BraintreeHttp.HttpException ex)
            {
                transactionResult.Success   = false;
                transactionResult.Exception = ex;
            }

            return(transactionResult);
        }
示例#7
0
        public static async Task <Payment> ExecutePayment(string paymentId, string payerId)
        {
            var client = PayPalConfiguration.GetClient();

            var paymentExecution = new PaymentExecution()
            {
                PayerId = payerId
            };
            var payment = new Payment()
            {
                Id = paymentId
            };

            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

            request.RequestBody(paymentExecution);

            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;
            }
        }
示例#8
0
        public static async Task <bool> ExecutePayment(string paymentId, string payerId)
        {
            SandboxEnvironment environment = new SandboxEnvironment(
                "AcsZudPzaw7QNmu68Q15SdtKMCM0HJMKO-q-Lp1IXgLwqe-Dt9CWOYqsBtZ_QiS2hVVL0o50BK8xW0Dk",
                "EJo0Vn_JKFf5qq4pN6zOKm50fmYN4dI8ZTeB5j2vl5YtWRnKeAPOvXK2WZ4faxGA8QaUM1KhVj-kF8kr");

            _client = new PayPalHttpClient(environment);


            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);

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


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

                HttpStatusCode Status = response.StatusCode;

                return(Status.ToString() == "OK");
            }
            catch (HttpException)
            {
                return(false);
            }
        }
示例#9
0
        public async Task <Payment> ExecutePayment(PaymentExecution objPaymentExecution, string paymentId)
        {
            var    client = new PayPalHttpClient(environment);
            string intent = "sale";


            PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId);;

            request.RequestBody(objPaymentExecution);

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

                var statusCode = response.StatusCode;

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

                return(result);
            }
            catch (Exception objException)
            {
                throw objException;
            }
        }
示例#10
0
        public override async Task <IOrder> ChargeAsync(PayPalChargeBindings bindings, CancellationToken cancellationToken = default(CancellationToken))
        {
            var environment = configuration.Environment == "production" ?
                              new SandboxEnvironment(configuration.ClientIdProduction, configuration.SecretProduction) :
                              new SandboxEnvironment(configuration.ClientIdSandbox, configuration.SecretSandbox);

            var client = new PayPalHttpClient(environment);

            var request = new PaymentExecuteRequest(bindings.PaymentId);

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

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

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

                var order = await this.orderService.GetByIdAsync(bindings.OrderId, cancellationToken);

                var payments = new List <OurPayment>();
                foreach (var transaction in result.Transactions)
                {
                    if (!Decimal.TryParse(transaction.Amount.Total, out decimal amount))
                    {
                        amount = 0;
                    }

                    var payment = new OurPayment()
                    {
                        Title     = "Paypal Payment",
                        Provider  = Name,
                        Reference = $"{bindings.PaymentId}",
                        Status    = PaymentStatus.Paid,
                        Date      = DateTime.UtcNow,
                        Method    = PaymentMethod.Electronic,
                        Details   = $"Payment Order #{order.Reference}: {transaction.Amount.Total} {transaction.Amount.Currency}",
                        Currency  = transaction.Amount.Currency,
                        Amount    = amount
                    };
                    payments.Add(payment);
                    await orderService.AddPayment(order, payment, cancellationToken);
                }
                return(order);
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                // TODO: better error text
                throw new AppException($"impossible to create payment, statusCode: '{statusCode}' paypal debug Id '{debugId}'");
            }
        }
示例#11
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");
            }
        }
示例#12
0
        public async Task <bool> ExecutePayment(string paypalId, string payerId)
        {
            PaymentExecuteRequest request = new PaymentExecuteRequest(paypalId);

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

            var response = await Client.Execute(request);

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

            return(result.State.ToLower() == "approved");
        }
示例#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"));
            }
        }
        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);
        }
示例#15
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!"
            });
        }
示例#16
0
        public async Task <IActionResult> PayPalHoanThanh()
        {
            var model = _context.loais.ToList();

            ViewBag.model = model;

            var paymentId = Request.Query["paymentId"];
            var payerId   = Request.Query["PayerID"];

            var environment = new SandboxEnvironment(_clientId, _secretKey);
            var client      = new PayPalHttpClient(environment);

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

            request.RequestBody(paymentExecution);

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

                var statusCode = response.StatusCode.ToString();
                if (statusCode == "OK")
                {
                    if (_orderId == 0)
                    {
                        var orderId = SessionHelper.Get <long>(HttpContext.Session, "orderId");
                        _orderId = orderId;
                    }
                    SessionHelper.Set(HttpContext.Session, "orderId", 0);

                    var oder = _context.Oders.SingleOrDefault(m => m.ID == _orderId);

                    if (oder == null)
                    {
                        return(NotFound());
                    }

                    oder.Status = true;
                    _context.Update(oder);
                    _context.SaveChanges();
                    SessionHelper.Set(HttpContext.Session, "cart", "");

                    return(View());
                }
                else
                {
                    return(Redirect("/cart/that-bai"));
                }
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                return(Redirect("/cart/that-bai"));
            }
        }