Skip to content

Instantly share code, notes, and snippets.

@cjavilla-stripe
Last active June 29, 2022 12:53
Show Gist options
  • Save cjavilla-stripe/6026e43f574877be4c8b1eaef3cbe613 to your computer and use it in GitHub Desktop.
Save cjavilla-stripe/6026e43f574877be4c8b1eaef3cbe613 to your computer and use it in GitHub Desktop.
require 'stripe'
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
def date_description(dates)
end
def next_dates
# some database stuff
[start_date, end_date]
end
checkout_session = Stripe::Checkout::Session.create({
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/cancel',
line_items: [{
price_data: {
currency: 'cad',
unit_amount: 100000, # in cents
product_data: {
name: 'Product Coaching',
description: date_description(next_dates),
},
},
quantity: 1,
}],
mode: 'payment',
metadata: {
start_date: next_dates.first,
end_date: next_dates.last
}
})
redirect_to checkout_session.url
require 'json'
# Using Sinatra
post '/webhook' do
payload = request.body.read
event = nil
begin
event = Stripe::Event.construct_from(
JSON.parse(payload, symbolize_names: true)
)
rescue JSON::ParserError => e
# Invalid payload
status 400
return
end
# Handle the event
case event.type
when 'checkout.session.completed', 'checkout.session.async_payment_succeeded'
checkout_session = event.data.object
if checkout_session.payment_status == 'paid'
# use checkout_session.metadata.start_date and checkout_session.metadata.end_date to udpate the database
end
else
puts "Unhandled event type: #{event.type}"
end
status 200
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment