尝试使用ASP.NET MVC和C#为条纹设置Web挂钩

问题描述

我已经实现了一些前端代码,当用户单击结帐按钮时,他们将被重定向一个分页,在该分页中,他们可以输入其卡付款细节。该代码具有成功的URL和失败的URL。如果客户输入有效的付款明细-将它们重定向到成功的URL,则我需要更新数据库以确保后端知道该特定用户已付款,并且现在可以查看订阅内容。我正在尝试设置网络挂钩,以便执行此操作,因此我知道用户是否已经付款,取消付款等。

using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Stripe;

namespace workspace.Controllers
{
    [Route("api/[controller]")]
    public class StripeWebHook : Controller
{
    // You can find your endpoint's secret in your webhook settings
    const string secret = "whsec_...";

    [HttpPost]
    public async Task<IActionResult> Index()
    {
        var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

        try
        {
            var stripeEvent = EventUtility.ConstructEvent(json,Request.Headers["Stripe-Signature"],secret);

            // Handle the checkout.session.completed event
            if (stripeEvent.Type == Events.CheckoutSessionCompleted)
            {
                var session = stripeEvent.Data.Object as Checkout.Session;

                // Fulfill the purchase...
                HandleCheckoutSession(session);
            }
            else
            {
                return Ok()
            }
        }
        catch (StripeException e)
        {
            return BadRequest();
        }
    }
}
}

但是,当尝试实现此功能时,会出现错误,因为我认为上面提供的自定义代码使用.NET Core,并且我使用的是完整的.NET框架。

有没有解决的办法,或者我做错了什么?

解决方法

在我的Asp.net Framework 4.7中有效,请尝试下面的Webhook代码

    [HttpPost]
   [Route("api/[controller]/webhook")]
    public async Task<HttpResponseMessage> ProcessRequest()
    {

        var json = await new StreamReader(HttpContext.Current.Request.InputStream).ReadToEndAsync();
        try
        {
            var stripeEvent = EventUtility.ParseEvent(json);

            // Handle the event
            if (stripeEvent.Type == Events.PaymentIntentSucceeded)
            {
                var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
                // Then define and call a method to handle the successful payment intent.
                // handlePaymentIntentSucceeded(paymentIntent);
            }
            else if (stripeEvent.Type == Events.PaymentMethodAttached)
            {
                var paymentMethod = stripeEvent.Data.Object as PaymentMethod;
                // Then define and call a method to handle the successful attachment of a PaymentMethod.
                // handlePaymentMethodAttached(paymentMethod);
            }
            // ... handle other event types
            else
            {
                // Unexpected event type
                Console.WriteLine("Unhandled event type: {0}",stripeEvent.Type);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (StripeException e)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        //Modification and Saving Data
   
      }

添加此Webhook后,您可以从https://stripe.com/docs/webhooks/test此链接进行本地测试