> ## Documentation Index
> Fetch the complete documentation index at: https://paypal-sb-staging.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cart orchestration

The unified <a href="https://docs.paypal.ai/reference/api/rest/cart-operations/create-cart" target="_blank">Cart API</a> abstracts platform-specific complexities, letting your agents to work seamlessly with supported platforms through a single integration point. This guide explains how to integrate PayPal's Cart API v1 into your commerce platform using the unified `PayPalCart` schema.

> **Important:** To access and use store sync, including cart orchestration, merchants must complete <a href="https://www.paypal.com/us/business/ai" target="_blank">this form</a> to contact the AI team at PayPal and request access.

This guide explains:

* How PayPal's Cart API fits into your checkout flow
* When to use each API endpoint and why
* How to handle complex scenarios, including variants, discounts, age verification, and gift cards
* Common integration mistakes and how to avoid them

You'll also get to explore complete HTTP examples and implementation patterns that you can adapt to your tech stack.

## Modern commerce architecture

PayPal's Cart API enables agentic commerce, where AI agents handle shopping on behalf of customers through a sophisticated integration chain. This architecture connects customers, AI agents, and merchant systems seamlessly, creating a new paradigm for online shopping.

```
Customer ↔ AI Agent ↔ PayPal Commerce Platform ↔ PayPal ↔ Your Merchant API
```

What this means:

* Customers interact naturally with AI agents using voice or chat.
* AI agents assess intent and make shopping decisions for customers.
* PayPal's <a href="https://www.paypal.com/si/webapps/mpp/commerce-platform" target="_blank">Commerce Platform</a> orchestrates the entire payment and cart flow.
* PayPal Catalog provides catalog ingestion, product discovery, and validation. It uses product selections to route orders to the correct merchant API.
* The merchant's API handles inventory, pricing, and order fulfillment.

## 1. Product discovery

The shopping journey begins when customers express their needs in natural language. The AI agent interprets this intent and searches PayPal's ingested catalog to find matching products across multiple merchants.

```
Customer: "I need a blue t-shirt"
    ↓
AI Agent → PayPal Catalog (ingested products)
    ↓
PayPal returns product data with merchant routing info
    ↓
AI Agent: "Found perfect shirts! Here are your options..."
```

## 2. Cart creation and management

After a customer selects products, the AI agent creates and manages the shopping cart through PayPal's <a href="https://www.paypal.com/si/webapps/mpp/commerce-platform" target="_blank">Commerce Platform</a>. This process validates product availability, pricing, and shipping options in real-time with your merchant API.

```
Customer: "I'll take the medium one"
    ↓
AI Agent → PayPal Commerce Platform
    ↓
Shopping Cart validates with Honey (product details, merchant routing)
    ↓
Shopping Cart → Your Merchant API: POST /merchant-cart
    ↓
Your API responds: Cart created with pricing, shipping options
```

## 3. Seamless checkout

The final step completes the purchase without requiring customers to leave the conversation. PayPal's Smart Wallet handles payment authentication and processing while the AI agent confirms order details.

```
Customer: "Checkout with PayPal"
    ↓
AI Agent → PayPal Smart Wallet (no redirect needed)
    ↓
PayPal → Shopping Cart → Your Merchant API: Complete checkout
    ↓
AI Agent: "Order confirmed! Arrives Tuesday."
```

## Benefits

This integration delivers value across all stakeholders in the commerce ecosystem. Here's how each party benefits from the agentic commerce approach.

**For customers:**

* **Natural conversation** - No complex navigation or forms
* **Intelligent assistance** - AI understands preferences and context
* **Seamless payments** - PayPal smart wallet integration
* **Proactive updates** - AI handles tracking and delivery information

**For merchants:**

* **Automated orders** - AI agents create perfect carts without human intervention
* **Reduced friction** - Customers never leave the conversation
* **Higher conversion** - AI optimizes for successful purchases
* **Future-ready** - Built for the next generation of commerce

**For developers:**

* **Simple integration** - Just implement the merchant API endpoints using unified PayPalCart schema
* **Honey handles discovery** - Catalog ingestion and product routing intelligence
* **Real-time inventory** - Your API provides live pricing and availability
* **Rich error handling** - Clear validation and resolution options

## Cart status fields

The PayPal Cart API uses three key status indicators that work together to communicate cart state and validation issues. Understanding these fields is crucial for proper error handling and cart lifecycle management.

```json theme={null}
{
  "id": "CART-123",
  "status": "INCOMPLETE",
  "validation_status": "REQUIRES_ADDITIONAL_INFORMATION",
  "validation_issues": [
    {
      "code": "DATA_ERROR",
      "type": "MISSING_FIELD",
      "message": "Shipping address is required for delivery",
      "context": {
        "specific_issue": "MISSING_SHIPPING_ADDRESS"
      }
    }
  ]
}
```

### 1. `status` - Business outcome (merchant controlled)

Indicates what happened to the cart

| Value        | Description                                        |
| ------------ | -------------------------------------------------- |
| `CREATED`    | Cart was successfully created and is ready for use |
| `INCOMPLETE` | Cart has issues that need resolution               |
| `READY`      | Cart is validated and ready for checkout           |
| `COMPLETED`  | Order is finalized and payment was captured        |

### 2. `validation_status` - Item and data validation

Indicates whether the cart contents and data are valid for checkout:

* All items are available with current pricing.
* Required information is complete (shipping address, customer data).
* No business rule violations exist.
* The `validation_issues` array is empty.
* Transaction can proceed to checkout.

| Value     | Description                      |
| --------- | -------------------------------- |
| `VALID`   | Ready for checkout               |
| `INVALID` | Has problems that block checkout |
|           | Needs more data to proceed       |

If the value is `REQUIRES_ADDITIONAL_INFORMATION`, the `validation_issues` array indicates what information is needed, for example:

* Required fields are missing (shipping address, checkout fields).
* Items and pricing are valid but require additional customer input.

### 3. `validation_issues` - Specific problems with type classification

Detailed list of issues that need resolution with clear categorization

| Field           | Description                                                            |
| --------------- | ---------------------------------------------------------------------- |
| `MISSING_FIELD` | Required information missing (shipping address, checkout fields, etc.) |
| `INVALID_DATA`  | Provided data is incorrect or invalid                                  |
| `BUSINESS_RULE` | Business logic violations (out of stock, minimum order, etc.)          |

The following example shows the structure.

```json theme={null}
[
  {
    "code": "DATA_ERROR",
    "type": "MISSING_FIELD",
    "message": "Shipping address is required",
    "context": {
      "specific_issue": "MISSING_SHIPPING_ADDRESS"
    },
    "variant_id": "optional-if-item-specific"
  }
]
```

### `validation_status` decision matrix

Available statuses can be one of the following options.

| Status                            | Description                                                   |
| --------------------------------- | ------------------------------------------------------------- |
| `VALID`                           | Everything is in order for checkout                           |
| `REQUIRES_ADDITIONAL_INFORMATION` | Value is valid, but more data is needed to proceed            |
| `INVALID`                         | Intervention is necessary before the transaction can continue |

See the following table to understand when to use each status.

| Situation                        | validation\_status                | validation\_issues                                                                                     | Action Required                     |
| -------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------ | ----------------------------------- |
| **All good, ready for checkout** | `VALID`                           | `[]` (empty)                                                                                           | Proceed to checkout                 |
| **Missing shipping address**     | `REQUIRES_ADDITIONAL_INFORMATION` | `[{code: "DATA_ERROR", type: "MISSING_FIELD", context: {specific_issue: "MISSING_SHIPPING_ADDRESS"}}]` | Collect shipping address            |
| **Age verification needed**      | `REQUIRES_ADDITIONAL_INFORMATION` | `[{code: "DATA_ERROR", type: "MISSING_FIELD", context: {specific_issue: "MISSING_CHECKOUT_FIELDS"}}]`  | Complete age verification           |
| **Item out of stock**            | `INVALID`                         | `[{code: "INVENTORY_ISSUE", type: "BUSINESS_RULE"}]`                                                   | Remove item or suggest alternatives |
| **Price changed**                | `INVALID`                         | `[{code: "PRICING_ERROR", type: "BUSINESS_RULE"}]`                                                     | Customer must accept new price      |
| **Invalid postal code**          | `INVALID`                         | `[{code: "SHIPPING_ERROR", type: "INVALID_DATA"}]`                                                     | Correct address format              |
| **Payment declined**             | `INVALID`                         | `[{code: "PAYMENT_ERROR", type: "BUSINESS_RULE"}]`                                                     | Try different payment method        |

### Common Status Combinations

| Scenario                      | HTTP Status   | Cart status  | validation\_status                | validation\_issues                                                                                     |
| ----------------------------- | ------------- | ------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------ |
| **Cart Created Successfully** | `201 Created` | `CREATED`    | `VALID`                           | `[]`                                                                                                   |
| **Item Out of Stock**         | `200 OK`      | `INCOMPLETE` | `INVALID`                         | `[{code: "INVENTORY_ISSUE", type: "BUSINESS_RULE", context: {specific_issue: "ITEM_OUT_OF_STOCK"}}]`   |
| **Missing Shipping**          | `200 OK`      | `INCOMPLETE` | `REQUIRES_ADDITIONAL_INFORMATION` | `[{code: "DATA_ERROR", type: "MISSING_FIELD", context: {specific_issue: "MISSING_SHIPPING_ADDRESS"}}]` |
| **Ready for Checkout**        | `200 OK`      | `READY`      | `VALID`                           | `[]`                                                                                                   |
| **Order Completed**           | `200 OK`      | `COMPLETED`  | `VALID`                           | `[]`                                                                                                   |

### HTTP status code strategy

The PayPal Cart API uses a combination of HTTP status codes and cart status fields to communicate the outcome of requests.

#### Business logic issues → 200 OK + validation\_issues

Use `200 OK` for business scenarios that AI agents can understand and potentially resolve:

* Cart validation issues (out of stock, price changes)
* Missing required information (shipping address, checkout fields)
* Payment processing issues (declined payments, business rules)

#### Technical issues → HTTP error codes

Use proper HTTP error codes for technical problems:

* `400 Bad Request` - Invalid request format, missing required parameters
* `404 Not Found` - Cart ID doesn't exist
* `500 Internal Server Error` - System failures, service unavailable

## Scenario

Imagine a simple customer interaction where an AI agent helps a customer find and purchase a blue t-shirt.

> Customer: "I need a medium blue t-shirt"
> AI Agent: processes intent and searches inventory
> AI Agent: creates cart via PayPal Commerce Platform, orchestrating with the Merchant API

```http theme={null}
POST /api/paypal/v1/merchant-cart
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "items": [
    {
      "variant_id": "TSHIRT-BLUE-M",
      "quantity": 1,
      "name": "Blue Cotton T-Shirt (Medium)",
      "price": {
        "currency_code": "USD",
        "value": "25.00"
      }
    }
  ],
  "customer": {
    "email_address": "customer@example.com"
  },
  "shipping_address": {
    "address_line_1": "123 Main Street",
    "admin_area_2": "San Jose",
    "admin_area_1": "CA",
    "postal_code": "95131",
    "country_code": "US"
  },
  "payment_method": {
    "type": "paypal"
  }
}

```

> AI agent: "Found perfect blue t-shirt in medium! \$25 total. Ready to checkout?"

#### PayPal Cart API returns cart information

```json theme={null}
{
  "id": "CART-ABC123",
  "status": "CREATED",
  "items": [
    {
      "variant_id": "TSHIRT-BLUE-M",
      "quantity": 1,
      "name": "Blue Cotton T-Shirt (Medium)",
      "price": { "currency_code": "USD", "value": "25.00" }
    }
  ],
  "totals": {
    "subtotal": { "currency_code": "USD", "value": "25.00" },
    "shipping": { "currency_code": "USD", "value": "5.99" },
    "tax": { "currency_code": "USD", "value": "2.70" },
    "handling": { "currency_code": "USD", "value": "1.50" },
    "custom_charges": { "currency_code": "USD", "value": "2.00" },
    "total": { "currency_code": "USD", "value": "37.19" }
  }
}
```

#### AI completes checkout

> AI Agent: "Ready to checkout with PayPal?"
> Customer: "Yes, proceed"
> AI Agent: seamlessly handles PayPal smart wallet approval (no redirect needed)

```http theme={null}
POST /api/paypal/v1/merchant-cart/CART-ABC123/checkout
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "payment_method": {
    "type": "paypal",
    "token": "EC-7U8939823K567",
    "payer_id": "PAYER123456789"
  },
  "accepted_policies": [
    "terms_of_service"
  ]
}

```

> AI Agent: "Order confirmed! Your t-shirt will arrive Tuesday."

## Authentication - PayPal-supplied JWT tokens

1. PayPal-issued - Tokens are generated and managed by PayPal, not merchants.
2. Request authentication - Included in Authorization header for every API call.
3. Merchant identification - Token contains merchant ID and permissions.
4. Security verification - Verify token signature using PayPal's public keys.

### 1. Receive token in authorization header

```http theme={null}
POST /api/paypal/v1/merchant-cart
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjaGFudF9pZCI6Ik1FUkNIQU5ULTEyMyIsInNjb3BlIjpbImNhcnQiXSwiaWF0IjoxNzE5MjQwMDAwLCJleHAiOjE3MTkyNDM2MDB9.signature
Content-Type: application/json

{
  ...cart create request body
}
```

### 2. Verify token

1. Parse Authorization header: "Bearer \<token>"
2. Verify token signature using PayPal public keys
3. Validate token expiration
4. Check required scopes (e.g., "cart", "complete")

## API endpoints

The Cart API provides 3 core endpoints that handle the complete cart lifecycle. Each endpoint serves a specific purpose in the shopping flow.

### Unified PayPalCart schema

```json theme={null}
{
  "items": [...],
  "customer": {...},
  "shipping_address": {...},
  "payment_method": {...},
  "checkout_fields": [...],
  "gift_options": {...}
}
```

### `POST /merchant-cart` - Create cart

Creates a new shopping cart with specified items, customer info, shipping address, and payment method.

#### Basic creation

```http theme={null}
POST /api/paypal/v1/merchant-cart
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "items": [
    {
      "variant_id": "PRODUCT-001",
      "quantity": 1,
      "name": "Basic T-Shirt",
      "price": {"currency_code": "USD", "value": "25.00"}
    }
  ],
  "payment_method": {
    "type": "paypal"
  }
}
```

#### Advanced creation (everything at once)

```http theme={null}
POST /api/paypal/v1/merchant-cart
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "items": [...],
  "shipping_address": {...},
  "customer": {"email_address": "customer@example.com"},
  "payment_method": {"type": "paypal"},
  "checkout_fields": [...]
}
```

### `PUT /merchant-cart/{id}` - Update cart

Updates an existing cart by replacing its contents with the provided data. Use this endpoint to add or remove items, change quantities, update shipping address, apply discounts, and so on.

> Note: PUT replaces the ENTIRE cart. Any fields that you do not include in your request will be **removed or reset**. This is a complete replacement operation, not a merge.

Include ALL current cart data when making changes, as shown in the following example.

```json theme={null}
{
  "items": [
    {"variant_id": "EXISTING-ITEM", "quantity": 1},
    {"variant_id": "NEW-ITEM", "quantity": 1}
  ],
  "customer": {
    "email_address": "customer@example.com"
  },
  "shipping_address": {
    "address_line_1": "123 Current Street",
    "admin_area_2": "Current City",
    "admin_area_1": "CA",
    "postal_code": "95131",
    "country_code": "US"
  },
  "checkout_fields": [...],
  "payment_method": {...}
}
```

### `POST /merchant-cart/{id}/checkout` - Complete checkout

```http theme={null}
POST /api/paypal/v1/merchant-cart/CART-123/checkout
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "payment_method": {
    "type": "paypal",
    "token": "EC-7U8939823K567",
    "payer_id": "PAYER123456789"
  },
  "checkout_fields": [
    {
      "type": "AGE_VERIFICATION_21_PLUS",
      "status": "COMPLETED",
      "value": {
        "confirmed": true,
        "verification_method": "self_declaration",
        "verification_date": "2024-06-24T14:30:00Z"
      }
    }
  ],
  "accepted_policies": [
    "terms_of_service",
    "privacy_policy"
  ]
}
```

## PayPal Orders API Integration Pattern

Behind the scenes, the PayPal Cart API integrates with PayPal's Orders API v2 to manage payment tokens and process transactions. Understanding this relationship helps you implement proper payment handling.

When implementing the Cart API, merchants must integrate with **<a href="https://developer.paypal.com/docs/api/orders/v2/" target="_blank" rel="noopener noreferrer">PayPal Orders API v2</a>** to handle payment tokens and order updates. This section clarifies when to CREATE vs PATCH orders based on cart lifecycle.

### 1. Initial cart creation → CREATE order

```mermaid theme={null}
sequenceDiagram
    participant PS as PayPal Commerce Platform
    participant M as Merchant API
    participant PP as PayPal Orders API

    PS->>M: POST /merchant-cart<br/>Initial cart creation
    Note over M: Validate inventory<br/>Calculate initial totals
    M->>PP: POST /v2/orders<br/>Create order with initial totals
    PP-->>M: Order created + order_id + token
    M-->>PS: Cart created + payment_method.token
```

### 2. Cart updates → PATCH order

```mermaid theme={null}
sequenceDiagram
    participant PS as PayPal Commerce Platform
    participant M as Merchant API
    participant PP as PayPal Orders API

    PS->>M: PUT /merchant-cart/{id}<br/>Update cart (shipping, coupons, etc.)
    Note over M: Recalculate totals<br/>Apply changes
    M->>PP: PATCH /v2/orders/{order_id}<br/>Update totals, shipping, tax
    PP-->>M: Order updated successfully
    M-->>PS: Cart updated + new totals
```

### When to CREATE or PATCH

| Scenario                    | PayPal Orders Action    | Reason                       |
| --------------------------- | ----------------------- | ---------------------------- |
| **Initial cart creation**   | `POST /v2/orders`       | Create new payment context   |
| **Add/remove items**        | `PATCH /v2/orders/{id}` | Update totals                |
| **Apply/remove coupons**    | `PATCH /v2/orders/{id}` | Update totals                |
| **Update shipping address** | `PATCH /v2/orders/{id}` | Update shipping + tax        |
| **Change quantities**       | `PATCH /v2/orders/{id}` | Update totals                |
| **Payment token expired**   | `POST /v2/orders`       | Create fresh payment context |
| **New cart after checkout** | `POST /v2/orders`       | New transaction              |

### Examples

The following code snippets illustrate how to implement cart creation and updates.

#### Cart creation with order

```javascript theme={null}
// Merchant API implementation
async function createCart(cartData) {
  const cart = await validateAndCalculateCart(cartData);

  const paypalOrder = await paypalClient.orders.create({
    intent: "CAPTURE",
    purchase_units: [
      {
        amount: {
          currency_code: cart.totals.total.currency_code,
          value: cart.totals.total.value,
          breakdown: {
            item_total: {
              currency_code: "USD",
              value: cart.totals.subtotal.value,
            },
            shipping: {
              currency_code: "USD",
              value: cart.totals.shipping.value,
            },
            tax_total: { currency_code: "USD", value: cart.totals.tax.value },
          },
        },
      },
    ],
  });

  cart.payment_method = {
    type: "PAYPAL",
    token: paypalOrder.id, // PayPal uses order_id as token
  };

  return cart;
}
```

#### Cart update with order PATCH

```javascript theme={null}
async function updateCart(cartData) {
  const cart = await applyUpdatesAndRecalculate(cartData);

  await paypalClient.orders.patch(cart.paypal_order_id, [
    {
      op: "replace",
      path: "/purchase_units/@reference_id=='default'/amount",
      value: {
        currency_code: cart.totals.total.currency_code,
        value: cart.totals.total.value,
        breakdown: {
          item_total: {
            currency_code: "USD",
            value: cart.totals.subtotal.value,
          },
          shipping: { currency_code: "USD", value: cart.totals.shipping.value },
          tax_total: { currency_code: "USD", value: cart.totals.tax.value },
        },
      },
    },
  ]);

  return cart;
}
```

## Error handling guide

Effective error handling is critical for maintaining a smooth shopping experience. The API provides rich error context that enables AI agents to resolve issues automatically or guide customers to resolution.

Instead of handling dozens of specific error cases, focus on these essential patterns:

1. **Can you fix this automatically?** → Fix it
2. **Can the customer fix this?** → Show them how

### Common error pattern

```json theme={null}
{
  "code": "INVENTORY_ISSUE",
  "user_message": "Blue T-Shirt is out of stock. Try a different color?",
  "resolution_options": [
    {
      "action": "SUGGEST_ALTERNATIVE",
      "label": "View other colors"
    },
    {
      "action": "REMOVE_ITEM",
      "label": "Remove from cart"
    }
  ]
}
```

### Inventory and stock management errors

Inventory issues are among the most common errors in e-commerce. These examples show how to handle out-of-stock scenarios, back-orders, and discontinued products gracefully.

#### Out of stock with alternatives

```json theme={null}
{
  "code": "INVENTORY_ISSUE",
  "type": "BUSINESS_RULE",
  "message": "Product is no longer available",
  "user_message": "The Blue T-Shirt is temporarily out of stock. Would you like to try a different color?",
  "variant_id": "SHIRT-BLUE-M",
  "context": {
    "specific_issue": "ITEM_OUT_OF_STOCK",
    "available_quantity": 0,
    "requested_quantity": 1,
    "suggested_alternatives": ["SHIRT-RED-M", "SHIRT-GREEN-M"],
    "restock_date": "2024-07-20T00:00:00Z"
  },
  "resolution_options": [
    {
      "action": "SUGGEST_ALTERNATIVE",
      "label": "View similar colors",
      "metadata": {
        "priority": "high",
        "auto_applicable": true
      }
    },
    {
      "action": "WAIT_FOR_RESTOCK",
      "label": "Notify when back in stock",
      "metadata": {
        "estimated_time": "5-7 days",
        "priority": "medium"
      }
    },
    {
      "action": "REMOVE_ITEM",
      "label": "Remove from cart",
      "metadata": {
        "priority": "low"
      }
    }
  ]
}
```

#### Back-order scenario

```json theme={null}
{
  "code": "INVENTORY_ISSUE",
  "type": "BUSINESS_RULE",
  "message": "Item is currently back-ordered",
  "user_message": "This item will ship in 2-3 weeks. Would you like to proceed with your order?",
  "variant_id": "LAPTOP-PRO-15",
  "context": {
    "available_quantity": 0,
    "back_order_limit": 50,
    "estimated_ship_date": "2024-08-15T00:00:00Z",
    "current_back_orders": 23
  },
  "resolution_options": [
    {
      "action": "ACCEPT_BACK_ORDER",
      "label": "Order anyway (ships August 15th)",
      "metadata": {
        "estimated_time": "2-3 weeks",
        "priority": "high",
        "cost_impact": "$0.00"
      }
    },
    {
      "action": "SUGGEST_ALTERNATIVE",
      "label": "View similar laptops in stock",
      "metadata": {
        "priority": "medium",
        "auto_applicable": true
      }
    }
  ]
}
```

#### Discontinued product

```json theme={null}
{
  "code": "INVENTORY_ISSUE",
  "type": "BUSINESS_RULE",
  "message": "Product has been discontinued",
  "user_message": "This product is no longer available. Here are some similar alternatives.",
  "variant_id": "PRODUCT-OLD-MODEL",
  "context": {
    "discontinuation_date": "2024-02-01T00:00:00Z",
    "suggested_alternatives": ["PRODUCT-NEW-MODEL", "PRODUCT-SIMILAR"],
    "upgrade_available": true
  },
  "resolution_options": [
    {
      "action": "SUGGEST_ALTERNATIVE",
      "label": "View newer model (+$50)",
      "metadata": {
        "cost_impact": "+$50.00",
        "priority": "high"
      }
    },
    {
      "action": "REMOVE_ITEM",
      "label": "Remove from cart",
      "metadata": {
        "priority": "low"
      }
    }
  ]
}
```

### Pricing and financial Errors

Price changes can occur between cart creation and checkout. These error patterns help you handle pricing discrepancies transparently while maintaining customer trust.

#### Price change during checkout

```json theme={null}
{
  "code": "PRICING_ERROR",
  "type": "BUSINESS_RULE",
  "message": "Product price has changed since cart creation",
  "user_message": "The price for Ocean Blue T-Shirt has increased from $29.99 to $34.99. Continue with new price?",
  "variant_id": "SHIRT-OCEAN-BLUE",
  "context": {
    "original_price": "29.99",
    "current_price": "34.99",
    "currency_code": "USD",
    "price_change_reason": "promotional_ended",
    "price_increase": "5.00"
  },
  "resolution_options": [
    {
      "action": "ACCEPT_NEW_PRICE",
      "label": "Continue with $34.99",
      "metadata": {
        "cost_impact": "+$5.00",
        "priority": "high",
        "auto_applicable": false
      }
    },
    {
      "action": "REMOVE_ITEM",
      "label": "Remove from cart",
      "metadata": {
        "cost_impact": "-$29.99",
        "priority": "medium"
      }
    }
  ]
}
```

### Shipping and address errors

Address validation ensures successful delivery while preventing fraud. These examples demonstrate handling invalid addresses, PO Box restrictions, and shipping limitations.

#### Invalid shipping address

```json theme={null}
{
  "code": "SHIPPING_ERROR",
  "type": "INVALID_DATA",
  "message": "Shipping address validation failed",
  "user_message": "The shipping address appears to be incomplete or invalid. Please check and correct.",
  "field": "shipping_address",
  "context": {
    "validation_failures": ["invalid_postal_code", "missing_street_number"],
    "suggested_corrections": {
      "postal_code": "90210",
      "address_line_1": "123 Main Street"
    },
    "address_quality_score": 0.3
  },
  "resolution_options": [
    {
      "action": "UPDATE_ADDRESS",
      "label": "Use suggested corrections",
      "metadata": {
        "priority": "high",
        "auto_applicable": true
      }
    },
    {
      "action": "PROVIDE_MISSING_FIELD",
      "label": "Add street number",
      "metadata": {
        "priority": "medium"
      }
    }
  ]
}
```

#### PO box destrictions

```json theme={null}
{
  "code": "SHIPPING_ERROR",
  "type": "BUSINESS_RULE",
  "message": "PO Box delivery not available for this order",
  "user_message": "This order contains items requiring signature confirmation and cannot be delivered to a PO Box.",
  "field": "shipping_address",
  "context": {
    "restricted_items": ["ELECTRONICS-LAPTOP-001"],
    "restriction_reason": "signature_required",
    "po_box_detected": true
  },
  "resolution_options": [
    {
      "action": "UPDATE_ADDRESS",
      "label": "Use street address instead",
      "metadata": {
        "priority": "high"
      }
    },
    {
      "action": "REMOVE_ITEM",
      "label": "Remove items requiring signature",
      "metadata": {
        "cost_impact": "-$899.00",
        "priority": "low"
      }
    }
  ]
}
```

### Geographic and legal restrictions

Some products or merchants have regional restrictions due to regulations or business policies. These errors help communicate limitations clearly to customers.

#### Regional sales restrictions

```json theme={null}
{
  "code": "BUSINESS_RULE_ERROR",
  "type": "BUSINESS_RULE",
  "message": "Store does not sell to this region",
  "user_message": "Unfortunately, we don't ship to your location due to regulatory restrictions. Please check our shipping policy.",
  "context": {
    "restricted_region": "EU",
    "customer_country": "DE",
    "restriction_reason": "regulatory_compliance",
    "supported_countries": ["US", "CA", "GB"],
    "policy_url": "https://merchant.com/shipping-policy"
  },
  "resolution_options": [
    {
      "action": "CONTACT_SUPPORT",
      "label": "Contact support for alternatives",
      "url": "https://merchant.com/support",
      "metadata": {
        "priority": "medium"
      }
    }
  ]
}
```

### System and store errors

Temporary system issues require special handling to maintain customer relationships. These patterns show how to communicate maintenance windows and system unavailability.

#### Store maintenance mode

```json theme={null}
{
  "code": "BUSINESS_RULE_ERROR",
  "type": "BUSINESS_RULE",
  "message": "Store is currently in maintenance mode",
  "user_message": "The store is temporarily closed for maintenance. Please try again later.",
  "context": {
    "maintenance_end_time": "2024-06-25T09:00:00Z",
    "service_status": "maintenance",
    "reason": "system_upgrade",
    "retry_after": 7200
  },
  "resolution_options": [
    {
      "action": "RETRY_LATER",
      "label": "Try again at 9:00 AM",
      "metadata": {
        "estimated_time": "2 hours",
        "priority": "high"
      }
    }
  ]
}
```

### Error handling implementation strategy

When implementing error handling for the PayPal Cart API, use the following guidelines to determine appropriate HTTP status codes and error responses.

#### 200 OK + validation\_issues

* Inventory changes (out of stock, back-ordered)
* Price changes during checkout
* Payment processing issues that can be resolved
* Geographic restrictions
* Discount validation failures
* Customer account issues
* Address validation problems

#### 422 Unprocessable entity

This should be used when encountering any `validation_issue` that would prevent you from creating a cart. For instance, if you do not create a cart for an `OUT_OF_STOCK` issue, you would send back a 422 Unprocessable Entity error with details about the error in the body.

Refer to the [API Spec](../api-spec.yaml) for how Errors should be formatted

#### 400 Bad request

* Invalid JSON format
* Missing required fields (items array)
* Invalid field types or formats
* Malformed request structure
* **Invalid cart ID format** (e.g., doesn't match expected pattern like "CART-\[A-Z0-9]+")

#### 404 not found

* **Cart ID doesn't exist in merchant's system** (well-formed ID but not found)
* Invalid endpoint paths

#### Cart retrieval error handling (`GET /merchant-cart/{cartId}`)

**Example 1: Invalid cart ID format (400 response)**

```json theme={null}
{
  "name": "INVALID_CART_ID",
  "message": "Cart ID format is invalid. Expected format: CART-[A-Z0-9]+",
  "debug_id": "ERROR-400-CART-FORMAT",
  "details": [
    {
      "field": "cartId",
      "issue": "INVALID_FORMAT",
      "description": "Cart ID format is invalid. Expected format: CART-[A-Z0-9]+. Provided: invalid-cart-id-123"
    }
  ]
}
```

**Example 2: Cart not found (404 response)**

```json theme={null}
{
  "name": "CART_NOT_FOUND",
  "message": "Cart with ID 'CART-MISSING-123' does not exist",
  "debug_id": "ERROR-404-12345",
  "details": [
    {
      "field": "cartId",
      "issue": "NOT_FOUND",
      "description": "Cart with ID 'CART-MISSING-123' does not exist for merchant 'MERCHANT_789'. Verify cart ID or create a new cart."
    }
  ]
}
```

#### 500 internal server error

* System failures
* Database connectivity issues
* Payment processor unavailable
* Unexpected server errors

#### Error context best practices

1. **Provide Rich Context**: Include all relevant information for smart resolution.
2. **Customer-Friendly Messages**: Write user\_message for end customers.
3. **Technical Details**: Include technical message for developers.
4. **Resolution Guidance**: Always provide actionable next steps.
5. **Cost Impact**: Show financial implications of resolution options.
6. **Time Estimates**: Provide realistic timeframes for resolutions.

#### AI agent considerations

Errors are designed for AI agents to handle autonomously:

* **Auto-applicable actions**: AI can resolve without human intervention.
* **Priority guidance**: Immediate action is required.
* **Context-rich**: The system has enough information for intelligent decision making.
* **Resolution metadata**: The system helps AI choose best resolution.

#### Resolution action types

| Action                | Use Case               | Auto-applicable                |
| --------------------- | ---------------------- | ------------------------------ |
| `ACCEPT_NEW_PRICE`    | Price increases        | No                             |
| `ACCEPT_BACK_ORDER`   | Inventory delays       | Depends on customer preference |
| `SUGGEST_ALTERNATIVE` | Out of stock items     | Yes                            |
| `UPDATE_ADDRESS`      | Address validation     | Yes (if correction available)  |
| `REMOVE_ITEM`         | Restriction violations | Depends on item importance     |
| `SPLIT_ORDER`         | Payment limits         | Yes                            |
| `CONTACT_SUPPORT`     | Complex issues         | No                             |
| `RETRY_LATER`         | Temporary failures     | Yes                            |

## Advanced use cases

Beyond basic cart operations, the API supports sophisticated scenarios like gift cards and location-based services. These examples demonstrate advanced integration capabilities.

### Gift cards

```http theme={null}
POST /api/paypal/v1/merchant-cart
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "items": [
    {
      "variant_id": "GIFTCARD-100",
      "quantity": 1,
      "gift_options": {
        "is_gift": true,
        "recipient": {
          "name": "Mary Johnson",
          "email": "mary@example.com"
        },
        "delivery_date": "2024-12-25T09:00:00Z",
        "sender_name": "John Smith",
        "gift_message": "Merry Christmas! Enjoy your shopping."
      }
    }
  ],
  "payment_method": {
    "type": "paypal"
  }
}
```

### Geographic coordinates

Some merchants offer location-based services that require precise geographic positioning beyond standard postal addresses. The Cart API supports optional latitude/longitude coordinates to enable features like local inventory checking, distance-based pricing, delivery radius validation, and enhanced shipping calculations. This geographic data operates independently from shipping addresses, allowing you to provide location-aware commerce experiences while maintaining clean separation between postal and coordinate data.

#### Latitute and longitude support strategy

Geographic coordinates are optional. It is designed for merchants who can provide enhanced location services.
Geographic coordinates are provided in a separate `geo_coordinates` field, distinct from the `shipping_address` object. This clean separation allows:

* Postal addresses to remain focused on standard shipping data
* Geographic coordinates to provide precise location enhancement
* Independent handling of address vs. coordinate data
* Graceful degradation when coordinates aren't supported

```json theme={null}
{
  "shipping_address": {
    "address_line_1": "123 Main Street",
    "admin_area_2": "San Jose",
    "admin_area_1": "CA",
    "postal_code": "95131",
    "country_code": "US"
  },
  "geo_coordinates": {
    "latitude": "37.3349",
    "longitude": "-122.0090",
    "subdivision": "CA",
    "country_code": "US"
  }
}
```

#### Geographic fields

* `latitude` & `longitude`: Precise WGS84 coordinates in decimal degrees
* `subdivision`: Administrative division (state, province, region) using ISO 3166-2 format
* `country_code`: ISO 3166-1 alpha-2 country code for the coordinate location

**Examples:**

* US: `subdivision: "CA"` (California), `country_code: "US"`
* Canada: `subdivision: "ON"` (Ontario), `country_code: "CA"`
* UK: `subdivision: "ENG"` (England), `country_code: "GB"`

## Testing your integration

Comprehensive testing ensures your integration handles all scenarios correctly. Use this checklist and test scenarios to validate your implementation before going live.

### Integration checklist

Before you launch your integration, verify that your implementation handles all critical scenarios correctly. This checklist covers the essential functionality, error states, and edge cases that ensure a robust commerce experience. Work through each item systematically to confirm your integration can handle real-world usage patterns and recover gracefully from common issues.

#### Basic Functionality

* Can create cart with simple items
* Can handle PayPal payment (smart wallet)
* Can handle successful payment return
* Can complete checkout and get order confirmation
* Can handle payment cancellation

#### Cart Updates

* Can update shipping address via PUT
* Can add/remove items via PUT
* Can apply and remove coupon codes
* Can handle cart validation errors
* Can update checkout field values

#### Error Handling

* Out of stock items are handled gracefully
* Invalid addresses are caught and corrected
* Network errors don't break the flow
* Payment failures are handled properly

### Test scenario: Happy path

```http theme={null}
# 1. Create cart
POST /api/paypal/v1/merchant-cart
{
  "items": [
    {
      "variant_id": "TEST-PRODUCT-001",
      "quantity": 1,
      "price": {"currency_code": "USD", "value": "29.99"}
    }
  ],
  "payment_method": {
    "type": "paypal"
  }
}

# 2. Update with shipping
PUT /api/paypal/v1/merchant-cart/CART-TEST-123
{
  "items": [
    {
      "variant_id": "TEST-PRODUCT-001",
      "quantity": 1,
      "price": {"currency_code": "USD", "value": "29.99"}
    }
  ],
  "shipping_address": {
    "address_line_1": "123 Test Street",
    "admin_area_2": "Test City",
    "admin_area_1": "CA",
    "postal_code": "95131",
    "country_code": "US"
  },
  "payment_method": {
    "type": "paypal"
  }
}

# 3. Simulate PayPal return
POST /api/paypal/v1/merchant-cart/CART-TEST-123/checkout
{
  "payment_method": {
    "type": "paypal",
    "token": "EC-TEST123",
    "payer_id": "TEST_PAYER"
  }
}
```
