public dynamic confirmPayment(ConfirmPaymentInfo confirmPaymentInfo)
        {
            string        stripeRedirectUrl    = String.IsNullOrEmpty(confirmPaymentInfo.RedirectUrl)? GetEnvironmentConfigVar(StripeConfigKey, this.configuration.GetValue <string>(StripeConfigRedirectUrl)) + "/Home/ConfirmPayment":confirmPaymentInfo.RedirectUrl;
            var           paymentIntentService = new PaymentIntentService();
            PaymentIntent paymentIntent        = null;

            try
            {
                if (confirmPaymentInfo.PaymentIntentId != null)
                {
                    paymentIntent = paymentIntentService.Get(confirmPaymentInfo.PaymentIntentId);
                    if (paymentIntent.Status == "requires_payment_method")
                    {
                        generatePaymentResponse(paymentIntent);
                    }
                    else
                    {
                        var confirmOptions = new PaymentIntentConfirmOptions {
                            ReturnUrl = stripeRedirectUrl
                        };
                        paymentIntent = paymentIntentService.Confirm(
                            confirmPaymentInfo.PaymentIntentId,
                            confirmOptions
                            );
                    }
                }
            }
            catch (StripeException e)
            {
                return(new { error = e.StripeError.Message });
            }
            return(generatePaymentResponse(paymentIntent));
        }
Exemple #2
0
        public override void ProcessCallback(Payment payment)
        {
            InitClient(payment);
            // BH: Normally, our payment processor would "ping" this endpoint.
            // However, we're going to do it from AJAX ourselves, thus negating the need for a Stripe webhook.
            var paymentIntentId = payment.PaymentProperties.First(p => p.Key == PaymentIntentKey).Value;

            // Just confirm the payment intent exists
            var paymentIntent = PaymentIntentService.Get(paymentIntentId);

            // Firstly: does the payment intent require manual confirmation?
            if (paymentIntent.ConfirmationMethod == "manual")
            {
                try {
                    paymentIntent = PaymentIntentService.Confirm(paymentIntent.Id);
                } catch {
                    throw new InvalidOperationException("Could not confirm payment intent");
                }
            }

            if (paymentIntent.Status != StripeStatus.Succeeded)
            {
                throw new InvalidOperationException("Payment intent capture not successful");
            }

            var transaction = paymentIntent.Charges.First();

            if (transaction.Currency != payment.PurchaseOrder.BillingCurrency.ISOCode.ToLower())
            {
                throw new InvalidOperationException($"The payment currency ({payment.PurchaseOrder.BillingCurrency.ISOCode.ToUpper()}) and the currency configured for the merchant account ({transaction.Currency.ToUpper()}) doesn't match. Make sure that the payment currency matches the currency selected in the merchant account.");
            }

            var paymentStatus = PaymentStatusCode.Declined;

            if (paymentIntent.Status == StripeStatus.Succeeded)
            {
                if (string.IsNullOrEmpty(transaction.Id))
                {
                    throw new ArgumentException(@"Charge ID must be present in the PaymentIntent object.");
                }
                payment.TransactionId = paymentIntent.Id;                 // This is used for
                paymentStatus         = PaymentStatusCode.Authorized;
            }

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            HttpContext.Current.Response.StatusCode = 200;
        }
Exemple #3
0
        public string Get(int total, string currency, string customer)
        {
            total    = 50000;
            currency = "CAD";
            customer = "cus_HWhZwYCqBmCxoU";

            var intent = new PaymentIntentCreateOptions
            {
                Amount             = total,
                Currency           = currency,
                Customer           = customer,
                SetupFutureUsage   = "on_session",
                PaymentMethodTypes = new List <string>
                {
                    "card"
                },
                PaymentMethod = "pm_1GxeAPITcigAAz2yPakJ4Ce7"
            };

            var service       = new PaymentIntentService();
            var paymentIntent = service.Create(intent);

            var options = new PaymentIntentConfirmOptions
            {
                PaymentMethod = "pm_1GxeAPITcigAAz2yPakJ4Ce7",
            };
            var payment = new PaymentIntentService();

            payment.Confirm(
                paymentIntent.Id,
                options
                );

            var myClient = new clientSecret()
            {
                client_secret = paymentIntent.ClientSecret
            };

            return(JsonSerializer.Serialize <clientSecret>(myClient));
        }
        /// <inheritdoc />
        /// <exception cref="Exception">Thrown if error</exception>
        public async Task <TransactionViewModel> ConfirmIntent(ConfirmIntentBody confirmIntentBody)
        {
            var transaction =
                await ApplicationContext.Transactions.FirstOrDefaultAsync(x =>
                                                                          x.StripeIntentId == confirmIntentBody.IntentId);

            if (transaction == null)
            {
                throw new Exception("Transaction not found");
            }

            var service = new PaymentIntentService();

            try
            {
                // requests intent confirm from Stripe api
                var intent = service.Confirm(confirmIntentBody.IntentId);

                // updates transaction with Stripe response
                transaction.Updated = DateTime.Now;
                transaction.Status  = Enum.Parse <PaymentStatus>(intent.Status, true);

                // if the intent has finished set paid
                if (transaction.Status == PaymentStatus.succeeded)
                {
                    transaction.Paid = true;
                    transaction.End  = DateTime.Now;
                }

                await ApplicationContext.SaveChangesAsync();

                return(Mapper.Map <TransactionViewModel>(transaction));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <OrderPaymentIntent> CreatePaymentIntentAsync(Order_Receipt order)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var service = new PaymentIntentService();

            var options = new PaymentIntentCreateOptions
            {
                Amount             = Convert.ToInt64(order.TotalPrice) * 100,
                Currency           = "usd",
                PaymentMethodTypes = new List <string> {
                    "card"
                }
            };

            var confirmOptions = new PaymentIntentConfirmOptions
            {
                PaymentMethod = "pm_card_visa"
            };

            var intent = await service.CreateAsync(options);

            order.PaymentIntent = new OrderPaymentIntent
            {
                PaymentIndentId = intent.Id,
                ClientSecret    = intent.ClientSecret
            };
            service.Confirm(
                intent.Id,
                confirmOptions
                );

            repository.Update(order);

            return(order.PaymentIntent);
        }
Exemple #6
0
        public IActionResult Index([FromBody] ConfirmPaymentRequest request)
        {
            var           paymentIntentService = new PaymentIntentService();
            PaymentIntent paymentIntent        = null;

            try
            {
                if (request.PaymentMethodId != null)
                {
                    // Create the PaymentIntent
                    var createOptions = new PaymentIntentCreateOptions
                    {
                        PaymentMethodId    = request.PaymentMethodId,
                        Amount             = 1099,
                        Currency           = "gbp",
                        ConfirmationMethod = "manual",
                        Confirm            = true,
                    };
                    paymentIntent = paymentIntentService.Create(createOptions);
                }
                if (request.PaymentIntentId != null)
                {
                    var confirmOptions = new PaymentIntentConfirmOptions {
                    };
                    paymentIntent = paymentIntentService.Confirm(
                        request.PaymentIntentId,
                        confirmOptions
                        );
                }
            }
            catch (StripeException e)
            {
                return(Json(new { error = e.StripeError.Message }));
            }
            return(generatePaymentResponse(paymentIntent));
        }
        private string ProcessCaptureRequest(Order order, HttpRequest request, IDictionary <string, string> settings)
        {
            var apiKey = settings[settings["mode"] + "_secret_key"];

            ConfigureStripe(apiKey);

            try
            {
                var capture = settings.ContainsKey("capture") && settings["capture"].Trim().ToLower() == "true";

                PaymentIntent intent;

                var intentService = new PaymentIntentService();

                var paymentIntentId = request.Form["stripePaymentIntentId"];

                // If we don't have a stripe payment intent passed in then we create a payment
                // and try to create / capture it
                if (string.IsNullOrWhiteSpace(paymentIntentId))
                {
                    var intentOptions = new PaymentIntentCreateOptions
                    {
                        PaymentMethod = request.Form["stripePaymentMethodId"],
                        Amount        = DollarsToCents(order.TotalPrice.Value.WithVat),
                        Currency      = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId).IsoCode,
                        Description   = $"{order.CartNumber} - {order.PaymentInformation.Email}",
                        Metadata      = new Dictionary <string, string>
                        {
                            { "orderId", order.Id.ToString() },
                            { "cartNumber", order.CartNumber }
                        },
                        ConfirmationMethod = "manual",
                        Confirm            = true,
                        CaptureMethod      = capture ? "automatic" : "manual"
                    };

                    if (settings.ContainsKey("send_stripe_receipt") && settings["send_stripe_receipt"] == "true")
                    {
                        intentOptions.ReceiptEmail = order.PaymentInformation.Email;
                    }

                    intent = intentService.Create(intentOptions);

                    order.Properties.AddOrUpdate(new CustomProperty("stripePaymentIntentId", intent.Id)
                    {
                        ServerSideOnly = true
                    });
                    order.TransactionInformation.PaymentState = PaymentState.Initialized;

                    if (intent.Status != "succeeded")
                    {
                        order.Save();
                    }
                }
                // If we have a stripe payment intent then it means it wasn't confirmed first time around
                // so just try and confirm it again
                else
                {
                    intent = intentService.Confirm(request.Form["stripePaymentIntentId"], new PaymentIntentConfirmOptions
                    {
                        PaymentMethod = request.Form["stripePaymentMethodId"]
                    });
                }

                if (intent.Status == "succeeded")
                {
                    FinalizeOrUpdateOrder(order, intent);

                    return(JsonConvert.SerializeObject(new { success = true }));
                }
                else if (intent.Status == "requires_action" && intent.NextAction.Type == "use_stripe_sdk")
                {
                    return(JsonConvert.SerializeObject(new
                    {
                        requires_card_action = true,
                        payment_intent_client_secret = intent.ClientSecret
                    }));
                }

                return(JsonConvert.SerializeObject(new { error = "Invalid payment intent status" }));
            }
            catch (Exception ex)
            {
                LoggingService.Instance.Error <Stripe>("Stripe(" + order.CartNumber + ") - ProcessCaptureRequest", ex);

                return(JsonConvert.SerializeObject(new
                {
                    error = ex.Message
                }));
            }
        }
