Created
October 25, 2012 04:36
-
-
Save SidShetye/3950433 to your computer and use it in GitHub Desktop.
Receiving Stripe.com's Webhooks in ASP.NET C#, MVC4
This file contains 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
using System; | |
using System.IO; | |
using System.Web; | |
using System.Web.Mvc; | |
using Stripe; // you need this library https://github.com/jaymedavis/stripe.net | |
using System.Net; | |
namespace StripeSampleMVC.Controllers | |
{ | |
public class StripeWebhookController : Controller | |
{ | |
[HttpPost] | |
public ActionResult Index() | |
{ | |
// MVC3/4: Since Content-Type is application/json in HTTP POST from Stripe | |
// we need to pull POST body from request stream directly | |
Stream req = Request.InputStream; | |
req.Seek(0, System.IO.SeekOrigin.Begin); | |
string json = new StreamReader(req).ReadToEnd(); | |
StripeEvent stripeEvent = null; | |
try | |
{ | |
// as in header, you need https://github.com/jaymedavis/stripe.net | |
// it's a great library that should have been offered by Stripe directly | |
stripeEvent = StripeEventUtility.ParseEvent(json); | |
} | |
catch (Exception ex) | |
{ | |
return new HttpStatusCodeResult(HttpStatusCode.BadRequest,"Unable to parse incoming event"); | |
} | |
if (stripeEvent ==null) | |
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Incoming event empty"); | |
switch (stripeEvent.Type) | |
{ | |
case "charge.refunded": | |
// do work | |
break; | |
case "customer.subscription.updated": | |
case "customer.subscription.deleted": | |
case "customer.subscription.created": | |
// do work | |
break; | |
} | |
return new HttpStatusCodeResult(HttpStatusCode.OK); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You might want to add something like this before the switch statement:
and then in the cases you can use something like this:
This way you can have a strongly typed object to work with instead of the data.object dynamic class of the stripeEvent. For each case the payload would be a different type, so you can check the stripe api and create objects that are easier to work with in your code. (I was unaware that there was a Mapper<> in Stripe.net, made things easy because it converts the unix dates from the json properly)