Skip to content

Instantly share code, notes, and snippets.

@cjavilla-stripe
Created December 27, 2021 17:46
Show Gist options
  • Save cjavilla-stripe/efaeba1abe949592906bcf928e1e5ba4 to your computer and use it in GitHub Desktop.
Save cjavilla-stripe/efaeba1abe949592906bcf928e1e5ba4 to your computer and use it in GitHub Desktop.
Stripe webhook handler for .NET 6 minimal API
using Stripe;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapPost("/webhook", async (HttpRequest request) =>
{
var json = await new StreamReader(request.Body).ReadToEndAsync();
const string signingSecret = "whsec_...";
try
{
var stripeEvent = EventUtility.ConstructEvent(
json,
request.Headers["Stripe-Signature"],
signingSecret
);
// Handle the event
if (stripeEvent.Type == Events.PaymentIntentSucceeded)
{
var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
Console.WriteLine("PaymentIntent was successful!");
}
else if (stripeEvent.Type == Events.PaymentMethodAttached)
{
var paymentMethod = stripeEvent.Data.Object as PaymentMethod;
Console.WriteLine("PaymentMethod was attached to a Customer!");
}
// ... handle other event types
else
{
Console.WriteLine("Unhandled event type: {0}", stripeEvent.Type);
}
return Results.Ok(new { Message = "success" });
}
catch (StripeException e)
{
return Results.BadRequest(new { Error = e.Message });
}
catch (Exception e)
{
return Results.BadRequest(new { Error = $"{e}" });
}
});
app.Run("http://localhost:4242");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment