Last active
September 15, 2023 09:40
-
-
Save a-patel/47a16f23b97aaca262fc51cc185fee3e to your computer and use it in GitHub Desktop.
Stripe WebHooks handling in ASP.NET MVC (C#)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StripeController : Controller | |
{ | |
/// <summary> | |
/// Stripe webhook handling | |
/// </summary> | |
/// <returns></returns> | |
[AllowAnonymous] | |
[HttpPost] | |
[Route("webhook")] | |
public IActionResult StripeWebhook() | |
{ | |
try | |
{ | |
var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); | |
var signatureHeader = Request.Headers["Stripe-Signature"]; | |
var webhookEndpointSecret = "whsec_xxxxxx"; | |
// validate webhook called by stripe only | |
var stripeEvent = EventUtility.ConstructEvent(json, signatureHeader, webhookEndpointSecret); | |
switch (stripeEvent.Type) | |
{ | |
case Events.CustomerCreated: | |
var customer = stripeEvent.Data.Object as Customer; | |
// do work | |
break; | |
case Events.CustomerUpdated: | |
// do work | |
break; | |
case Events.CustomerDeleted: | |
// do work | |
break; | |
case Events.PaymentMethodAttached: | |
// do work | |
break; | |
case Events.CustomerSubscriptionCreated: | |
var subscription = stripeEvent.Data.Object as Subscription; | |
// do work | |
break; | |
case Events.CustomerSubscriptionTrialWillEnd: | |
// do work | |
break; | |
case Events.CustomerSubscriptionPaused: | |
// do work | |
break; | |
case Events.CustomerSubscriptionResumed: | |
// do work | |
break; | |
case Events.CustomerSubscriptionUpdated: | |
// do work | |
break; | |
case Events.CustomerSubscriptionDeleted: | |
// do work | |
break; | |
// DO SAME FOR OTHER EVENTS | |
} | |
return Ok(); | |
} | |
catch (StripeException ex) | |
{ | |
//_logger.LogError(ex, $"StripWebhook: {ex.Message}"); | |
return BadRequest(); | |
} | |
catch (Exception ex) | |
{ | |
//_logger.LogError(ex, $"StripWebhook: {ex.Message}"); | |
return BadRequest(); | |
} | |
} | |
} |
Which version of .NET are you using @vishal-parmar?
4.5.2 dot net version and 11.10 Stripe nuget version
Above code is for ASP.NET Core.
Please upgrade your Stripe SDK to its latest version, they have fixed many minor bugs in last few versions.
@vishal-parmar
@a-patel Thank you sir.
How to get CustomerID from StripeEvents if ChargeSucceeded.
I have done
var customer = stripeEvent.Data.Object as Customer
but customer.Email and customer.ID get NULL
@vishal-parmar, if you are testing webhook in Test mode then you won't have customer details, it will only trigger the webhook for that event only.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am same code use but inside
var json = new StreamReader(HttpContext.Request.Body).ReadToEnd();
Body not support