EL02
EL02

Reputation: 322

How to check if payment was successful or not Stripe ASP.NET

public ActionResult Index()
      {
          StripeConfiguration.ApiKey = "secretKey";

          var options = new SessionCreateOptions
          {
              PaymentMethodTypes = new List<string> {
              "card",
          },
          LineItems = new List<SessionLineItemOptions> {
          new SessionLineItemOptions {
          Name = "Basic Plan",
          Description = "Up to 1 Featured Product",
          Amount = 1000,
          Currency = "usd",
          Quantity = 1,
      },
  },
              SuccessUrl = "https://localhost:44390/payment/successful",
              CancelUrl = "https://localhost:44390/payment/fail",
              PaymentIntentData = new SessionPaymentIntentDataOptions
              {
                  Metadata = new Dictionary<string, string>
                  {
                      {"Order_ID", "123456" },
                      {"Description", "Basic Plan" }
                  }
              }
          };

          var service = new SessionService();
          Session session = service.Create(options);
          return PartialView("_PaymentIndex", session);
      }

Is there any way of checking the status of the payment, because I wanna call another action if the payment is confirmed. Like the same as adding a successful url, but for an action. I'm kinda new to this so :/

Edit:

I added a webhook to https://xxxx.eu.ngrok.io/payment/UpdatePaymentStatus for this action:

 [HttpPost]
        public ActionResult UpdatePaymentStatus()
        {
            try
            {
                StripeConfiguration.ApiKey = "key";
                Stream req = Request.InputStream;
                req.Seek(0, System.IO.SeekOrigin.Begin);
                string json = new StreamReader(req).ReadToEnd();
                myLogger.GetInstance().Warning(User.Identity.Name, "| Check |", "Payment/UpdatePaymentStatus");

                // Get all Stripe events.
                var stripeEvent = EventUtility.ParseEvent(json);
                string stripeJson = stripeEvent.Data.RawObject + string.Empty;
                var childData = Charge.FromJson(stripeJson);
                var metadata = childData.Metadata;

                int orderID = -1;
                string strOrderID = string.Empty;
                if (metadata.TryGetValue("Order_ID", out strOrderID))
                {
                    int.TryParse(strOrderID, out orderID);
                    // Find your order from database.
                    // For example:
                    // Order order = db.Order.FirstOrDefault(x=>x.ID == orderID);

                }

                switch (stripeEvent.Type)
                {
                    case Events.ChargeCaptured:
                    case Events.ChargeFailed:
                    case Events.ChargePending:
                    case Events.ChargeRefunded:
                    case Events.ChargeSucceeded:
                    case Events.ChargeUpdated:
                        var charge = Charge.FromJson(stripeJson);
                        string amountBuyer = ((double)childData.Amount / 100.0).ToString();
                        if (childData.BalanceTransactionId != null)
                        {
                            long transactionAmount = 0;
                            long transactionFee = 0;
                            if (childData.BalanceTransactionId != null)
                            {
                                // Get transaction fee.
                                var balanceService = new BalanceTransactionService();
                                BalanceTransaction transaction = balanceService.Get(childData.BalanceTransactionId);
                                transactionAmount = transaction.Amount;
                                transactionFee = transaction.Fee;
                            }

                            // My status, it is defined in my system.
                            int status = 0; // Wait

                            double transactionRefund = 0;

                            // Set order status.
                            if (stripeEvent.Type == Events.ChargeFailed)
                            {
                                status = -1; // Failed
                                myLogger.GetInstance().Warning(User.Identity.Name, "| Purchase of basic plan failed |", "Payment/UpdatePaymentStatus");

                            }
                            if (stripeEvent.Type == Events.ChargePending)
                            {
                                status = -2; // Pending
                                myLogger.GetInstance().Warning(User.Identity.Name, "| Purchase of basic plan pending |", "Payment/UpdatePaymentStatus");

                            }
                            if (stripeEvent.Type == Events.ChargeRefunded)
                            {
                                status = -3; // Refunded
                                transactionRefund = ((double)childData.AmountRefunded / 100.0);
                                myLogger.GetInstance().Warning(User.Identity.Name, "| Purchase of basic plan refunded |", "Payment/UpdatePaymentStatus");
                            }
                            if (stripeEvent.Type == Events.ChargeSucceeded)
                            {
                                status = 1; // Completed
                                myLogger.GetInstance().Info(User.Identity.Name, "Bought Basic Plan", "Payment/UpdatePaymentStatus");
                            }


                            // Update data
                            // For example: database
                            // order.Status = status;
                            // db.SaveChanges();
                        }
                        break;
                    default:
                        //log.Warn("");
                        break;
                }
                return Json(new
                {
                    Code = -1,
                    Message = "Update failed."
                });
            }
            catch (Exception e)
            {
                //log.Error("UpdatePaymentStatus: " + e.Message);
                return Json(new
                {
                    Code = -100,
                    Message = "Error."
                });
            }
        }

        public ActionResult Successful()
        {
            return View();
        }
        public ActionResult Fail()
        {
            return View();
        }
    }

Still not working though. I'm not getting any logs(using nLog) and the webhook is failing(in stripe dashboard).

Upvotes: 0

Views: 1271

Answers (1)

koopajah
koopajah

Reputation: 25552

Your code is creating a Checkout Session via the API. This is associated with Stripe's Checkout product. Stripe controls the UI to collect all the payment method details which means you're going to redirect your customer directly to Stripe's hosted page.

Once a customer pays, they will be redirected to your payment page configured in SuccessUrl in your code. You need to write code that detects the customer hitting that URL and map it to the session they were paying.

Additionally, it's possible for a customer to close their browser too before hitting your page. For that reason, Stripe also sends the checkout.session.completed event to your webhook handler. You can write code to handle that event and look at the status of their payment and all relevant information.

Stripe covers all possible fulfillment approaches in their documentation: https://stripe.com/docs/payments/checkout/fulfill-orders

Upvotes: 1

Related Questions