Exemple #8
0
        protected override async Task <IPaymentResponse> CreateCharge(IStripeCharge stripeChargeParameters)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(stripeChargeParameters.Token))
                {
                    if (stripeChargeParameters.IsIntentConfirm || stripeChargeParameters.Token.Contains("~"))
                    {
                        var    splitToken      = stripeChargeParameters.Token.Split('~');
                        string paymentMethodId = splitToken[1];
                        string paymentIntentId = splitToken[0];

                        var service        = new PaymentIntentService();
                        var confirmOptions = new PaymentIntentConfirmOptions();

                        PaymentIntent paymentIntent = service.Confirm(paymentIntentId, confirmOptions, new RequestOptions
                        {
                            ApiKey = GetStripeToken(stripeChargeParameters)
                        });
                        if (paymentIntent.Status == "succeeded")
                        {
                            if (paymentIntent.Status == "succeeded")
                            {
                                Transaction transactionResult = _transactionStatusUpdater.UpdateTranscationStatus(Convert.ToInt64(stripeChargeParameters.TransactionId));
                                if (stripeChargeParameters.ChannelId == Channels.Feel)
                                {
                                    try
                                    {
                                        var redemptionOrder = new Redemption_OrderDetails
                                        {
                                            AltId              = Guid.NewGuid(),
                                            ApprovedBy         = null,
                                            ApprovedUtc        = null,
                                            CreatedBy          = transactionResult.CreatedBy,
                                            CreatedUtc         = DateTime.UtcNow,
                                            IsEnabled          = false,
                                            OrderCompletedDate = null,
                                            OrderStatusId      = (int)FIL.Contracts.Enums.ApproveStatus.Pending,
                                            TransactionId      = Convert.ToInt64(stripeChargeParameters.TransactionId),
                                            UpdatedBy          = null,
                                            UpdatedUtc         = null
                                        };
                                        _orderDetailsRepository.Save(redemptionOrder);
                                        _zoomMeetingProvider.CreateMeeting(transactionResult);
                                    }
                                    catch (Exception e)
                                    {
                                        _logger.Log(LogCategory.Error, new Exception("Failed to save the redemption order", e));
                                    }
                                }
                                else if (stripeChargeParameters.ChannelId == Channels.Website)
                                {
                                    _zoomMeetingProvider.CreateMeeting(transactionResult);
                                }
                            }

                            _transactionPaymentDetailRepository.Save(new TransactionPaymentDetail
                            {
                                TransactionId    = Convert.ToInt64(stripeChargeParameters.TransactionId),
                                PaymentOptionId  = PaymentOptions.CreditCard,
                                PaymentGatewayId = PaymentGateway.Stripe,
                                RequestType      = "Charge Recieved",
                                Amount           = stripeChargeParameters.Amount.ToString(),
                                PayConfNumber    = paymentIntent.Id,
                                PaymentDetail    = "{\"Response\":" + Newtonsoft.Json.JsonConvert.SerializeObject(paymentIntent) + "}",
                            });
                            return(GetPaymentResponse(true, PaymentGatewayError.None));
                        }
                        else if ((paymentIntent.Status == "requires_source_action" || paymentIntent.Status == "requires_action") && paymentIntent.NextAction.Type == "use_stripe_sdk")
                        {
                            return(GetPaymentResponse(false, PaymentGatewayError.RequireSourceAction, PaymentGateway.Stripe, paymentIntent.ClientSecret));
                        }
                        return(GetPaymentResponse(false, GetPaymentGatewayErrorCode(paymentIntent.CancellationReason)));
                    }

                    Stripe.PaymentIntent stripeCharge = CreateStripeCharge(stripeChargeParameters);
                    if (stripeCharge != null)
                    {
                        var paymentConfirmationNumber = stripeCharge.Id;
                        if ((stripeCharge.Status == "requires_source_action" || stripeCharge.Status == "requires_action") && stripeCharge.NextAction.Type == "use_stripe_sdk")
                        {
                            return(GetPaymentResponse(false, PaymentGatewayError.RequireSourceAction, PaymentGateway.Stripe, stripeCharge.ClientSecret));
                        }

                        if (stripeCharge.Status == "succeeded")
                        {
                            Transaction transactionResult = _transactionStatusUpdater.UpdateTranscationStatus(Convert.ToInt64(stripeChargeParameters.TransactionId));
                            if (stripeChargeParameters.ChannelId == Channels.Feel)
                            {
                                try
                                {
                                    var redemptionOrder = new Redemption_OrderDetails
                                    {
                                        AltId              = Guid.NewGuid(),
                                        ApprovedBy         = null,
                                        ApprovedUtc        = null,
                                        CreatedBy          = transactionResult.CreatedBy,
                                        CreatedUtc         = DateTime.UtcNow,
                                        IsEnabled          = false,
                                        OrderCompletedDate = null,
                                        OrderStatusId      = (int)FIL.Contracts.Enums.ApproveStatus.Pending,
                                        TransactionId      = Convert.ToInt64(stripeChargeParameters.TransactionId),
                                        UpdatedBy          = null,
                                        UpdatedUtc         = null
                                    };
                                    _orderDetailsRepository.Save(redemptionOrder);
                                    _zoomMeetingProvider.CreateMeeting(transactionResult);
                                }
                                catch (Exception e)
                                {
                                    _logger.Log(LogCategory.Error, new Exception("Failed to save the redemption order", e));
                                }
                            }
                            else if (stripeChargeParameters.ChannelId == Channels.Website)
                            {
                                _zoomMeetingProvider.CreateMeeting(transactionResult);
                            }
                        }

                        _transactionPaymentDetailRepository.Save(new TransactionPaymentDetail
                        {
                            TransactionId    = Convert.ToInt64(stripeChargeParameters.TransactionId),
                            PaymentOptionId  = PaymentOptions.CreditCard,
                            PaymentGatewayId = PaymentGateway.Stripe,
                            RequestType      = "Charge Recieved",
                            Amount           = stripeChargeParameters.Amount.ToString(),
                            PayConfNumber    = stripeCharge.Id,
                            PaymentDetail    = "{\"Response\":" + Newtonsoft.Json.JsonConvert.SerializeObject(stripeCharge) + "}",
                        });

                        return(stripeCharge.Status == "succeeded" ? GetPaymentResponse(true, PaymentGatewayError.None) : GetPaymentResponse(false, GetPaymentGatewayErrorCode(stripeCharge.CancellationReason)));
                    }
                    else
                    {
                        return(GetPaymentResponse(false, PaymentGatewayError.Unknown));
                    }
                }
                else
                {
                    return(GetPaymentResponse(false, PaymentGatewayError.InvalidToken));
                }
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("Your card was declined"))
                {
                    _logger.Log(LogCategory.Error, new Exception("Failed to create charge", ex));
                }
                _transactionPaymentDetailRepository.Save(new TransactionPaymentDetail
                {
                    TransactionId    = Convert.ToInt64(stripeChargeParameters.TransactionId),
                    PaymentOptionId  = PaymentOptions.CreditCard,
                    PaymentGatewayId = PaymentGateway.Stripe,
                    RequestType      = "Charge Recieved",
                    Amount           = stripeChargeParameters.Amount.ToString(),
                    PayConfNumber    = "",
                    PaymentDetail    = "{\"Response\":" + ex.Message + "}",
                });
                return(GetPaymentResponse(false, GetPaymentGatewayErrorCode(ex.Message)));
            }
        }
        async void placeOrder(object sender, System.EventArgs e)
        {
            var request = new HttpRequestMessage();

            request.RequestUri = new Uri("http://10.0.2.2:5000/api/v1/payment");

            request.Method = HttpMethod.Get;
            var client = new HttpClient();
            MultipartFormDataContent requestContent = new MultipartFormDataContent();
            StringContent            amountContent  = new StringContent("9923", Encoding.UTF8);

            requestContent.Add(amountContent, "amount");
            request.Content = requestContent;


            HttpResponseMessage response = await client.SendAsync(request);

            StripeConfiguration.ApiKey = "pk_test_j5YImiDFgybfafp8HuEkn6Ou00JtFKI0s9";

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                HttpContent content        = response.Content;
                var         responseString = await content.ReadAsStringAsync();

                var messageObj    = JsonConvert.DeserializeObject <message>(responseString);
                var client_secret = messageObj.client_secret;

                var service    = new PaymentIntentService();
                var getOptions = new PaymentIntentGetOptions
                {
                    ClientSecret = client_secret
                };
                PaymentIntent paymentIntent = service.Get(messageObj.id, getOptions);

                //var creditCardOptions = new CreditCardOptions
                //{
                //    Number = "4000 0000 0000 9995",
                //    Cvc = "333",
                //    ExpMonth = 02,
                //    ExpYear = 24,

                //};

                var paymentMethodCardCreateOption = new PaymentMethodCardCreateOptions {
                    //Insufficiant fund
                    //Number = "4000000000009995",
                    //Payment Succeed
                    //Number = "4242424242424242",
                    //Payment Require Authentication
                    //Number = "4000002500003155",
                    Number   = CreditCardNumber.Text,
                    Cvc      = CVC.Text,
                    ExpMonth = long.Parse(ExpMonth.Text),
                    ExpYear  = long.Parse(ExpYear.Text),
                };

                //var paymentMethodDataOption = new PaymentIntentPaymentMethodDataOptions
                //{
                //    Card = paymentMethodCardCreateOption,
                //    Type = "card",

                //};
                List <String> methodTypes = new List <String>();
                methodTypes.Add("pm_card_visa");
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    //PaymentMethod = "pm_card_visa",
                    PaymentMethodData = paymentMethodDataOption,

                    ClientSecret = client_secret,
                };
                try
                {
                    var status = service.Confirm(messageObj.id, confirmOptions);
                    if (status.Status == "succeeded")
                    {
                        await DisplayAlert("Request Sent!", "Our customer service will reach out to you in 3-5 bussiness days", "OK");
                    }
                    else
                    {
                        await DisplayAlert("Failed", "Please try another card", "OK");
                    }
                }
                catch (Exception)
                {
                    await DisplayAlert("Failed", "Please try another card", "OK");
                }


                //Console.WriteLine(status.Status);
            }
        }
        public async Task <IActionResult> Stripe([FromBody] ConfirmPaymentRequest request)
        {
            var           paymentIntentService = new PaymentIntentService();
            PaymentIntent paymentIntent        = null;

            try
            {
                if (request.PaymentMethodId != null)
                {
                    //Needed objects
                    var course  = _courseService.GetCourse(request.CourseId);
                    var invoice = _paymentService.GetInvoice(request.InvoiceNumber);
                    var user    = await _context.Users.FindAsync(_access.GetUserId(User));

                    var description = "";

//            if (user == null)
//                return BadRequest(new {result = EnumList.PaymentResult.Failed.ToString(), message = "error", courseId, invoiceNumber,reason = reason.ToString()});
                    //ToDo :: Handle the return of bad request


                    decimal amountToPay = 0;

                    switch (request.Reason)
                    {
                    case EnumList.PaymentReason.Register:
                        //Check if course null
                        if (course == null) // ToDo :: Handle bad request return
                        {
                            return(BadRequest(new { userId = user.Id, result = EnumList.PaymentResult.Failed.ToString(), message = "error", request.CourseId, request.InvoiceNumber, reason = request.Reason.ToString() }));
                        }

                        //Get on register invoice
                        var registerInvoice = _paymentService.CreateOnRegisterInvoices(request.CourseId, user)
                                              .SingleOrDefault(x => x.Reason == EnumList.InvoiceReason.Registration);

                        //Determine the amount user wants to pay now
                        if (request.PayAllNow)
                        {
                            amountToPay = course.Price;
                        }
                        else
                        {
                            amountToPay = registerInvoice?.Amount ?? 0;
                        }

                        description = $"Charge for {user.FirstName} {user.LastName} - {user.Email} For Course {course.Subject}-{course.Code} Payment: {amountToPay} kr";
                        break;



                    case EnumList.PaymentReason.Invoice:
                        //Check if invoice is null
                        if (invoice == null || !invoice.ActiveInvoice())
                        {
                            return(BadRequest(new { userId = user.Id, result = EnumList.PaymentResult.Failed.ToString(), message = "error", request.CourseId, request.InvoiceNumber, reason = request.Reason.ToString() }));
                        }

                        amountToPay = invoice.CurrentAmount;
                        description = $"Betaling av {user.FirstName} {user.LastName} - Fakturanummer: {invoice.Number} - KID-nummer: {invoice.CIDNumber}";

                        break;


                    case EnumList.PaymentReason.Empty:
                    case EnumList.PaymentReason.Donate:
                    case EnumList.PaymentReason.Other:
                    default:
                        return(BadRequest(new { userId = user.Id, result = EnumList.PaymentResult.Failed.ToString(), message = "error", request.CourseId, request.InvoiceNumber, reason = request.Reason.ToString() }));
                    }


                    //ToDo :: If amount to pay is 0 return Bad Request



                    var customerOptions = new CustomerCreateOptions
                    {
                        Description   = $"{user.FirstName +" "+ user.LastName}",
                        Name          = $"{user.FirstName +" "+ user.LastName}",
                        PaymentMethod = request.PaymentMethodId,
                        Email         = $"{user.Email}",
                        Metadata      = new Dictionary <string, string>
                        {
                            { "UniqueId", $"USERID-{user.Id}-COURSE-{course.Id}-{Format.NorwayDateTimeNow().Year}" }
                        }
                    };

                    var customerService = new CustomerService();
                    var customer        = customerService.Create(customerOptions);

                    // Create the PaymentIntent
                    var createOptions = new PaymentIntentCreateOptions
                    {
                        Amount             = (int)amountToPay * 100,
                        Currency           = "nok",
                        Description        = description,
                        Customer           = customer.Id,
                        ReceiptEmail       = $"{user.Email}",
                        PaymentMethod      = request.PaymentMethodId,
                        ConfirmationMethod = "manual",
                        Confirm            = true,
                    };
                    paymentIntent = paymentIntentService.Create(createOptions);

                    var initiatedOrder = new InitiatedOrder
                    {
                        Id     = paymentIntent.Id, User = user, CourseId = request.CourseId, InvoiceNumber = request.InvoiceNumber,
                        Amount = amountToPay, PaymentMethod = EnumList.PaymentMethod.Stripe, Reason = request.Reason, Status = EnumList.OrderStatus.Initiated,
                        Ip     = request.Ip, OperatingSystem = request.OperatingSystem, DeviceType = request.DeviceType, AuthCookies = request.AuthCookies, PayAllNow = request.PayAllNow
                    };
                    await _context.AddAsync(initiatedOrder);

                    await _context.SaveChangesAsync();
                }
                if (request.PaymentIntentId != null)
                {
                    var confirmOptions = new PaymentIntentConfirmOptions {
                    };
                    paymentIntent = paymentIntentService.Confirm(
                        request.PaymentIntentId,
                        confirmOptions
                        );
                }
            }
            catch (StripeException e)
            {
                return(Json(new { error = e.StripeError.Message }));
            }
            return(GeneratePaymentResponse(paymentIntent));
        }
        public async Task <ActionResult <StripeResult> > Post([FromBody] StripeCharge request)
        {
            StripeConfiguration.ApiKey = StripeApiKey;

            PaymentIntentService service = new PaymentIntentService();
            PaymentIntent        paymentIntent;
            StripeResult         result = new StripeResult();
            Order order = _context.orders.Find(request.CartId);

            // First pass
            if (request.PaymentMethodId != null)
            {
                PaymentIntentCreateOptions options = new PaymentIntentCreateOptions
                {
                    PaymentMethod      = request.PaymentMethodId,
                    Amount             = request.TotalCost,
                    Currency           = "nok",
                    Description        = "Purchase from VippsCase.",
                    ConfirmationMethod = "manual",
                    Confirm            = true,
                };

                try
                {
                    paymentIntent = service.Create(options, new RequestOptions
                    {
                        IdempotencyKey = order.IdempotencyToken
                    });

                    // Check the user making the purchase
                    User user;
                    if (request.UserId == -1)
                    {
                        // Adding a new customer if one was not specified in the request
                        user = new User
                        {
                            Name           = request.CustomerDetails.FullName,
                            AddressLineOne = request.CustomerDetails.AddressLineOne,
                            AddressLineTwo = request.CustomerDetails.AddressLineTwo,
                            County         = request.CustomerDetails.County,
                            PostalCode     = request.CustomerDetails.PostalCode,
                            City           = request.CustomerDetails.City,
                            Country        = request.CustomerDetails.Country,
                            PhoneNumber    = request.CustomerDetails.PhoneNumber,
                            Email          = request.CustomerDetails.Email
                        };

                        // Storing our customer details.
                        _context.users.Add(user);
                    }
                    else
                    {
                        // Find the user matching the userId and add them to the order.
                        user = _context.users.Find(request.UserId);
                    }

                    // Setting the user and charge to the user we just made and the charge token.
                    order.StripeChargeToken = paymentIntent.Id;
                    order.UserId            = user.UserId;

                    // Saving all of our changes.
                    await _context.SaveChangesAsync();
                }
                catch (StripeException exception)
                {
                    // Idempotency special handling
                    if (exception.StripeError.ErrorType == "idempotency_error" ||
                        exception.StripeError.DeclineCode == "duplicate_transaction" ||
                        exception.StripeError.Code == "duplicate_transaction")
                    {
                        result.Success = true;
                    }
                    else
                    {
                        // When an order fails due to an issue with stripe,
                        // we'll assign the order a new idempotency key to prevent the "idempotency_error" from stripe.
                        order.IdempotencyToken = Guid.NewGuid().ToString();
                        await _context.SaveChangesAsync();

                        // Return the error message to the user.
                        result.Success = false;
                        result.Error   = _stripeErrorHandler.ErrorHandler(exception);
                    }
                    return(result);
                }
            }
            // Second pass
            else
            {
                PaymentIntentConfirmOptions options = new PaymentIntentConfirmOptions {
                };
                try
                {
                    paymentIntent = service.Confirm(request.PaymentIntentId, options);
                }
                catch (StripeException exception)
                {
                    // When an order fails due to an issue with stripe,
                    // we'll assign the order a new idempotency key to prevent the "idempotency_error" from stripe.
                    order.IdempotencyToken = Guid.NewGuid().ToString();
                    await _context.SaveChangesAsync();

                    // Return the error message to the user.
                    result.Success = false;
                    result.Error   = _stripeErrorHandler.ErrorHandler(exception);
                    return(result);
                }
            }

            switch (paymentIntent.Status)
            {
            case "requires_action" when paymentIntent.NextAction.Type == "use_stripe_sdk":
                // Tell the client to handle the action
                result.Data = new
                {
                    requires_action = true,
                    payment_intent_client_secret = paymentIntent.ClientSecret
                };
                result.Success = false;
                break;

            case "succeeded":
                // The payment didn't need any additional actions and completed!
                // Handle post-payment fulfillment
                result.Success = true;
                break;

            default:
                // Invalid status
                // TODO: Change this error message to be user-friendly
                result.Error   = "Invalid PaymentIntent status";
                result.Success = false;
                break;
            }

            return(result);
        }
Exemple #12
0
        static void Main(string[] args)
        {
            StripeConfiguration.ApiKey = "sk_test_XkvAeMDMkmENwnuctwQxesT3";

            //InvoiceService invoiceService = new InvoiceService();
            //Invoice invoice = invoiceService.Get("in_1ET2FYIH9mcFLxLz31AUOYQF");
            //string invoiceSerialized = JsonConvert.SerializeObject(invoice);

            //ChargeService stripeChargeService = new ChargeService();
            //Charge stripeCharge = stripeChargeService.Get(invoice.ChargeId);
            //string chargeSerialized = JsonConvert.SerializeObject(stripeCharge);

            CustomerService customerService = new CustomerService();
            Customer        customer        = customerService.Get("cus_GXpkRhKeV60Bzr");

            Subscription subscription = customer.Subscriptions.First();

            string paymentMethodId = subscription.DefaultPaymentMethodId;
            //CustomerUpdateOptions customerUpdateOptions = new CustomerUpdateOptions()
            //{
            //    InvoiceSettings = new CustomerInvoiceSettingsOptions()
            //    {
            //        DefaultPaymentMethod = paymentMethodId
            //    },
            //};
            //customerService.Update(customer.Id, customerUpdateOptions);


            //PaymentMethodAttachOptions paymentMethodAttachOptions = new PaymentMethodAttachOptions()
            //{
            //    Customer = customer.Id
            //};

            //var service = new PaymentMethodService();
            //service.Attach(paymentMethodId, paymentMethodAttachOptions);


            InvoiceService invoiceService = new InvoiceService();

            //InvoiceItemCreateOptions invoiceItemCreateOptions = new InvoiceItemCreateOptions
            //{
            //    Customer = customer.Id,
            //    Amount = 10000,
            //    Currency = "eur",
            //    Description = "Testing invoice payment",
            //};

            //InvoiceItemService invoiceItemService = new InvoiceItemService();
            //invoiceItemService.Create(invoiceItemCreateOptions);

            //InvoiceCreateOptions invoiceCreateOptions = new InvoiceCreateOptions
            //{
            //    Customer = customer.Id,
            //    AutoAdvance = true,
            //};
            //Invoice prorateInvoice = invoiceService.Create(invoiceCreateOptions);
            //invoiceService.FinalizeInvoice("in_1G0l5CIH9mcFLxLzAYcq1h4m");


            Invoice invoice = invoiceService.Get("in_1G0lh0IH9mcFLxLzGQrSg264");

            PaymentIntentConfirmOptions paymentIntentConfirmOptions = new PaymentIntentConfirmOptions()
            {
                PaymentMethod = paymentMethodId,
            };
            PaymentIntentService paymentIntentService = new PaymentIntentService();

            paymentIntentService.Confirm(invoice.PaymentIntentId, paymentIntentConfirmOptions);

            string s = "" + "";
        }
        public override int ThreeDSecurePayment(Payment payment, Uri postBackURL, string languageCode = "", string languageDialectCode = "")
        {
            int    ret = 10;
            string url = "";

            err = "";

            try
            {
                StripeConfiguration.ApiKey = payment.ProviderPassword;                 // Secret key

                if (postBackURL == null)
                {
                    url = Tools.ConfigValue("SystemURL");
                }
                else
                {
                    url = postBackURL.GetLeftPart(UriPartial.Authority);
                }
                if (!url.EndsWith("/"))
                {
                    url = url + "/";
                }
                d3Form = "";
                ret    = 20;
                url    = url + "RegisterThreeD.aspx?ProviderCode=" + bureauCode
                         + "&TransRef=" + Tools.XMLSafe(payment.MerchantReference);

                ret = 50;
                var paymentMethodOptions = new PaymentMethodCreateOptions
                {
                    Type = "card",
                    Card = new PaymentMethodCardOptions
                    {
                        Number   = payment.CardNumber,
                        ExpMonth = payment.CardExpiryMonth,
                        ExpYear  = payment.CardExpiryYear,
                        Cvc      = payment.CardCVV
                    }
                };
                ret = 60;
                var paymentMethodService = new PaymentMethodService();
                var paymentMethod        = paymentMethodService.Create(paymentMethodOptions);
                err = err + ", paymentMethodId=" + Tools.NullToString(paymentMethod.Id);

                ret = 70;
                var customerOptions = new CustomerCreateOptions
                {
                    Name          = payment.CardName,                     // (payment.FirstName + " " + payment.LastName).Trim(),
                    Email         = payment.EMail,
                    Phone         = payment.PhoneCell,
                    PaymentMethod = paymentMethod.Id
                };
                ret = 80;
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerOptions);
                err = err + ", customerId=" + Tools.NullToString(customer.Id);

//				if ( payment.PaymentDescription.Length < 1 )
//					payment.PaymentDescription = "CareAssist";
//				else if ( payment.PaymentDescription.Length > 22 )
//					payment.PaymentDescription = payment.PaymentDescription.Substring(0,22);

//	Stripe needs a minimum payment of 50 US cents
                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount              = 050,                         // payment.PaymentAmount,
                    Currency            = "usd",                       // payment.CurrencyCode.ToLower(), // Must be "usd" not "USD"
                    StatementDescriptor = payment.PaymentDescriptionLeft(22),
                    Customer            = customer.Id,
                    PaymentMethod       = paymentMethod.Id,
                    Description         = payment.MerchantReference,
                    ConfirmationMethod  = "manual"
                };
                ret = 40;
                var paymentIntentService = new PaymentIntentService();
                var paymentIntent        = paymentIntentService.Create(paymentIntentOptions);
                err = err + ", paymentIntentId=" + Tools.NullToString(paymentIntent.Id);

                ret = 50;
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    PaymentMethod = paymentMethod.Id,
                    ReturnUrl     = url
                };
                ret = 60;
                var paymentConfirm = paymentIntentService.Confirm(paymentIntent.Id, confirmOptions);
                payRef = paymentConfirm.Id;
                err    = err + ", paymentConfirmId=" + Tools.NullToString(payRef);

                ret        = 70;
                strResult  = paymentConfirm.StripeResponse.Content;
                d3Form     = Tools.JSONValue(strResult, "url", "next_action");
                d3Form     = Tools.JSONRaw(d3Form);
                resultMsg  = Tools.JSONValue(strResult, "status");
                ret        = 80;
                resultCode = paymentConfirm.StripeResponse.ToString();
                int k = resultCode.ToUpper().IndexOf(" STATUS=");
                err = err + ", StripeResponse=" + Tools.NullToString(resultCode);
                ret = 90;

                Tools.LogInfo("ThreeDSecurePayment/60", "strResult=" + strResult, 221, this);

                string sql = "exec sp_WP_PaymentRegister3DSecA @ContractCode=" + Tools.DBString(payment.MerchantReference)
                             + ",@ReferenceNumber=" + Tools.DBString(payRef)
                             + ",@Status='77'";                                               // Means payment pending
                if (languageCode.Length > 0)
                {
                    sql = sql + ",@LanguageCode=" + Tools.DBString(languageCode);
                }
                if (languageDialectCode.Length > 0)
                {
                    sql = sql + ",@LanguageDialectCode=" + Tools.DBString(languageDialectCode);
                }
                using (MiscList mList = new MiscList())
                    mList.ExecQuery(sql, 0, "", false, true);

                Tools.LogInfo("ThreeDSecurePayment/80", "PayRef=" + payRef + "; SQL=" + sql + "; " + d3Form, 10, this);
                return(0);
            }
            catch (Exception ex)
            {
                Tools.LogException("ThreeDSecurePayment/99", "Ret=" + ret.ToString(), ex, this);
            }
            return(ret);
        }
        public override int TokenPayment(Payment payment)
        {
            if (!EnabledFor3d(payment.TransactionType))
            {
                return(590);
            }

            int ret = 610;

            payRef     = "";
            strResult  = "";
            err        = "";
            resultMsg  = "Fail";
            resultCode = "981";

            Tools.LogInfo("TokenPayment/10", "Merchant Ref=" + payment.MerchantReference, 10, this);

            try
            {
                ret = 620;
                StripeConfiguration.ApiKey = payment.ProviderPassword;                 // Secret key

                ret = 624;
                err = err + ", customerId=" + Tools.NullToString(payment.CustomerID)
                      + ", paymentMethodId=" + Tools.NullToString(payment.PaymentMethodID)
                      + ", tokenId=" + Tools.NullToString(payment.CardToken);
                ret = 630;
                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount              = payment.PaymentAmount,
                    Currency            = payment.CurrencyCode.ToLower(),                     // Must be "usd" not "USD"
                    StatementDescriptor = payment.PaymentDescriptionLeft(22),
                    Customer            = payment.CustomerID,
                    PaymentMethod       = payment.PaymentMethodID,
                    Description         = payment.MerchantReference,
                    ConfirmationMethod  = "manual"
//					SetupFutureUsage    = "off_session",
//					Confirm             = true,
//					PaymentMethodData   = new PaymentIntentPaymentMethodDataOptions
//					{
//						Type = "card"
//					},
                };

//	Create a separate mandate
//				string mandateId = "";
//				if ( payment.MandateDateTime > Constants.DateNull && payment.MandateIPAddress.Length > 2 )
//				{
//					ret         = 640;
//					var mandate = new Mandate
//					{
//						CustomerAcceptance = new MandateCustomerAcceptance
//						{
//							AcceptedAt = payment.MandateDateTime,
//							Online     = new MandateCustomerAcceptanceOnline
//							{
//								IpAddress = payment.MandateIPAddress,
//								UserAgent = payment.MandateBrowser
//							}
//						}
//					};
//					mandateId = mandate.Id;
//					err       = err + ", mandateId="+Tools.NullToString(mandateId);
//				}
//				else
//					err       = err + ", No mandate";

                ret = 690;
                var paymentIntentService = new PaymentIntentService();
                var paymentIntent        = paymentIntentService.Create(paymentIntentOptions);
                err = err + ", paymentIntentId=" + Tools.NullToString(paymentIntent.Id);

                ret = 700;
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    PaymentMethod = payment.PaymentMethodID,
                    OffSession    = true
//					Mandate       = mandateId
//					MandateData   = new PaymentIntentMandateDataOptions
//					{
//						CustomerAcceptance = new PaymentIntentMandateDataCustomerAcceptanceOptions
//						{
//							AcceptedAt = payment.MandateDateTime,
//							Online     = new PaymentIntentMandateDataCustomerAcceptanceOnlineOptions
//							{
//								IpAddress = payment.MandateIPAddress,
//								UserAgent = payment.MandateBrowser
//							}
//						}
//					}
                };

                if (payment.MandateDateTime > Constants.DateNull && payment.MandateIPAddress.Length > 2)
                {
                    ret = 710;
                    confirmOptions.MandateData = new PaymentIntentMandateDataOptions
                    {
                        CustomerAcceptance = new PaymentIntentMandateDataCustomerAcceptanceOptions
                        {
                            AcceptedAt = payment.MandateDateTime,
                            Type       = "online",
                            Online     = new PaymentIntentMandateDataCustomerAcceptanceOnlineOptions
                            {
                                IpAddress = payment.MandateIPAddress,
                                UserAgent = payment.MandateBrowser
                            }
                        }
                    };
                }

                ret = 720;
                var paymentConfirm = paymentIntentService.Confirm(paymentIntent.Id, confirmOptions);
                payRef = paymentConfirm.Id;
                err    = err + ", paymentConfirmId=" + Tools.NullToString(payRef);

                ret        = 730;
                strResult  = paymentConfirm.StripeResponse.Content;
                resultMsg  = Tools.JSONValue(strResult, "status");
                resultCode = paymentConfirm.StripeResponse.ToString();
                int k = resultCode.ToUpper().IndexOf(" STATUS=");
                ret = 740;
                err = err + ", StripeResponse=" + Tools.NullToString(resultCode);

                if (k > 0)
                {
                    ret        = 750;
                    resultCode = resultCode.Substring(k + 8).Trim();
                    k          = resultCode.IndexOf(" ");
                    if (k > 0)
                    {
                        resultCode = resultCode.Substring(0, k);
                    }
                }
                else
                {
                    resultCode = "989";
                }

                ret = 760;
                err = err + ", strResult=" + Tools.NullToString(strResult)
                      + ", resultCode=" + Tools.NullToString(resultCode);
//				mandate              = null;
                paymentIntentService = null;
                paymentIntent        = null;
                confirmOptions       = null;
                paymentConfirm       = null;

                if (!resultCode.StartsWith("2") || payRef.Length < 1)
                {
                    resultCode = (resultMsg.Length > 0 ? resultMsg : "Fail");
                    //	resultCode = "Fail/" + resultCode + ( resultMsg.Length > 0 ? " : " + resultMsg : "" );
                    Tools.LogInfo("TokenPayment/197", "Ret=" + ret.ToString() + err, 231, this);
                }
                else if (resultMsg.ToUpper().StartsWith("SUCCE") || resultMsg.Length == 0)
                {
                    ret        = 0;
                    resultCode = "Success";
                    //	resultCode = "Success/" + resultCode;
                    //	Tools.LogInfo ("TokenPayment/189","Ret=0" + err,255,this);
                }
                else
                {
                    resultCode = resultMsg;
                }
            }
            catch (Exception ex)
            {
                resultCode = ex.Message;
                //	resultCode = "Fail/" + ret.ToString() + " : " + ex.Message + ( resultMsg.Length > 0 ? " (" + resultMsg + ")" : "" );
                err = "Ret=" + ret.ToString() + err;
                Tools.LogInfo("TokenPayment/198", err, 231, this);
                Tools.LogException("TokenPayment/199", err, ex, this);
            }
            return(ret);
        }
