简体   繁体   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);
      }

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.就像添加一个成功的 url 一样,但是对于一个动作。 I'm kinda new to this so :/我对此有点陌生,所以:/

Edit:编辑:

I added a webhook to https://xxxx.eu.ngrok.io/payment/UpdatePaymentStatus for this action:我为此操作添加了一个 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();
        }
    }

Still not working though.仍然无法正常工作。 I'm not getting any logs(using nLog) and the webhook is failing(in stripe dashboard).我没有收到任何日志(使用 nLog)并且 webhook 失败(在条带仪表板中)。

Your code is creating a Checkout Session via the API .您的代码正在通过API创建一个 Checkout Session。 This is associated with Stripe's Checkout product.这与 Stripe 的Checkout产品有关。 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. Stripe 控制 UI 以收集所有付款方式的详细信息,这意味着您将直接将客户重定向到 Stripe 的托管页面。

Once a customer pays, they will be redirected to your payment page configured in SuccessUrl in your code.客户付款后,他们将被重定向到您代码中SuccessUrl中配置的付款页面。 You need to write code that detects the customer hitting that URL and map it to the session they were paying.您需要编写代码来检测客户点击该 URL 并将其映射到他们支付的会话。

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.因此,Stripe 还将checkout.session.completed事件发送到您的 webhook 处理程序。 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 Stripe 在其文档中涵盖了所有可能的履行方法: https ://stripe.com/docs/payments/checkout/fulfill-orders

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM