-
-
Save arabyniuk/24f285262c4a4a7dc44a720355a3b5fc to your computer and use it in GitHub Desktop.
simple stripe webhook
This file contains hidden or 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
сlass WebhooksController < ApplicationController | |
skip_before_action :authenticate_user! | |
skip_before_action :verify_authenticity_token | |
def create | |
payload = request.body.read | |
sig_header = request.env['HTTP_STRIPE_SIGNATURE'] | |
event = nil | |
begin | |
event = Stripe::Webhook.construct_event( | |
payload, sig_header, Rails.application.credentials[:stripe][:webhook] | |
) | |
rescue JSON::ParserError => e | |
status 400 | |
return | |
rescue Stripe::SignatureVerificationError => e | |
# Invalid signature | |
puts "Signature error" | |
p e | |
return | |
end | |
# Handle the event | |
case event.type | |
when 'checkout.session.completed' | |
session = event.data.object | |
session_with_expand = Stripe::Checkout::Session.retrieve({ id: session.id, expand: ["line_items"]}) | |
session_with_expand.line_items.data.each do |line_item| | |
product = Product.find_by(stripe_product_id: line_item.price.product) | |
product.increment!(:sales_count) | |
end | |
end | |
render json: { message: 'success' } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment