2024-10-08 14:37:47 -05:00
|
|
|
class SubscriptionsController < ApplicationController
|
|
|
|
def new
|
|
|
|
if Current.family.stripe_customer_id.blank?
|
2024-10-24 11:02:27 -04:00
|
|
|
customer = stripe_client.v1.customers.create(
|
2024-10-08 14:37:47 -05:00
|
|
|
email: Current.family.primary_user.email,
|
|
|
|
metadata: { family_id: Current.family.id }
|
|
|
|
)
|
|
|
|
Current.family.update(stripe_customer_id: customer.id)
|
|
|
|
end
|
|
|
|
|
2024-10-24 11:02:27 -04:00
|
|
|
session = stripe_client.v1.checkout.sessions.create({
|
2024-10-08 14:37:47 -05:00
|
|
|
customer: Current.family.stripe_customer_id,
|
|
|
|
line_items: [ {
|
|
|
|
price: ENV["STRIPE_PLAN_ID"],
|
|
|
|
quantity: 1
|
|
|
|
} ],
|
|
|
|
mode: "subscription",
|
2024-10-08 15:19:23 -05:00
|
|
|
allow_promotion_codes: true,
|
2024-10-24 11:02:27 -04:00
|
|
|
success_url: success_subscription_url + "?session_id={CHECKOUT_SESSION_ID}",
|
2024-10-08 14:37:47 -05:00
|
|
|
cancel_url: settings_billing_url
|
|
|
|
})
|
|
|
|
|
|
|
|
redirect_to session.url, allow_other_host: true, status: :see_other
|
|
|
|
end
|
|
|
|
|
|
|
|
def show
|
2024-10-24 11:02:27 -04:00
|
|
|
portal_session = stripe_client.v1.billing_portal.sessions.create(
|
2024-10-08 14:37:47 -05:00
|
|
|
customer: Current.family.stripe_customer_id,
|
|
|
|
return_url: settings_billing_url
|
|
|
|
)
|
2024-10-24 11:02:27 -04:00
|
|
|
|
2024-10-08 14:37:47 -05:00
|
|
|
redirect_to portal_session.url, allow_other_host: true, status: :see_other
|
|
|
|
end
|
2024-10-24 11:02:27 -04:00
|
|
|
|
|
|
|
def success
|
|
|
|
checkout_session = stripe_client.v1.checkout.sessions.retrieve(params[:session_id])
|
|
|
|
Current.session.update(subscribed_at: Time.at(checkout_session.created))
|
|
|
|
redirect_to root_path, notice: "You have successfully subscribed to Maybe+."
|
|
|
|
rescue Stripe::InvalidRequestError
|
|
|
|
redirect_to settings_billing_path, alert: "Something went wrong processing your subscription. Please contact us to get this fixed."
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def stripe_client
|
|
|
|
@stripe_client ||= Stripe::StripeClient.new(ENV["STRIPE_SECRET_KEY"])
|
|
|
|
end
|
2024-10-08 14:37:47 -05:00
|
|
|
end
|