Skip to main content
This tutorial was written by Claude Code (an AI) and has not yet been reviewed. Follow along with caution. If the tutorial was helpful or a specific part was not clear/correct, please provide feedback at the bottom of the page. Thank you.
This guide covers CoCart Preview API features. The checkout endpoints require CoCart v4.6 and up with the Preview API enabled.

Overview

The CoCart Checkout API provides a complete solution for processing e-commerce transactions through three main endpoints:
  • GET /checkout - Retrieve checkout data including cart contents, totals, and available payment/shipping methods
  • POST /checkout - Update checkout information such as billing address, shipping address, and payment method
  • PUT /checkout - Process the final checkout and create the order

Prerequisites

Before implementing the checkout flow, ensure you have:
  1. A valid cart with items added
  2. Proper authentication (Cart Key, Basic Auth, or JWT)
  3. Required customer information (billing address at minimum)
  4. Available payment and shipping methods configured in WooCommerce

Basic Checkout Flow

1

Get Checkout Data

Retrieve current checkout information to display available options
2

Update Checkout Information

Set billing/shipping addresses and selected payment/shipping methods
3

Process Checkout

Complete the transaction and create the order

Authentication

The CoCart Checkout API uses WooCommerce consumer key/secret authentication for secure access:

Consumer Keys

Required for all requests - WooCommerce API keys provide secure, authenticated access

Customer Context

Optional customer ID - Include for registered customer features and personalization

Authentication Methods

  • Consumer Key/Secret: Required for all API access (see Consumer Key Setup)
  • Cart Key: Identifies the customer’s cart session and automatically provides customer context for registered users

Request Structure

// All requests require consumer authentication
const url = `/wp-json/cocart/preview/checkout?consumer_key=ck_123&consumer_secret=cs_456`;

// Cart key identifies the specific cart and customer (if logged in)
const headers = {
    'Cart-Key': 'your-cart-key-here', // Contains customer context automatically
    'Content-Type': 'application/json'
};
The cart key automatically contains customer context for registered users. No separate customer ID parameter is needed since WooCommerce sessions already track the user ID.

API Endpoints

Get Checkout Data

Retrieve current checkout information including cart contents, totals, addresses, and available shipping/payment methods.
  • cURL
  • PHP
  • JavaScript
curl -X GET "https://yoursite.com/wp-json/cocart/preview/checkout?consumer_key=ck_1234567890abcdef&consumer_secret=cs_1234567890abcdef" \
  -H "Cart-Key: your-cart-key-here" \
  -H "Content-Type: application/json"

Update Checkout Information

Update checkout details such as billing address, shipping address, payment method, or shipping method.
  • cURL
  • PHP
  • JavaScript
curl -X POST "https://yoursite.com/wp-json/cocart/preview/checkout" \
  -H "Cart-Key: your-cart-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "billing_address": {
      "first_name": "John",
      "last_name": "Doe",
      "email": "john@example.com",
      "phone": "555-1234",
      "address_1": "123 Main St",
      "address_2": "Apt 4B",
      "city": "Anytown",
      "state": "CA",
      "postcode": "12345",
      "country": "US"
    }
  }'

Process Checkout

Complete the checkout process to create an order and process payment.
  • cURL
  • PHP
  • JavaScript
curl -X PUT "https://yoursite.com/wp-json/cocart/preview/checkout" \
  -H "Cart-Key: your-cart-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "billing_address": {
      "first_name": "John",
      "last_name": "Doe",
      "email": "john@example.com",
      "phone": "555-1234",
      "address_1": "123 Main St",
      "city": "Anytown",
      "state": "CA",
      "postcode": "12345",
      "country": "US"
    },
    "payment_method": "stripe",
    "shipping_method": "flat_rate:1"
  }'

Response Examples

Successful Checkout Response

{
  "order_id": 123,
  "status": "processing",
  "order_key": "wc_order_abc123def456",
  "order_number": "123",
  "payment_result": {
    "payment_status": "success",
    "redirect_url": "https://yoursite.com/checkout/order-received/123/?key=wc_order_abc123def456",
    "message": "Payment completed successfully"
  },
  "billing_address": {
    "first_name": "John",
    "last_name": "Doe",
    "email": "john@example.com",
    "address_1": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "postcode": "12345",
    "country": "US"
  },
  "cart_key": null
}

Error Response Example

{
  "code": "cocart_checkout_empty_cart",
  "message": "Cannot checkout with empty cart.",
  "data": {
    "status": 400
  }
}

Advanced Usage

Payment Methods Integration

Get available payment methods before showing checkout form:
  • cURL
  • PHP
  • JavaScript
curl -X GET "https://yoursite.com/wp-json/cocart/preview/checkout/payment-methods" \
  -H "Cart-Key: your-cart-key-here" \
  -H "Content-Type: application/json"

Payment Context for Client-Side Processing

For payment gateways that require client-side processing (like Stripe Elements):
  • cURL
  • JavaScript
curl -X POST "https://yoursite.com/wp-json/cocart/preview/checkout/payment-context" \
  -H "Cart-Key: your-cart-key-here" \
  -H "Content-Type: application/json" \
  -d '{"payment_method": "stripe"}'

Payment Processing

The checkout API supports both simple server-side payment methods and complex client-side payment processing. The approach depends on your payment gateway:

Server-Side Payment Methods

For payment methods that process entirely server-side (Bank Transfer, Check, COD), you only need to specify the payment method:
const checkoutData = {
    billing_address: billingAddress,
    payment_method: 'bacs', // Bank transfer
    shipping_method: 'flat_rate:1'
};

await processCheckout(checkoutData);

Client-Side Payment Methods

For gateways requiring client-side processing (Stripe, PayPal, Square), you need to:
  1. Create Payment Context - Get gateway configuration from the server
  2. Collect Payment Details - Use the gateway’s SDK to securely collect payment info
  3. Process Payment - Handle the payment with the gateway
  4. Submit Checkout - Include payment data in your checkout request

Payment Gateway Integration Guides

For detailed integration examples with specific payment gateways, see our dedicated tutorials:

Basic Payment Data Structure

When submitting checkout with payment data, include the gateway-specific information:
const checkoutData = {
    billing_address: {
        first_name: 'John',
        last_name: 'Doe',
        email: 'john@example.com',
        // ... other address fields
    },
    payment_method: 'stripe', // Gateway ID
    shipping_method: 'flat_rate:1',

    // Gateway-specific payment data (see individual tutorials)
    payment_data: {
        payment_intent_id: 'pi_1234567890',
        payment_method_id: 'pm_1234567890',
        // ... other gateway-specific fields
    }
};

Error Handling

Common error scenarios and how to handle them:

Empty Cart

Code: cocart_checkout_empty_cartSolution: Redirect user to shop or cart page

Invalid Address

Code: cocart_checkout_invalid_addressSolution: Validate and correct address fields

Payment Failed

Code: cocart_payment_failedSolution: Display error message and allow retry

Insufficient Stock

Code: cocart_insufficient_stockSolution: Update quantities or remove unavailable items
function handleCheckoutError(error) {
    switch (error.code) {
        case 'cocart_checkout_empty_cart':
            window.location.href = '/shop';
            break;

        case 'cocart_checkout_invalid_address':
            highlightInvalidFields(error.data.invalid_fields);
            showError('Please correct the highlighted fields');
            break;

        case 'cocart_payment_failed':
            showError(`Payment failed: ${error.data.message}`);
            enableRetryButton();
            break;

        case 'cocart_insufficient_stock':
            updateCartQuantities(error.data.stock_data);
            showError('Some items have limited stock. Cart updated.');
            break;

        default:
            showError('An unexpected error occurred. Please try again.');
    }
}

Payment Processing Approaches

Development vs Production

The payment methods endpoint provides different levels of information based on user permissions:
  • Development/Debugging
  • Production Implementation
For users with admin permissions, the payment methods endpoint includes debug information to help understand gateway configurations:
// Only available to admin users
const response = await fetch('/wp-json/cocart/preview/checkout/payment-methods', {
    headers: {
        'Authorization': `Bearer ${adminJwtToken}`, // Admin user required
        'Cart-Key': cartKey
    }
});

const data = await response.json();
console.log(data.debug_info); // Gateway configuration details
Response with debug info:
{
  "payment_methods": {
    "stripe": {
      "id": "stripe",
      "title": "Credit Card",
      "enabled": true
    }
  },
  "debug_info": {
    "payment_context": {
      "stripe": {
        "publishable_key": "pk_test_xxx",
        "webhook_endpoint": "/wc-api/stripe",
        "gateway_mode": "test"
      }
    },
    "note": "Debug information - DO NOT use in production"
  }
}
Debug information is only available to users with manage_options capability and should never be used in production applications.

Gateway Configuration Alignment

Important: Your frontend gateway configuration must match your WooCommerce store settings:
WooCommerce Store Settings:
WooCommerce → Payments → Stripe
- Publishable Key: pk_live_abc123...
- Secret Key: sk_live_xyz789...
- Webhook Endpoint: yourstore.com/wc-api/stripe
Frontend Implementation:
// Must use the SAME publishable key
const stripe = Stripe('pk_live_abc123...'); // Same as store settings
WooCommerce Store Settings:
WooCommerce → Payments → PayPal
- Client ID: your_paypal_client_id
- Environment: live
Frontend Implementation:
// Must use the SAME client ID and environment
paypal.Buttons({
  env: 'live', // Same as store settings
  client: {
    live: 'your_paypal_client_id' // Same as store settings
  }
});

Rate Limiting for Checkout Operations

The checkout API includes enhanced rate limiting to prevent abuse:
// Default rate limits (can be customized via filters)
- GET /checkout: 20 requests per minute
- PUT /checkout: 5 requests per minute
- GET /payment-methods: 30 requests per minute
- GET /payment-methods (with debug): 1 request per minute
Use the cocart_api_rate_limits filter to customize limits for your application:
add_filter('cocart_api_rate_limits', function($limits) {
    $limits['checkout_get'] = 50; // Increase GET limit
    $limits['checkout_put'] = 3;  // Decrease POST limit
    return $limits;
});

Best Practices

Security

  • Never expose consumer secrets in client-side code
  • Use environment variables for storing API credentials
  • Rotate consumer keys regularly and monitor usage
  • Implement rate limiting to prevent abuse
  • Log authentication failures for security monitoring
  • Validate cart session ownership to prevent cart hijacking
  • Extract customer context from cart sessions rather than relying on client-provided IDs
  • Sanitize all input data server-side regardless of client validation
  • Use HTTPS exclusively for all API communications
  • Implement proper session management for cart keys with sufficient entropy
  • Clear sensitive data after successful transactions
  • Follow PCI DSS guidelines for payment data handling
  • Use payment gateway tokenization instead of storing card data
  • Implement webhook validation for payment confirmations
  • Monitor for fraudulent patterns and implement blocking
  • Use secure payment contexts with time-limited validity

Performance

  • Use longer timeouts for checkout processing (60+ seconds)
  • Implement request queuing to handle rate limits gracefully
  • Cache payment methods and shipping options when possible
  • Batch API calls to minimize round trips
  • Monitor API response times and optimize slow endpoints
  • Lazy load payment SDKs to improve initial page load
  • Implement progressive enhancement for checkout forms
  • Use efficient state management to avoid unnecessary re-renders
  • Optimize bundle size by code splitting payment methods
  • Implement proper loading states during async operations

User Experience

  • Validate forms in real-time but don’t be overly aggressive
  • Provide clear error messages with actionable guidance
  • Auto-format input fields (card numbers, phone numbers, etc.)
  • Support keyboard navigation and screen readers
  • Remember user preferences for returning customers
  • Show progress indicators for multi-step processes
  • Handle payment redirects gracefully with proper loading states
  • Provide multiple payment options to reduce abandonment
  • Support guest and registered checkout flows seamlessly
  • Implement proper success/failure handling with clear next steps

Development

  • Test with different payment gateways and edge cases
  • Use dedicated test/sandbox environments for integration testing
  • Implement automated testing for critical checkout paths
  • Test rate limiting and error scenarios thoroughly
  • Validate webhook handling with test data
  • Follow WordPress and WooCommerce coding standards
  • Implement proper error logging without exposing sensitive data
  • Use version control for API changes and rollbacks
  • Document API integrations thoroughly for team knowledge
  • Monitor production performance and error rates

Consumer Key Management

  • Use descriptive names for different applications/environments
  • Set appropriate permissions (read, write, read/write)
  • Generate separate keys for each application or environment
  • Document key purposes and ownership for team management
  • Store keys in secure configuration (environment variables, secure vaults)
  • Never commit keys to version control systems
  • Rotate keys periodically as part of security maintenance
  • Monitor key usage for suspicious patterns
  • Revoke compromised keys immediately and generate replacements
  • Track API usage patterns per consumer key
  • Set up alerts for unusual activity or rate limit hits
  • Monitor authentication failures and investigate patterns
  • Review key permissions regularly for principle of least privilege
  • Maintain audit logs for compliance and troubleshooting
Remember to test your checkout implementation thoroughly with different scenarios including successful payments, failed payments, address validation, and edge cases like empty carts or out-of-stock items.
I