public ActionResult Index() { Stream req = Request.InputStream; req.Seek(0, SeekOrigin.Begin); string json = new StreamReader(req).ReadToEnd(); StripeEvent stripeEvent = null; try { stripeEvent = StripeEventUtility.ParseEvent(json); } catch (Exception ex) { Log.Error().Exception(ex).Message("Unable to parse incoming event.").Report(b => b.AddObject(json, "Event")).Write(); return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Unable to parse incoming event")); } if (stripeEvent == null) { Log.Warn().Message("Null stripe event.").Write(); return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Incoming event empty")); } _stripeEventHandler.HandleEvent(stripeEvent); return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
public IActionResult StripeResponse() { var json = new StreamReader(HttpContext.Request.Body).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); return(View()); }
public async Task <IActionResult> PostAsync([FromBody] string json) { if (String.IsNullOrEmpty(json)) { return(Ok()); } if (!Request.Headers.TryGetValue("Stripe-Signature", out var signature) || String.IsNullOrEmpty(signature)) { return(Ok()); } using (_logger.BeginScope(new ExceptionlessState().SetHttpContext(HttpContext))) { StripeEvent stripeEvent; try { stripeEvent = StripeEventUtility.ConstructEvent(json, signature, Settings.Current.StripeWebHookSigningSecret); } catch (Exception ex) { using (_logger.BeginScope(new ExceptionlessState().Property("event", json))) _logger.LogError(ex, "Unable to parse incoming event: {Message}", ex.Message); return(BadRequest("Unable to parse incoming event")); } if (stripeEvent == null) { _logger.LogWarning("Null stripe event."); return(BadRequest("Incoming event empty")); } await _stripeEventHandler.HandleEventAsync(stripeEvent); return(Ok()); } }
public async Task <IActionResult> PostAsync() { string json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); using (_logger.BeginScope(new ExceptionlessState().SetHttpContext(HttpContext).Property("event", json))) { if (String.IsNullOrEmpty(json)) { _logger.LogWarning("Unable to get json of incoming event."); return(BadRequest()); } StripeEvent stripeEvent; try { stripeEvent = StripeEventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], Settings.Current.StripeWebHookSigningSecret); } catch (Exception ex) { _logger.LogError(ex, "Unable to parse incoming event with {Signature}: {Message}", Request.Headers["Stripe-Signature"], ex.Message); return(BadRequest()); } if (stripeEvent == null) { _logger.LogWarning("Null stripe event."); return(BadRequest()); } await _stripeEventHandler.HandleEventAsync(stripeEvent); return(Ok()); } }
public void RejectMessageWithUnicode() { var exception = Assert.Throws <StripeException>(() => StripeEventUtility.ConstructEvent(this.json + "\ud802", this.signature, this.secret)); Assert.Equal("The webhook cannot be processed because the signature cannot be safely calculated.", exception.Message); }
protected StripeEvent GetStripeEvent(HttpRequest request) { StripeEvent stripeEvent = null; if (HttpContext.Current.Items["TC_StripeEvent"] != null) { stripeEvent = (StripeEvent)HttpContext.Current.Items["TC_StripeEvent"]; } else { try { if (request.InputStream.CanSeek) { request.InputStream.Seek(0, SeekOrigin.Begin); } using (StreamReader reader = new StreamReader(request.InputStream)) { stripeEvent = StripeEventUtility.ParseEvent(reader.ReadToEnd()); HttpContext.Current.Items["TC_StripeEvent"] = stripeEvent; } } catch { } } return(stripeEvent); }
public void Execute() { var stripeEvent = StripeEventUtility.ParseEvent(json); if (stripeEvent.LiveMode == false) { return; } switch (stripeEvent.Type) { case "customer.subscription.deleted": // Event fires when a user cancels a subscription var aa = Stripe.Mapper <StripeSubscription> .MapFromJson(stripeEvent.Data.Object.ToString()); var customerId = aa.CustomerId; break; case "charge.refunded": // take a look at all the types here: https://stripe.com/docs/api#event_types var stripeCharge = Stripe.Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); break; } // TODO: Actually handle the hook if Majorsilence.Vpn.Logic.DailyProcessing is not being used }
public async static Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { try { var stripeEvent = StripeEventUtility.ParseEvent(await req.ReadAsStringAsync()); log.LogInformation($"Received stripe event of type: {stripeEvent.Type}"); var(accessToken, clientSecret) = await LoadSettingsAsync(stripeEvent.LiveMode); var fortnoxClient = new FortnoxClient(accessToken, clientSecret, log); var response = await HandleStripeEvent(stripeEvent, fortnoxClient); if (response.IsSuccessStatusCode) { return(new OkObjectResult(await response.Content.ReadAsStringAsync())); } return(new BadRequestObjectResult(await response.Content.ReadAsStringAsync())); } catch (Exception ex) { log.LogError(ex, $"Something went wrong ({ex.Message})"); // whytf is the exception not logged? return(new BadRequestObjectResult(ex.Message)); } }
public void RejectIncorrectSignature() { // This throws an error because the original JSON message is modified var exception = Assert.Throws <StripeException>(() => StripeEventUtility.ConstructEvent(this.json + "this_changes_the_json", this.signature, this.secret)); Assert.Equal("The signature for the webhook is not present in the Stripe-Signature header.", exception.Message); }
public void it_should_throw_with_invalid_unicode_in_message() { var exception = Assert.Throws <StripeException>(() => StripeEventUtility.ConstructEvent(fixture.StripeJson + "\ud802", fixture.StripeSignature, fixture.StripeSecret) ); exception.Message.Should().Be("The webhook cannot be processed because the signature cannot be safely calculated."); }
public void it_should_throw_with_incorrect_signature() { // This throws an error because the original JSON message is modified var exception = Assert.Throws <StripeException>(() => StripeEventUtility.ConstructEvent(fixture.StripeJson + "this_changes_the_json", fixture.StripeSignature, fixture.StripeSecret) ); exception.Message.Should().Be("The signature for the webhook is not present in the Stripe-Signature header."); }
public void it_should_throw_with_outdated_timestamp() { // This throws an error because the tolerance is higher than allowed var exception = Assert.Throws <StripeException>(() => StripeEventUtility.ConstructEvent(fixture.StripeJson, fixture.StripeSignature, fixture.StripeSecret) ); exception.Message.Should().Be("The webhook cannot be processed because the current timestamp is outside of the allowed tolerance."); }
public ActionResult Index() { Stream request = Request.InputStream; request.Seek(0, SeekOrigin.Begin); string json = new StreamReader(request).ReadToEnd(); StripeEvent stripeEvent = null; try { stripeEvent = StripeEventUtility.ParseEvent(json); } catch (Exception e) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, string.Format("Unable to parse incoming event. The following error occured: {0}", e.Message))); } if (stripeEvent == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Incoming event empty")); } var emailService = new Services.EmailService(); switch (stripeEvent.Type) { case StripeEvents.ChargeRefunded: var charge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); emailService.SendRefundEmail(charge); break; case StripeEvents.CustomerSubscriptionTrialWillEnd: var subscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.Data.Object.ToString()); emailService.SendTrialEndEmail(subscription); break; case StripeEvents.InvoicePaymentSucceeded: StripeInvoice invoice = Mapper <StripeInvoice> .MapFromJson(stripeEvent.Data.Object.ToString()); var customer = StripeCustomerService.Get(invoice.CustomerId); var user = UserManager.FindByEmail(customer.Email); user.ActiveUntil = user.ActiveUntil.AddMonths(1); UserManager.Update(user); emailService.SendSubscriptionPaymentReceiptEmail(invoice, customer); break; default: break; } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
public void ProcessRequest(HttpContext context) { var json = new StreamReader(context.Request.InputStream).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); switch (stripeEvent.Type) { case "charge.refunded": // take a look at all the types here: https://stripe.com/docs/api#event_types var stripeCharge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); break; case "charge.succeeded": // take a look at all the types here: https://stripe.com/docs/api#event_types try { var myCharge = new StripeCharge(); myCharge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); string Username = myCharge.Metadata["RALTUserName"]; string UserID = myCharge.Metadata["RALTUserID"]; //RentALanguageTeacher.user Paypal = UserService.GetUserById(74); //DateTime TransDate = App_Code.RALTService.ConvertFromPayPalDate(myCharge.); //DateTime UTCTransDate = DateTime.UtcNow; payment MyPayment = new payment(); MyPayment.hours = Convert.ToInt32(myCharge.Description.Substring(0, 2)); MyPayment.transaction_date = myCharge.Created; MyPayment.username = Username; MyPayment.update_user = "******"; MyPayment.user_id = Convert.ToInt32(UserID); MyPayment.item_name = myCharge.Description; //MyPayment.payer_email = ; MyPayment.transaction_id = myCharge.Id; MyPayment.transaction_status = stripeEvent.Type; App_Code.PaymentService.SaveObject(MyPayment); UserService.AccountStatusPaid(Convert.ToInt32(UserID)); } catch (Exception ex) { Send_download_link("*****@*****.**", "*****@*****.**", "StripeHandlerError", ex.Message); } break; } }
public void RejectOutdatedTimestamp() { var tolerance = 300; var fakeCurrentTimestamp = this.eventTimestamp + tolerance + 100; var exception = Assert.Throws <StripeException>(() => StripeEventUtility.ConstructEvent(this.json, this.signature, this.secret, tolerance, fakeCurrentTimestamp)); Assert.Equal("The webhook cannot be processed because the current timestamp is outside of the allowed tolerance.", exception.Message); }
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; WebhookEntities entity = new WebhookEntities(); entity.Logs.Add(new Log() { Info = "Webhook Received" }); entity.SaveChanges(); 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")); } entity.StripeWebhooks.Add(new StripeWebhook() { EventKey = stripeEvent.Id, EventType = stripeEvent.Type }); entity.SaveChanges(); 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)); }
public void ConstructEvent() { var tolerance = 300; var fakeCurrentTimestamp = this.eventTimestamp + 100; var evt = StripeEventUtility.ConstructEvent(this.json, this.signature, this.secret, tolerance, fakeCurrentTimestamp); Assert.NotNull(evt); Assert.Equal("acct_123", evt.Account); Assert.Equal("req_123", evt.Request.Id); Assert.Equal("idempotency-key-123", evt.Request.IdempotencyKey); }
public void it_should_validate_with_right_data() { // A timestamp within the default tolerance of 300 seconds int ReasonablyCloseTime = fixture.EventTimestamp + 120; ConstructedEvent = StripeEventUtility.ConstructEvent(fixture.StripeJson, fixture.StripeSignature, fixture.StripeSecret, ReasonablyCloseTime); ConstructedEvent.Should().NotBeNull(); ConstructedEvent.Request.Id.Should().Be("req_FAKE"); ConstructedEvent.Request.IdempotencyKey.Should().Be("placeholder"); ConstructedEvent.Account.Should().Be("acct_CONNECT"); }
public void ProcessRequest(HttpContext context) { try { Logs.LogsInsertAction("Stripe subscription attempted"); var json = new StreamReader(context.Request.InputStream).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); switch (stripeEvent.Type) { case StripeEvents.InvoicePaymentSucceeded: // all of the types available are listed in StripeEvents // parse first call StripeInvoice insecureStripeInvoice = Stripe.Mapper <StripeInvoice> .MapFromJson(stripeEvent.Data.Object.ToString()); // just get id and retreive from stripe to prevent spoofing var eventService = new StripeEventService(); StripeRequestOptions requestOptions = new StripeRequestOptions(); requestOptions.ApiKey = Constants.StripeSecretKey; // can't be called more than once (webhooks can send multiple times) requestOptions.IdempotencyKey = stripeEvent.Id; StripeEvent response = eventService.Get(stripeEvent.Id, requestOptions); StripeInvoice stripeInvoice = Stripe.Mapper <StripeInvoice> .MapFromJson(response.Data.Object.ToString()); if (stripeInvoice.Paid) { using (var db = new UniversalGymEntities()) { var user = db.Users.SingleOrDefault(s => s.StripeUrl == stripeInvoice.CustomerId); int charge = stripeInvoice.Total; new creditAdd(db).AddCredit(user, null, charge, charge); Logs.LogsInsertAction( "Stripe subscription successful: " + stripeInvoice.Total + " added to " + user.Email); } } break; } } catch (Exception exception) { Logs.LogsInsertError(exception); } }
public void ProcessRequest(HttpContext context) { var json = new StreamReader(context.Request.InputStream).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); switch (stripeEvent.Type) { case "charge.refunded": var stripeCharge = Stripe.Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object); break; } }
public IHttpActionResult Index() { var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); switch (stripeEvent.Type) { case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents var stripeCharge = Stripe.Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); break; } return(Ok()); }
public async Task ProcessRequestAsync(HttpContext context) { var json = await new StreamReader(context.Request.Body).ReadToEndAsync(); var stripeEvent = StripeEventUtility.ParseEvent(json); switch (stripeEvent.Type) { case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents var stripeCharge = Stripe.Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); break; } }
public void it_should_validate_with_right_data() { // Override the event utility to prevent it from looking at UTC now and use a fixed valid timestamp in the past StripeEventUtility.EpochUtcNowOverride = 1493329524; ConstructedEvent = StripeEventUtility.ConstructEvent(fixture.StripeJson, fixture.StripeSignature, fixture.StripeSecret); ConstructedEvent.Should().NotBeNull(); ConstructedEvent.Request.Id.Should().Be("req_FAKE"); ConstructedEvent.Request.IdempotencyKey.Should().Be("placeholder"); ConstructedEvent.Account.Should().Be("acct_CONNECT"); // Clean up to prevent unexpected behaviour in other facts StripeEventUtility.EpochUtcNowOverride = null; }
public IHttpActionResult Index() { StripeConfiguration.SetApiKey(WebConfigurationManager.AppSettings["StripeSecretKey"]); var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); var customerService = new StripeCustomerService(); string stripeCustomerID = stripeEvent.Data.Object.customer;//as string; var stripeCustomer = new Stripe.StripeCustomer(); //Test var eventObjectInfo = JObject.Parse(json); var evtDataObject = eventObjectInfo.SelectToken("data.object"); switch (stripeEvent.Type) { case StripeEvents.PayoutPaid: //var customer = Mapper<Stripe.StripeCustomer>.MapFromJson(eventObjectInfo.ToString()); return(Json(new { success = true, message = "Hello world number" })); case StripeEvents.InvoicePaymentFailed: return(Json(new { id = stripeEvent.Id, message = "User Subcription Paused" })); case StripeEvents.ChargeSucceeded: string dytoString = Convert.ToString(stripeCustomerID); var obj = _context.StripeCustomers.FirstOrDefault(c => c.StripeCustomerID == dytoString); if (obj != null) { } return(Json(new { type = stripeEvent.Type, stripeEvent.Type })); case StripeEvents.InvoiceCreated: //string custID = stripeEvent.Data.Object.customer; //var getCustomer = customerService.Get(custID); var evt = Mapper <StripeEvent> .MapFromJson(eventObjectInfo.ToString()); return(Json(new { evt.Id, evt.Data.Object.customer })); case StripeEvents.InvoicePaymentSucceeded: return(Json(new { message = "Invoice Payment Successful" })); default: return(Json(new { id = stripeEvent.Id })); } }
public ActionResult Index() { LoggingFactory.GetLogger().Log("StripeWebhookController Called", EventLogSeverity.Debug); var req = Request.InputStream; req.Seek(0, SeekOrigin.Begin); var json = new StreamReader(req).ReadToEnd(); LoggingFactory.GetLogger().Log("StripeWebhookController Json: " + json, EventLogSeverity.Debug); try { var stripeEvent = StripeEventUtility.ParseEvent(json); if (stripeEvent == null || (stripeEvent.Data == null) || (stripeEvent.Data.Object == null)) { LoggingFactory.GetLogger().Log("StripeWebhookController Incoming event empty", EventLogSeverity.Debug); return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Incoming event empty")); } string customerID = string.Empty; if (stripeEvent.Data.Object.customer != null) { customerID = stripeEvent.Data.Object.customer.ToString(); } else if (stripeEvent.Data.Object.id != null) { customerID = stripeEvent.Data.Object.id.ToString(); } if (!_stripeWebhookService.ValidateCustomer(customerID)) { LoggingFactory.GetLogger().Log("StripeWebhookController Customer Not Valid " + customerID.ToString(), EventLogSeverity.Debug); return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Customer Not Valid")); } _stripeWebhookService.ProcessEvent(customerID, stripeEvent); return(new HttpStatusCodeResult(HttpStatusCode.OK)); } catch (Exception ex) { LoggingFactory.GetLogger().LogError(ex); return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Unable to parse incoming event")); } }
public IActionResult GetWeebHook() { var json = new StreamReader(HttpContext.Request.Body).ReadToEnd(); try { var stripeEvent = StripeEventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], "whsec_vEw1qUwNaH1SyClLDYYZqqSlLWiBHtU1"); // Do something with event } catch (StripeException e) { return(BadRequest()); } return(Json(true)); }
public when_constructing_an_event() { StripeJson = new StreamReader( typeof(when_constructing_an_event).GetTypeInfo().Assembly.GetManifestResourceStream("Stripe.Tests.XUnit.events.event.json"), Encoding.UTF8 ).ReadToEnd(); // this throws an error because the tolerance was higher than allowed // ConstructedEvent = StripeEventUtility.ConstructEvent(StripeJson, StripeSignature, StripeSecret); // override the event utility from looking at utc now to 300 seconds in front of the timestamp in the header StripeEventUtility.EpochUtcNowOverride = 1493329524; ConstructedEvent = StripeEventUtility.ConstructEvent(StripeJson, StripeSignature, StripeSecret); // this throws an error that the signature doesn't match one in the headers //ConstructedEventBadJson = StripeEventUtility.ConstructEvent(StripeJson + "/n", StripeSignature, StripeSecret); }
public void ProcessRequest(HttpContext context) { var json = new StreamReader(context.Request.InputStream).ReadToEnd(); var stripeEvent = StripeEventUtility.ParseEvent(json); switch (stripeEvent.Type) { case StripeEvents.ChargeRefunded: var stripeCharge = Stripe.Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString()); break; case StripeEvents.ChargeDisputeCreated: var stripeDispute = Stripe.Mapper <StripeDispute> .MapFromJson(stripeEvent.Data.Object.ToString()); break; } }
public async Task <IActionResult> Stripe([FromBody] StripeEvent stripeEvent) { var result = new StripeBaseCommand(); try { switch (stripeEvent.Type) { case StripeEvents.ChargeRefunded: StripeRefundModel refund = StripeEventUtility.ParseEventDataItem <StripeRefundModel>(stripeEvent.Data.Object); await _stripeSvc.RefundPayment(refund.id, refund.metadata.AccountNumber, refund.amount_refunded); break; case StripeEvents.CustomerSubscriptionUpdated: break; case StripeEvents.InvoicePaymentFailed: // Invoice is sent and payment results in failure. //Undo Payment break; } } catch (StripeException ex) { var message = $"Unhandled {nameof(StripeException)} caught in {nameof(WebhookController)}.{nameof(Stripe)}. StripeEvent.Type: {stripeEvent.Type}"; _logger.Error(ex, message); result.Logs.Add(message); //await SendWebHookErrorEmail($"[Stripe Webhook Stripe Exception ({_env.EnvironmentName})]", stripeEvent, ex); } catch (Exception ex) { var message = $"Unhandled Exception caught in {nameof(WebhookController)}.{nameof(Stripe)}. StripeEvent.Type: {stripeEvent.Type}"; _logger.Error(ex, message); result.Logs.Add(message); //await SendWebHookErrorEmail($"[Stripe Webhook System Exception ({_env.EnvironmentName})]", stripeEvent, ex); } return(Ok(JsonNet.Serialize(new { result.Logs }, prettyPrint: true))); }
public async Task <IHttpActionResult> Post([NakedBody] string json) { StripeEvent stripeEvent; try { stripeEvent = StripeEventUtility.ParseEvent(json); } catch (Exception ex) { Log.Error().Exception(ex).Message("Unable to parse incoming event.").Property("event", json).Write(); return(BadRequest("Unable to parse incoming event")); } if (stripeEvent == null) { Log.Warn().Message("Null stripe event.").Write(); return(BadRequest("Incoming event empty")); } _stripeEventHandler.HandleEvent(stripeEvent); return(Ok()); }