簡體   English   中英

如何檢查支付是否成功 Stripe ASP.NET

[英]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);
      }

有什么方法可以檢查付款狀態,因為如果付款得到確認,我想調用另一個動作。 就像添加一個成功的 url 一樣,但是對於一個動作。 我對此有點陌生,所以:/

編輯:

我為此操作添加了一個 webhook 到https://xxxx.eu.ngrok.io/payment/UpdatePaymentStatus

 [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();
        }
    }

仍然無法正常工作。 我沒有收到任何日志(使用 nLog)並且 webhook 失敗(在條帶儀表板中)。

您的代碼正在通過API創建一個 Checkout Session。 這與 Stripe 的Checkout產品有關。 Stripe 控制 UI 以收集所有付款方式的詳細信息,這意味着您將直接將客戶重定向到 Stripe 的托管頁面。

客戶付款后,他們將被重定向到您代碼中SuccessUrl中配置的付款頁面。 您需要編寫代碼來檢測客戶點擊該 URL 並將其映射到他們支付的會話。

此外,客戶也可以在點擊您的頁面之前關閉瀏覽器。 因此,Stripe 還將checkout.session.completed事件發送到您的 webhook 處理程序。 您可以編寫代碼來處理該事件並查看他們的付款狀態和所有相關信息。

Stripe 在其文檔中涵蓋了所有可能的履行方法: https ://stripe.com/docs/payments/checkout/fulfill-orders

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM