Skip to main content

Overview

The completeActiveCart mutation converts a cart into an order after payment is captured. This is the final step in the checkout flow and creates an immutable order record.

GraphQL Mutation

mutation CompleteActiveCart($cartId: ID!, $paymentSessionId: ID) {
  completeActiveCart(cartId: $cartId, paymentSessionId: $paymentSessionId) {
    id
    displayId
    status
    total
    subtotal
    tax
    shipping
    discount
    secretKey
    shippingAddress {
      id
      firstName
      lastName
      address1
      city
      province
      postalCode
      country {
        iso2
      }
    }
    lineItems {
      id
      title
      quantity
      formattedTotal
    }
  }
}

Parameters

cartId
string
required
The ID of the cart to complete
paymentSessionId
string
The ID of the payment session to capture. Required for paid orders. Optional for account-based orders (B2B).If omitted, the order is added to the authenticated user’s business account balance instead of processing payment.

Response

id
string
Unique identifier for the created order
displayId
integer
Human-readable order number (timestamp-based)
status
string
Order status. Initially set to pending
secretKey
string
Secret key for guest order tracking (only present for non-authenticated orders)
total
string
Formatted order total including tax and shipping
subtotal
string
Formatted subtotal (sum of line items before tax, shipping, and discounts)
tax
string
Formatted tax amount based on region tax rate
shipping
string
Formatted shipping cost
discount
string
Formatted total discount amount (if applicable)
shippingAddress
object
Delivery address snapshot
lineItems
array
Snapshot of order line items

Example Request

Complete with Payment (Storefront)

const { completeActiveCart } = await openfrontClient.request(
  gql`
    mutation CompleteActiveCart($cartId: ID!, $paymentSessionId: ID) {
      completeActiveCart(
        cartId: $cartId, 
        paymentSessionId: $paymentSessionId
      ) {
        id
        displayId
        status
        total
        secretKey
        shippingAddress {
          firstName
          lastName
          country {
            iso2
          }
        }
      }
    }
  `,
  {
    cartId: "clx123abc456",
    paymentSessionId: "clx456def789"
  }
);

console.log(`Order #${completeActiveCart.displayId} created`);

// Redirect to confirmation page
const countryCode = completeActiveCart.shippingAddress.country.iso2.toLowerCase();
const secretParam = completeActiveCart.secretKey 
  ? `?secretKey=${completeActiveCart.secretKey}` 
  : '';

window.location.href = `/${countryCode}/order/confirmed/${completeActiveCart.id}${secretParam}`;

Complete without Payment (B2B Account)

const { completeActiveCart } = await openfrontClient.request(
  gql`
    mutation CompleteActiveCart($cartId: ID!) {
      completeActiveCart(cartId: $cartId) {
        id
        displayId
        status
        total
      }
    }
  `,
  {
    cartId: "clx123abc456"
  }
);

console.log(`Order #${completeActiveCart.displayId} added to account`);

Payment Flow

Storefront Orders (with paymentSessionId)

When paymentSessionId is provided:
  1. Payment Capture - The system captures payment based on the provider:
    • Stripe: Retrieves and captures the payment intent
    • PayPal: Verifies the PayPal order is approved/completed
    • Cash on Delivery: Marks payment as manual_pending
  2. Order Creation - Creates order with:
    • Line items snapshot (prices frozen at time of purchase)
    • Address snapshots
    • Total calculations
    • Order event log
  3. Payment Record - Creates payment record linked to order
  4. Cart Completion - Marks cart as completed (links to order)

B2B Account Orders (without paymentSessionId)

When paymentSessionId is omitted:
  1. Credit Check - Validates user has sufficient credit limit
  2. Order Creation - Creates order without payment processing
  3. Account Update - Adds order to business account balance
  4. Account Line Item - Creates account line item for tracking

Prerequisites

Before completing a cart, ensure:
Cart has line items - At least one product variant added
Addresses set - Both shipping and billing addresses configured
Shipping method - Shipping method selected
Payment ready - Payment session created and authorized (for paid orders)
Credit available - Sufficient credit limit (for account orders)

Order Creation Process

The completion process:

1. Validation

  • Verifies cart exists and has required data
  • Validates payment session (if provided)
  • Checks credit limit (if account order)

2. Payment Processing

  • Captures payment with provider
  • Verifies payment success
  • Handles payment failures gracefully

3. Order Snapshot

  • Creates immutable OrderLineItems with frozen prices
  • Creates OrderMoneyAmounts for price history
  • Snapshots product and variant data
  • Copies addresses, shipping, and discounts

4. Payment Record

  • Links payment to order
  • Records payment provider data
  • Sets captured timestamp

5. Order Events

  • Creates ORDER_PLACED event
  • Tracks guest vs authenticated orders
  • Initializes order audit trail

Error Handling

Cart not found - Verify the cart ID is correct and cart exists
Payment session not found - Ensure payment session was created and ID is correct
Payment failed - Check payment provider logs for details
Insufficient credit - User needs to increase credit limit or make payment (B2B only)
Missing required data - Ensure addresses and shipping method are set

Guest vs Authenticated Orders

Guest Orders

  • Generate a secretKey for order tracking
  • Create guest user account automatically
  • Require secretKey in confirmation URL
  • Limited order history access

Authenticated Orders

  • No secretKey generated
  • Full order history in account
  • Saved addresses for future orders
  • Email notifications

Next Steps

After completing a cart:
  1. Clear cart cookie on client
  2. Redirect to order confirmation page
  3. Send order confirmation email
  4. Begin fulfillment process
  5. Update inventory

Complete Checkout Flow

Here’s the full cart-to-order flow:
// Step 1: Create cart with region
const { createCart } = await openfrontClient.request(CREATE_CART_MUTATION, {
  data: { region: { connect: { id: regionId } } }
});

// Step 2: Add items to cart
await openfrontClient.request(UPDATE_CART_MUTATION, {
  cartId: createCart.id,
  data: {
    lineItems: {
      create: [{ 
        productVariant: { connect: { id: variantId } }, 
        quantity: 1 
      }]
    }
  }
});

// Step 3: Set addresses
await openfrontClient.request(UPDATE_CART_MUTATION, {
  cartId: createCart.id,
  data: {
    email: "[email protected]",
    shippingAddress: { connect: { id: addressId } },
    billingAddress: { connect: { id: addressId } }
  }
});

// Step 4: Create payment sessions
const { createActiveCartPaymentSessions } = await openfrontClient.request(
  CREATE_PAYMENT_SESSIONS_MUTATION,
  { cartId: createCart.id }
);

// Step 5: Complete cart (after payment authorization)
const { completeActiveCart } = await openfrontClient.request(
  COMPLETE_CART_MUTATION,
  {
    cartId: createCart.id,
    paymentSessionId: paymentSession.id
  }
);

console.log(`Order #${completeActiveCart.displayId} created successfully!`);

Build docs developers (and LLMs) love