Skip to content
This repository has been archived by the owner on Apr 19, 2022. It is now read-only.

Commit

Permalink
Fix webhook handling in Ruby server. (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten-stripe authored Apr 17, 2019
1 parent fcac2ab commit f8be115
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions server/ruby/app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -130,33 +130,35 @@
post '/webhook' do
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://stripe.com/docs/webhooks.
webhook_secret = ENV['STRIP_WEBHOOK_SECRET']
request_data = JSON.parse request.body.read
webhook_secret = ENV['STRIPE_WEBHOOK_SECRET']
payload = request.body.read

if webhook_secret
if !webhook_secret.empty?
# Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil

begin
event = Stripe::Webhook.construct_event(
payload, sig_header, endpoint_secret
payload, sig_header, webhook_secret
)
rescue JSON::ParserError => e
# Invalid payload
status 400
return
rescue Stripe::SignatureVerificationError => e
# Invalid signature
puts "⚠️ Webhook signature verification failed."
status 400
return
end
# Get the type of webhook event sent - used to check the status of PaymentIntents.
event_type = event['type']
else
data = request_data['data']
event_type = request_data['type']
data = JSON.parse(payload, symbolize_names: true)
event = Stripe::Event.construct_from(data)
end

# Get the type of webhook event sent - used to check the status of PaymentIntents.
event_type = event['type']
data = event['data']
data_object = data['object']

# PaymentIntent Beta, see https://stripe.com/docs/payments/payment-intents
Expand All @@ -176,7 +178,7 @@
end

# Monitor `source.chargeable` events.
elsif data_object['object'] == 'source' && data_object['status'] == 'chargeable' && data_object['metadata'].include?('paymentIntent')
elsif data_object['object'] == 'source' && data_object['status'] == 'chargeable' && !data_object['metadata']['paymentIntent'].nil?
source = data_object
puts "🔔 Webhook received! The source #{source['id']} is chargeable"

Expand Down Expand Up @@ -207,6 +209,7 @@
intent = Stripe::PaymentIntent.retrieve(
source['metadata']['paymentIntent']
)
puts "🔔 Webhook received! Source #{source['id']} failed or canceled. Cancelling #{intent['id']}."
intent.cancel
end

Expand Down

0 comments on commit f8be115

Please sign in to comment.