Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# Mike Bianco <mike@suitesync.io>
# Description: Example of using Stripe webhooks to copy a parent subscription
# metadata field to a Stripe-generated charge's metadata
require 'stripe'
require 'sinatra'
Stripe.api_key = "sk_test_"
# Listen to Stripe events using webhooks
#
# - https://stripe.com/docs/webhooks
# - https://dashboard.stripe.com/account/webhooks
# This example uses sinatra. You can easily use rails.
# post '/stripe/webhooks' => 'stripe_webhooks#consume'
post "/stripe/webhooks" do
event_json = JSON.parse(request.body.read)
# https://stripe.com/docs/api#list_events
# charge.pending is fired whenever a charge is created
if event_json['type'] == 'charge.pending'
stripe_charge = Stripe::Charge.retrieve(event_json['id'])
if stripe_charge.invoice
stripe_invoice = Stripe::Invoice.retrieve(stripe_charge.invoice)
stripe_subscription = Stripe::Subscription.retrieve(stripe_invoice.subscription)
stripe_charge.metadata['order_number'] = stripe_subscription.metadata['order_number']
stripe_charge.save
end
end
status 200
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment