Commerce: Stripe Checkout Session Creation

This section details how the application builds and initiates Stripe Checkout Sessions for event orders. It ensures a smooth, compliant, and metadata-rich payment flow by:

  • Expiring previous sessions to prevent duplicates
  • Persisting cart and billing data
  • Pre-creating orders and “rounds” for accurate tracking
  • Configuring session parameters (line items, URLs, TOS, consent, metadata)
  • Redirecting customers to Stripe’s hosted checkout page

Key Responsibilities

  • Expire open sessions to avoid duplicate checkouts
  • Store session data (cart contents, billing info) in Laravel session
  • Process the cart into pending orders/order-rounds before checkout
  • Build rich metadata for reconciliation and reporting
  • Set clear descriptors on the payment intent
  • Create the Checkout Session via Stripe’s PHP SDK
  • Persist the session ID on the Cart model
  • Redirect the customer to Stripe’s checkout URL

Workflow Sequence

sequenceDiagram
  participant U as User
  participant L as Livewire Component
  participant T as StripeTrait::stripeCheckout()
  participant S as SaveOrderService
  participant C as Stripe API
  participant B as Browser / Redirect

  U->>L: Click “Checkout”
  L->>T: stripeCheckout($line_items, $coupons, $cancel_url, $email)
  T->>T: expireExistingSession()  
  T->>T: storeData(sessionData)  
  T->>S: processCart(this)  
  S-->>T: $orderRounds created  
  T->>C: Session::create($stripeSessionData)  
  C-->>T: StripeSession object  
  T->>Cart: update(stripe_checkout_session_id)  
  T->>B: Redirect::away(stripeSession.url)  

Expiring Previous Sessions ⚠️

Before creating a new session, the trait checks for an open session in the user’s Laravel session and expires it via Stripe’s API. This avoids multiple active sessions per cart instance.

private function expireExistingSession(): void
{
    if (! session()->has('stripe_session_id')) {
        return;
    }
    $stripeSession = Session::retrieve(session('stripe_session_id'));
    if ($stripeSession && $stripeSession->status == 'open') {
        $stripeSession->expire();
    }
    session()->forget('stripe_session_id');
}

Session Data Persistence

The method storeData($sessionData) serializes cart, billing, and any selected events into the Laravel session. This snapshot drives post-payment order fulfillment and receipt generation.


Pre-Processing Orders

Before checkout, the cart is transformed into one or more Order and OrderRound records with a Pending status. This ensures:

  • Accurate allocation of tickets/teams
  • Round-based handling for multi-event carts
  • Zero-total carts are auto-completed
$orderRounds = (new SaveOrderService)->processCart($this);

Building Checkout Session Parameters

Metadata

Key Value
Event ID Comma-separated event IDs
Type Revenue type (Gate/RSVP/Registration)
Order ID Primary order_id
Order Rounds Comma-separated order_round IDs
Cart ID Unique Cart instance ID

Default Session Payload

$defaultSessionData = [
    'line_items'                => $line_items,
    'customer_email'            => $customer_email,
    'discounts'                 => array_map(fn($c)=>['coupon'=>$c->id], $coupons),
    'mode'                      => 'payment',
    'success_url'               => route('stripe.success').'?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url'                => $cancel_url,
    'custom_text'               => [
        'terms_of_service_acceptance' => ['message' => $terms],
    ],
    'metadata'                  => $metadata,
    'consent_collection'        => ['terms_of_service' => 'required'],
    'payment_method_configuration' => config('services.stripe.payment_method_configuration'),
    'payment_intent_data'       => [
        'description'         => $description,
        'statement_descriptor'=> $statementDescriptor,
        'metadata'            => $metadata,
    ],
    'customer_creation'         => 'always',
];
$stripeSessionData = array_merge_recursive($defaultSessionData, $options);
$stripeSession = Session::create($stripeSessionData);
  • Line items: Products, quantities, and pricing
  • URLs: success_url (with placeholder) and cancel_url
  • TOS message: Inline Markdown linking to Prep Network’s Terms and Privacy
  • Consent: Stripe’s required TOS acceptance
  • Metadata: Rich tags for downstream reconciliation
  • Payment intent data: Custom description and concise statement descriptor
  • Customer creation: Ensures Stripe Customer objects are always created

Persisting Session & Redirect

After creation, the session ID is saved on the Cart record, enabling later lookup. Finally, the user is redirected to Stripe’s hosted checkout page.

$this->update(['stripe_checkout_session_id' => $stripeSession->id]);
return Redirect::away($stripeSession->url);

Integration Points

  • Livewire Checkout Component: Invokes stripeCheckout() upon user action
  • SaveOrderService: Prepares orders/order rounds for metadata and post-payment processing
  • StripeController: Handles the /stripe/success redirect and invokes post-payment processing
  • StripeWebhookController: Listens for checkout.session.completed and checkout.session.expired for background sync

Best Practices Card

{
  "title": "Session Deduplication",
  "content": "Always expire any open Stripe session_id before creating a new one to prevent duplicate payments."
}

By centralizing Stripe session creation in the StripeTrait, the application ensures consistency, robust metadata capture, and streamlined order management across all checkout flows.