コード例 #1
0
        private void CancelPaymentIntent(string paymentIntentId)
        {
            StripeConfiguration.ApiKey = ApiSecretKey;
            var service = new PaymentIntentService();

            service.Cancel(paymentIntentId);
        }
コード例 #2
0
        public string Refund(string toggleRefund)
        {   //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
            //sk_test_51Gzaa1HAh8lBnQxza9cOAzY7LbfgQ4FWX2sYqiuHsoVWJg4mNDppueQkAVd0XIPU4GhcrNBca8aemNgr24m4jDv200ooFw0Bhz
            StripeConfiguration.ApiKey = "sk_test_51Gzaa1HAh8lBnQxza9cOAzY7LbfgQ4FWX2sYqiuHsoVWJg4mNDppueQkAVd0XIPU4GhcrNBca8aemNgr24m4jDv200ooFw0Bhz";
            var msg = "";

            if (toggleRefund == "refund")
            {
                var refunds       = new RefundService();
                var refundOptions = new RefundCreateOptions
                {
                    PaymentIntent = "pi_1GzxFMHAh8lBnQxzpA2OSATN"
                };
                var refund = refunds.Create(refundOptions);
                msg = "Payment refunded successfully";
            }

            else if (toggleRefund == "cancelRefund")
            {
                var service = new PaymentIntentService();
                var options = new PaymentIntentCancelOptions {
                };
                var intent  = service.Cancel("pi_1GzxFMHAh8lBnQxzpA2OSATN", options);
                msg = "Payment refund cancelled";
            }
            //ViewBag.message = msg;
            return(msg);
        }
コード例 #3
0
        public PaymentIntent Cancel(string paymentId,
                                    string userId,
                                    long orderId,
                                    long transactionId,
                                    Guid correlationId)
        {
            var service = new PaymentIntentService();
            var options = new PaymentIntentCancelOptions {
            };

            var intent = service.Cancel(paymentId, options);

            return(intent);
        }
コード例 #4
0
        // Contacts Stripe, cancels intent and removes transaction
        private async Task Cancel(ApplicationContext context, string id, Guid eventId, Guid ticketId)
        {
            var transaction = await context.Transactions.FirstOrDefaultAsync(x => x.StripeIntentId == id);

            var ticket = await context.Tickets.FirstOrDefaultAsync(x => x.Id == ticketId);

            var @event = await context.Events.FirstOrDefaultAsync(x => x.Id == eventId);

            if (@event == null)
            {
                return;
            }

            if (transaction == null)
            {
                return;
            }

            if (ticket == null)
            {
                return;
            }

            transaction.End     = DateTime.Now;
            transaction.Status  = PaymentStatus.canceled;
            transaction.Ticket  = null;
            transaction.Updated = DateTime.Now;

            ticket.User        = null;
            ticket.Available   = true;
            ticket.Transaction = null;

            @event.TicketsLeft++;

            var service = new PaymentIntentService();

            try
            {
                Logger.LogInformation("Canceling the intent");
                service.Cancel(transaction.StripeIntentId);

                await context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Logger.LogWarning(e.Message);
            }
        }
コード例 #5
0
        protected override bool CancelPaymentInternal(Payment payment, out string status)
        {
            InitClient(payment);
            var paymentIntentId = payment.PaymentProperties.First(p => p.Key == PaymentIntentKey).Value;
            var paymentIntent   = PaymentIntentService.Get(paymentIntentId);

            if (paymentIntent.Status == StripeStatus.Succeeded)
            {
                throw new InvalidOperationException("Cannot cancel a payment that has already been captured");
            }

            var result = PaymentIntentService.Cancel(paymentIntent.Id);

            status = result.Status;
            return(result.Status == StripeStatus.Canceled);
        }
コード例 #6
0
        public override ApiResult CancelPayment(OrderReadOnly order, StripeCheckoutSettings settings)
        {
            // NOTE: Subscriptions aren't currently abled to be "authorized" so the cancel
            // routine shouldn't be relevant for subscription payments at this point

            try
            {
                // See if there is a payment intent to cancel
                var stripePaymentIntentId = order.Properties["stripePaymentIntentId"];
                if (!string.IsNullOrWhiteSpace(stripePaymentIntentId))
                {
                    var secretKey = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey;

                    ConfigureStripe(secretKey);

                    var paymentIntentService = new PaymentIntentService();
                    var intent = paymentIntentService.Cancel(stripePaymentIntentId);

                    return(new ApiResult()
                    {
                        TransactionInfo = new TransactionInfoUpdate()
                        {
                            TransactionId = GetTransactionId(intent),
                            PaymentStatus = GetPaymentStatus(intent)
                        }
                    });
                }

                // If there is a charge, then it's too late to cancel
                // so we attempt to refund it instead
                var chargeId = order.Properties["stripeChargeId"];
                if (chargeId != null)
                {
                    return(RefundPayment(order, settings));
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <StripeCheckoutOneTimePaymentProvider>(ex, "Stripe - CancelPayment");
            }

            return(ApiResult.Empty);
        }
コード例 #7
0
        //When user wants to cancel the payment
        public ActionResult CancelPayment(int id)
        {
            StripeConfiguration.ApiKey = "sk_test_T3BF2ap8TTDpmetCKxF038r400HAf7zrj8";

            Donation removedDonation = db.Donations.Find(id);

            //Cancel the Payment
            var service = new PaymentIntentService();

            service.Cancel(removedDonation.donationReceiptId);

            //Delete the Donation from the table
            db.Donations.Remove(removedDonation);

            //Save the changes on the database
            db.SaveChanges();

            //Go back to the list of Donation
            return(RedirectToAction("Index"));
        }
コード例 #8
0
        public override ApiInfo CancelPayment(Order order, IDictionary <string, string> settings)
        {
            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("mode", "settings");
                settings.MustContainKey(settings["mode"] + "_secret_key", "settings");

                // Try canceling the payment intent
                var stripePaymentIntentId = order.Properties["stripePaymentIntentId"];
                if (!string.IsNullOrWhiteSpace(stripePaymentIntentId))
                {
                    var apiKey = settings[settings["mode"] + "_secret_key"];

                    ConfigureStripe(apiKey);

                    var service = new PaymentIntentService();
                    var options = new PaymentIntentCancelOptions();
                    var intent  = service.Cancel(stripePaymentIntentId, options);

                    return(new ApiInfo(GetTransactionId(intent), GetPaymentState(intent)));
                }

                // If there is a transaction ID (a charge) then it's too late to cancel
                // so we just attempt to refund it
                if (order.TransactionInformation.TransactionId != null)
                {
                    return(RefundPayment(order, settings));
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <Stripe>("Stripe(" + order.OrderNumber + ") - RefundPayment", exp);
            }

            return(null);
        }
コード例 #9
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());
        }