Created
November 6, 2024 21:49
-
-
Save jeremysmithco/ff58f4324b975fa2b62afc510fa108bd to your computer and use it in GitHub Desktop.
Stripe Checkout PaymentsController
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
class PaymentsController < ApplicationController | |
CHECKOUT_SESSION_ID_KEY = :checkout_session_id | |
before_action :authenticate_user! | |
def new | |
stripe_customer = find_or_create_stripe_customer | |
checkout_session = create_checkout_session(stripe_customer) | |
redirect_to checkout_session.url, allow_other_host: true | |
end | |
def show | |
checkout_session = find_checkout_session(params.fetch(CHECKOUT_SESSION_ID_KEY)) | |
stripe_customer = Stripe::Customer.retrieve(checkout_session.customer) | |
stripe_subscription = Stripe::Subscription.retrieve(checkout_session.subscription) | |
StripeSubscription.create!( | |
stripe_customer: StripeCustomer.find_by(stripe_customer_id: stripe_customer.id), | |
stripe_subscription_id: stripe_subscription.id | |
) | |
redirect_to new_space_path | |
end | |
private | |
def find_or_create_stripe_customer | |
find_stripe_customer || create_stripe_customer | |
end | |
def find_stripe_customer | |
return nil if current_user.stripe_customer_id.blank? | |
Stripe::Customer.retrieve(current_user.stripe_customer_id) | |
end | |
def create_stripe_customer | |
stripe_customer = Stripe::Customer.create( | |
email: current_user.email, | |
metadata: { user_id: current_user.id } | |
) | |
current_user.create_stripe_customer!(stripe_customer_id: stripe_customer.id) | |
stripe_customer | |
end | |
def create_checkout_session(stripe_customer) | |
success_url = url_for(action: :show) | |
cancel_url = pricing_index_url | |
attributes = { | |
mode: "subscription", | |
customer: stripe_customer.id, | |
line_items: [{ price: ENV["STRIPE_PRICE"], quantity: 1 }], | |
success_url: concat_unescaped_stripe_checkout_session_id(success_url), | |
cancel_url: concat_unescaped_stripe_checkout_session_id(cancel_url) | |
} | |
Stripe::Checkout::Session.create(**attributes) | |
end | |
def concat_unescaped_stripe_checkout_session_id(url) | |
stripe_callback_parameter = "#{CHECKOUT_SESSION_ID_KEY}={CHECKOUT_SESSION_ID}" | |
if URI(url).query | |
url.concat("&#{stripe_callback_parameter}") | |
else | |
url.concat("?#{stripe_callback_parameter}") | |
end | |
end | |
def find_checkout_session(checkout_session_id) | |
Stripe::Checkout::Session.retrieve(checkout_session_id) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment