rafal.siepak PRO said 9 days ago on Stripe Billing Portal :
This is my controller:


class CheckoutsController < ApplicationController
  before_action :require_user!
  before_action :check_subscription

  def require_user!
    unless current_user
      flash[:alert] = "Musisz być zalogowany, aby dostać się do tej strony."
      redirect_to root_path
    end
  end

  def show
    customer = current_user.stripe_customer

    payload = {
      customer: customer,
      billing_address_collection: :auto,
      payment_method_types: %w[card],
      allow_promotion_codes: true,
      subscription_data: {
        items: [{ plan: "price_xxxxxxxxx", quantity: 1 }]
      },
      ui_mode: "embedded",
      return_url: CGI.unescape(payments_url(session_id: '{CHECKOUT_SESSION_ID}'))
    }
    @session = Stripe::Checkout::Session.create(payload)
    @stripe_publishable_key = ENV['STRIPE_PUBLISHABLE_KEY']
    current_user.update(stripe_checkout_id: @session.id)
  end

  private

  def check_subscription
    return unless current_user.subscribed?

    redirect_to root_path, notice: "You are already subscribed!"
  end
end


This is my show:

<div data-controller="stripe"
     data-stripe-public-key-value="<%= @stripe_publishable_key %>"
     data-stripe-client-secret-value="<%= @client_secret %>">
</div>

and stimulus:

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="stripe"
export default class extends Controller {
  static values = { publicKey: String, clientSecret: String }
  stripe = Stripe(this.publicKeyValue)

  async connect() {
    this.checkout = await this.stripe.initEmbeddedCheckout({
      clientSecret: this.clientSecretValue
    })
    this.checkout.mount(this.element)
  }

  disconnect() {
    this.checkout.destroy()
  }
}

and stripe initializer:

Stripe.api_key = ENV['STRIPE_SECRET_KEY']
Stripe.api_version =  '2024-04-10'

STRIPE_PUBLISHABLE_KEY = ENV['STRIPE_PUBLISHABLE_KEY']