Commerce: Checkout and Order Processing – Order Processing Integration

This section explains how the system handles the transition from a user’s checkout to a fully recorded order. It covers how SaveOrderService processes carts, creates orders and order rounds, and how Stripe metadata is used for reconciliation and reporting.

SaveOrderService

This service encapsulates core order creation and payment processing logic. It ensures carts are transformed into orders in one or more “rounds,” and payments are recorded against those rounds.

  • Resides at app/Services/SaveOrderService.php.
  • Uses Laravel’s database transactions for atomicity.
  • Integrates with Stripe via the official PHP SDK.

1. processSessionId(string|Session $session, bool $deleteCart = true)

Retrieves the cart by Stripe session ID, then delegates to processCart().

public function processSessionId($session, $deleteCart = true)
{
    // Retrieve or fetch Stripe\Session
    // Find Cart by stripe_checkout_session_id
    return $this->processCart($cart);
}

(Source: )

2. processCart(Cart $cart)

Converts a cart into one or more OrderRound models, then dispatches synchronous jobs to finalize each round.

  • Restores session data for billing, line items, coupons.
  • Fails if the cart is empty.
  • Determines relevant events (single or upsell products).
  • Wraps round creation and job dispatch in a DB transaction.
public function processCart(Cart $cart)
{
    $sessionData = $cart->restoreData();
    $events      = $this->getEvents($cart);
    $orderRounds = $this->processEvents($events, $cart, $sessionData);

    return DB::transaction(function () use ($orderRounds, $cart) {
        foreach ($orderRounds as $orderRound) {
            ProcessOrder::dispatchSync($orderRound);
        }
        if ($cart->total() == 0) {
            $cart->delete();
        }
        return collect($orderRounds);
    });
}

(Source: )

3. processPayments(Session $session)

Completes payment processing for each incomplete OrderRound associated with the Stripe session metadata.

  • Reads Order Rounds and Cart ID from $session->metadata.
  • Saves a Payment record and updates round status to Completed.
  • Marks the parent Order complete if all its rounds finish.
  • Deletes the Cart.
public function processPayments(Session $session)
{
    $orderRounds = OrderRound::whereIn('id', explode(',', $session->metadata['Order Rounds']))
        ->where('order_status', '!=', 'Completed')
        ->get();

    foreach ($orderRounds as $orderRound) {
        $payment = $this->savePayment(...);
        $orderRound->update([
            'order_status'      => 'Completed',
            'stripe_payment_id' => $payment->stripe_id,
        ]);
        // Mark full order completed if all rounds done
        event(new OrderCompleted($orderRound->order, $orderRound->round));
    }

    $orderRounds->first()->order->calculateTotal();
    Cart::find($session->metadata['Cart ID'])->delete();
}

(Source: )

4. processEvents(Collection $events, Cart $cart, array $sessionData)

Creates or updates an Order for each event and adds an OrderRound with the current cart contents.

  • Supports free orders (auto-complete) and multi-round logic.
  • Tracks and rejects subscription upsells not tied to an event.
  • Increments current_round on repeat checkouts.
private function processEvents($events, $cart, $sessionData)
{
    $email  = $sessionData['billing']['email'];
    $isFree = $cart->total() == 0;
    $orderRounds = [];

    foreach ($events as $event) {
        $order = Order::firstOrCreate(
            ['email' => $email, 'event_id' => $event->id],
            ['status' => $isFree ? 'Completed' : 'Pending', 'current_round' => 1]
        );
        // Build cart_content array...
        $orderRound = OrderRound::create([...]);
        $orderRounds[] = $orderRound;
    }

    return $orderRounds;
}

(Source: )


🛠 Metadata Tracking

Stripe sessions include metadata that ties back to internal entities for post-payment processing and reporting:

Key Description
Event ID Comma-separated IDs of targeted Event models
Type Revenue classification (e.g., “cart”, “subscription”)
Order ID The primary key of the first Order created
Order Rounds IDs of all OrderRound records for this session
Cart ID Internal Cart model ID for cleanup

This metadata is set when creating the checkout session in Livewire’s checkout logic .


⚙️ Integration Points

  • Checkout Component: Initiates Stripe session and redirects user.
  • StripeController::success: Handles immediate success redirects, may trigger processPayments().
  • StripeWebhookController: Listens for checkout.session.completed, then invokes SaveOrderService::processPayments.
  • SyncMissingStripePayments (Console Command): Backsyncs Stripe payments by calling processSessionId() on historical sessions.

Order Processing Flowchart

flowchart TD
  U[User clicks Checkout] --> C[Cart → Stripe Session]
  C --> S[Stripe Hosted Checkout]
  S -- success_url --> SC[StripeController::success]
  SC -->|metadata exists| Svc[SaveOrderService::processPayments]
  S -- webhook --> WH[StripeWebhookController]
  WH --> Svc
  Svc --> OR[OrderRound status updated]
  OR --> O[Order marked Completed]
  OR --> PDB[Payment record saved]

Dependencies & Relationships

  • Models: Cart, Order, OrderRound, Payment, Event
  • Jobs: ProcessOrder handles item creation, notifications
  • Events: OrderCompleted triggers downstream operational tasks
  • Stripe SDK: Stripe\Checkout\Session, Stripe\Stripe

All dependencies are imported at the top of SaveOrderService .


Card

{
  "title": "Atomic Order Creation",
  "content": "SaveOrderService wraps round creation and job dispatch in a DB transaction to ensure data integrity."
}