Exemple #15
0
        static void Main(string[] args)
        {
            Console.Write("Enter seret key: ");
            StripeConfiguration.ApiKey = Console.ReadLine();

            Console.Write("Enter customer email: ");
            string email = Console.ReadLine();

            // Create a customer
            var customer = Helper.CreateCustomer(email);

            var paymentMethodService = new PaymentMethodService();
            var paymentIntentService = new PaymentIntentService();

            Console.WriteLine(@"Create Transaction\Payment Intent:");

            long amount = 0;

            Console.Write("Enter Amount (lowest denominator of currency):");
            while (!long.TryParse(Console.ReadLine(), out amount))
            {
                Console.WriteLine("Entered amount value cannot be converted to numeric. Please Try again.");
                Console.Write("Enter Amount (lowest denominator of currency):");
            }

            Console.Write("Enter Currency (3 Letter ISO):");
            string currency = Console.ReadLine();

            //Create a paymentIntent/TransactionIntent for the customer
            var intent = Helper.CreatePaymentIntent(amount, currency, customer, paymentIntentService);

            Console.WriteLine($"Intent has been create with client secret: '{intent.ClientSecret}'.\nTo verify please check the Stripe payments dashboard.");
            Console.Write("You can exit the program now. Use the web server to complete the request via Stripe Elements. Or if you want to add the payment method here, you can press any key to coninue.");
            Console.ReadLine();
            return;

            //If you want to add the payment method here
            Console.WriteLine("Do you want to enter a payment method? (y/n)");
            char response = Console.ReadLine().Single();

            if (response == 'y' || response == 'Y')
            {
                Console.WriteLine("Enter Card Details:");
                Console.Write("Enter Card Number: ");
                string cardNumber = Console.ReadLine();

                Console.Write("CVC: ");
                string cvc = Console.ReadLine();

                Console.Write("Expiry (month):");
                long expMonth = long.Parse(Console.ReadLine());

                Console.Write("Expiry (year):");
                long expYear = long.Parse(Console.ReadLine());

                // Create and attach payment method to customer
                var cardPaymentMethod = Helper.CreateCardPaymentMethod(cardNumber, expMonth, expYear, cvc, paymentMethodService);
                Helper.AttachPaymentMethod(customer, cardPaymentMethod, paymentMethodService);

                // Retrieve the paymentintent/transactionIntent for a customer
                var paymentIntents = paymentIntentService.List(
                    new PaymentIntentListOptions
                {
                    Customer = customer.Id,
                })
                                     .OrderBy(x => x.Created).ToList();

                // Confirm the transaction
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    PaymentMethod = cardPaymentMethod.Id,
                };

                paymentIntentService.Confirm(intent.Id, confirmOptions);
                //paymentIntentService.Confirm(paymentIntents.Last().Id, confirmOptions);
            }

            return;
        }
Exemple #16
0
        public async Task <IActionResult> OnPostChargeAsync(string stripeEmail, string stripeToken)
        {
            HttpClient          client = _api.Initial();
            HttpResponseMessage res    = await client.GetAsync("api/CartDetails/" + CartDetailDTO.MemberID + "/GetCartDetailById");

            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                CartDetailDTO = JsonConvert.DeserializeObject <UserCartDetailDTO>(result);
            }

            if (!res.IsSuccessStatusCode || !ModelState.IsValid)
            {
                ViewData["Error"] = ERROR_MSG;
                return(Page());
            }

            try
            {
                decimal totalPrice = CartDetailDTO.TotalPrice;

                var customerOptions = new CustomerCreateOptions
                {
                    Email  = stripeEmail,
                    Source = stripeToken,
                };
                var customer = new CustomerService().Create(customerOptions);

                //var paymentMethodOptions = new PaymentMethodCreateOptions
                //{
                //    Type = "card",
                //    Card = new PaymentMethodCardOptions
                //    {
                //        Number = "4242424242424242",
                //        ExpMonth = 4,
                //        ExpYear = 2022,
                //        Cvc = "314",
                //    },
                //};
                //var paymentMethod = new PaymentMethodService().Create(paymentMethodOptions);

                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount       = (long)(totalPrice * 100),
                    Currency     = "usd",
                    Description  = "Test Payment",
                    Customer     = customer.Id,
                    ReceiptEmail = stripeEmail,
                    Metadata     = new Dictionary <string, string>()
                    {
                        { "Country", CartInputModel.Country },
                        { "State", CartInputModel.State },
                        { "Postcode", CartInputModel.Postcode },
                    },
                    PaymentMethod = "pm_card_visa",
                };

                var           service       = new PaymentIntentService();
                PaymentIntent paymentIntent = service.Create(paymentIntentOptions);

                var order = new EcommerceWebApi.Models.Order();

                order.MemberID   = CartDetailDTO.MemberID;
                order.PaymentID  = paymentIntent.Id;
                order.OrderDate  = DateTime.Now;
                order.Country    = CartInputModel.Country;
                order.State      = CartInputModel.State;
                order.PostCode   = CartInputModel.Postcode;
                order.Status     = "To Ship";
                order.StatusDesc = "Waiting to be shipped out.";
                order.TotalPrice = totalPrice;

                bool stockSufficient            = true;
                List <OrderDetail> orderDetails = new List <OrderDetail>();
                foreach (var item in CartDetailDTO.CartDetails)
                {
                    orderDetails.Add(new OrderDetail
                    {
                        Quantity         = item.Quantity,
                        VariantID        = item.VariantID,
                        ProductName      = item.Variant.Product.ProductName,
                        ProductPrice     = item.Variant.Product.Price,
                        ProductImagePath = item.Variant.Product.ProductImages.FirstOrDefault().Path,
                        VariantType      = item.Variant.Type
                    });

                    HttpResponseMessage variant_res = await client.PutAsync("api/Action/UpdateVariantQuantity/" + item.VariantID + "/" + item.Quantity, new StringContent(
                                                                                JsonConvert.SerializeObject(order, new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }), Encoding.UTF8, MediaTypeNames.Application.Json));

                    if (variant_res.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        var result = variant_res.Content.ReadAsStringAsync().Result;
                        if (result.Equals("Out of stock"))
                        {
                            item.Variant.Stock = 0;
                            stockSufficient    = false;
                            //CartDetailDTO.CartDetails.Remove(item);
                            //CartDetailDTO.TotalPrice = CartDetailDTO.CartDetails.Sum(cd => cd.Quantity * cd.Variant.Product.Price);
                            //ViewData["Error"] = OUT_OF_STOCK_MSG;
                        }
                    }
                }

                if (!stockSufficient)
                {
                    service.Cancel(paymentIntent.Id);
                    return(Page());
                }

                order.OrderDetails = orderDetails;

                HttpResponseMessage insert_res = await client.PostAsync("api/Orders", new StringContent(
                                                                            JsonConvert.SerializeObject(order, new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                }), Encoding.UTF8, MediaTypeNames.Application.Json));

                HttpResponseMessage delete_res = await client.DeleteAsync("api/Action/DeleteCart/" + CartDetailDTO.MemberID);

                if (insert_res.IsSuccessStatusCode && delete_res.IsSuccessStatusCode)
                {
                    paymentIntent = service.Confirm(paymentIntent.Id);
                }

                if (paymentIntent.Status == "succeeded")
                {
                    _logger.LogInformation("Order is successfully made by {user_email} with PaymentID >> {payment_id}", stripeEmail, paymentIntent.Id);
                    return(RedirectToPage("My-purchase"));
                }
                else
                {
                    service.Cancel(paymentIntent.Id);
                }
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex.ToString());
            }

            ViewData["Error"] = ERROR_MSG;
            return(Page());
        }