Skip to main content
The unified Cart API abstracts platform-specific complexities, letting your agents work seamlessly with supported platforms. This guide explains how to integrate PayPal’s Cart API v1 into your commerce platform using the unified PayPalCart schema. For the full protocol reference, see the Cart API and Complete checkout API reference pages.
Important: To access and use store sync, complete this form to contact the AI team at PayPal and request access.
In this guide, you’ll see how to build an API that integrates with PayPal for AI-powered commerce, including:
  • Receiving cart requests from PayPal’s Orders v2 API to validate products, calculate taxes, and handle shipping
  • Handling updates to a shopping cart, like shipping options and line items, using the Cart API
  • Completing orders by processing PayPal payments and fulfilling shipments using the Complete checkout API
You’ll also explore complete HTTP examples and implementation patterns that you can adapt to your tech stack.
Important: Complete catalog creation and ingestion before you complete set up your cart API.

Agentic shopping flow

Before you set up your API, it helps to understand the different roles and steps in the agentic shopping flow.

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. For example:
  1. A customer says, “I need a blue t-shirt.”
  2. The AI agent queries PayPal’s catalog for blue t-shirts.
  3. PayPal returns product data along with merchant routing information.
  4. The AI agent presents the options to the customer.
This step uses PayPal’s product catalog integration to discover products from your store.

Cart creation and management

After a customer selects products, the AI agent creates and manages the shopping cart through PayPal. This process validates product availability, pricing, and shipping options in real-time with your merchant API. For example:
  1. The customer says, “I’ll take the medium one.”
  2. The AI agent sends a cart creation request to PayPal.
  3. PayPal routes the request to your merchant API for validation.
  4. Your API responds with cart details, including pricing and shipping options.
For more information about building your cart API, see Step 1: Handle incoming cart creation from PayPal.

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. For example:
  1. The customer says, “Checkout with PayPal.”
  2. The AI agent initiates the checkout process with PayPal.
  3. PayPal processes the payment using the customer’s Smart Wallet.
  4. The AI agent confirms the order and provides delivery information.
For more information about completing checkout, see Step 3: Your API works with PayPal to handle the order-completion request.

Step 1: Handle incoming cart creation from PayPal

When a customer interacts with an AI agent to buy something, PayPal calls your API endpoint, as shown in the following example.
Note: This step shows one type of product feed integration. To determine which type of product feed integration is best for your environment, see the Create a product catalog.
POST /api/paypal/v1/merchant-cart
Content-Type: application/json
Authorization: Bearer <paypal-issued-jwt-token>

{
  "items": [
    {
      "variant_id": "SHIRT-001",
      "quantity": 1,
      "name": "Blue T-Shirt",
      "price": {
        "currency_code": "USD",
        "value": "25.00"
      }
    }
  ],
  "shipping_address": {
		"address_line_1": "1060 West Addison Street",
		"admin_area_2": "CHICAGO",
		"admin_area_1": "IL",
		"postal_code": "60613",
		"country_code": "US"
	}
}

Success response (201 created)

{
  "id": "CART-123",
  "status": "CREATED",
  "payment_method": {
    "type": "PAYPAL",
    "token": "EC-7U8939823K567"
  },
  "items": [
    {
      "variant_id": "SHIRT-001",
      "quantity": 1,
      "name": "Blue T-Shirt",
      "unit_amount": { "currency_code": "USD", "value": "25.00" },
      "item_total": { "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" },
    "total": { "currency_code": "USD", "value": "33.69" }
  },
  "validation_issues": []
}

Key response fields

FieldDescription
idCart identifier for GET/PUT/PATCH/checkout operations
ec_tokenPayPal payment token (required for checkout completion) that enables PayPal payment for a customer.
statusCart state:
CREATED
INCOMPLETE
READY
COMPLETED
validation_issuesArray of problems that need fixing (empty = good)

Step 2: PayPal handles payment with customer

After receiving a successful cart creation response:
  1. PayPal presents the cart to the customer for approval.
  2. The customer approves payment using PayPal’s agentic checkout APIs.
  3. PayPal returns payment approval details to complete the checkout.
  4. Your API receives the checkout completion request.

Step 3: Your API works with PayPal to handle the order-completion request

After the customer approves payment, PayPal calls your API to complete the order.
POST /api/paypal/v1/merchant-cart/CART-123/checkout
Content-Type: application/json
Authorization: Bearer <paypal-issued-jwt-token>

{
  ...existing cart,
  "payment_method": {
    "type": "paypal",
    "token": "EC-7U8939823K567"
  }
}

Success response (200 OK)

{
  "id": "CART-123",
  "status": "COMPLETED",
  "payment_confirmation": {
    "merchant_order_number": "ORDER-789",
    "order_review_page": "https://yourstore.com/orders/789"
  },
  "totals": {
    "total": { "currency_code": "USD", "value": "33.69" }
  }
}

Key parameters

ParameterDescription
tokenThe ec_token returned during cart creation
typeCurrently paypal for PayPal payments
At this point, your API has successfully processed the AI-assisted purchase, the customer now owns a new t-shirt, and the AI agent can confirm the successful order.

Unified PayPalCart schema

{
  "items": [...],
  "customer": {...},
  "shipping_address": {...},
  "payment_method": {...},
  "checkout_fields": [...],
  "gift_options": {...}
}

API endpoints

The Cart API provides 3 core endpoints that handle the complete cart lifecycle. Each endpoint serves a specific purpose in the agentic shopping flow.
  • POST /merchant-cart creates a new cart.
  • PUT /merchant-cart/{id} updates an existing cart.
  • POST /merchant-cart/{id}/checkout completes the checkout process.

Create a cart

Use POST /merchant-cartto create a new shopping cart with specified items. The cart also can include customer information, such as a shipping address and payment method to use.

Basic cart creation

This example shows how to create a simple cart.
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 cart creation

A more advanced cart includes additional information, such as customer contact information (customer) and a payment method (payment_method).
POST /api/paypal/v1/merchant-cart
Content-Type: application/json
Authorization: Bearer <paypal-jwt-token>

{
  "items": [...],
  "shipping_address": {...},
  "customer": {"email_address": "[email protected]"},
  "payment_method": {"type": "paypal"},
  "checkout_fields": [...]
}

Update a cart

Use PUT /merchant-cart/{id} to update an existing cart by replacing its contents with the provided data. Use this endpoint to add or remove items, change quantities, update the shipping address, apply discounts, and so on.
Important: PUT replaces the ENTIRE cart. It removes or resets any fields that you do not include in your request. This is a complete replacement operation, not a merge.
Include all current cart data when making changes, as shown in the following example.
{
  "items": [
    {"variant_id": "EXISTING-ITEM", "quantity": 1},
    {"variant_id": "NEW-ITEM", "quantity": 1}
  ],
  "customer": {
    "email_address": "[email protected]"
  },
  "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": {...}
}

Complete checkout

Use POST /merchant-cart/{id}/checkout to complete the checkout process for a cart. This endpoint finalizes the purchase by processing the payment using the specified payment method.
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"
  ]
}

Cart status fields

The PayPal Cart API uses 3 key status indicators that work together to communicate cart state and validation issues.
FieldDescription
statusBusiness outcome status (merchant-controlled)
validation_statusItem-validation and data-validation status
validation_issuesSpecific problems with type classification
Understanding these fields is crucial for proper error handling and cart lifecycle management. In this example, you can see that the cart status is INCOMPLETE, the validation status is REQUIRES_ADDITIONAL_INFORMATION, and several specific validation issues exist.
{
  "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"
      }
    }
  ]
}

Business outcome status

The merchant-controlled status value indicates the current state of the cart.
ValueDescription
CREATEDCart was successfully created and is ready for use
INCOMPLETECart has issues that need resolution
READYCart is validated and ready for checkout
COMPLETEDOrder is finalized and payment was captured

Item-validation and data-validation status

The validation-status value indicates whether the cart contents and data are valid fo checkout. A valid transaction meets these requirements:
  • All items are available with current pricing.
  • Required information is complete (shipping address, customer data, and so on).
  • No business rule violations exist.
  • The validation_issues array is empty.
The following table describes the validation-status values.
ValueDescription
VALIDCart is ready for checkout.
INVALIDCart has problems that block checkout.
REQUIRES_ADDITIONAL_INFORMATIONPayPal requires 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.

Validation issues

The validation_issues array communicates business logic problems that prevent cart completion but don’t warrant HTTP error codes. These structured error objects help AI agents understand what went wrong and how to fix it, whether that’s suggesting alternative products for out-of-stock items, requesting missing information, or explaining pricing changes. Use these patterns to provide clear, actionable feedback that enables automatic resolution or guides customers to make informed decisions.
FieldDescription
MISSING_FIELDRequired information is missing (shipping address, checkout fields, and so on).
INVALID_DATAProvided data is incorrect or invalid.
BUSINESS_RULEBusiness logic violations (out of stock, minimum order, and so on).
The following example shows the structure.
[
  {
    "code": "DATA_ERROR",
    "type": "MISSING_FIELD",
    "message": "Shipping address is required",
    "context": {
      "specific_issue": "MISSING_SHIPPING_ADDRESS"
    },
    "variant_id": "optional-if-item-specific"
  }
]
Note: When validation_issues exist, PayPal sends a PUT request with the updated cart state.

Simple validation error (minimal fields)

{
  "code": "INVENTORY_ISSUE",
  "type": "BUSINESS_RULE",
  "message": "Product availability issue"
}

​Complete validation error (all fields)

{
  "code": "INVENTORY_ISSUE",
  "type": "BUSINESS_RULE",
  "message": "Product availability issue",
  "user_message": "The Blue T-Shirt is currently 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"]
  },
  "resolution_options": [
    {
      "action": "SUGGEST_ALTERNATIVE",
      "label": "View similar colors",
      "metadata": { "priority": "high", "auto_applicable": true }
    }
  ]
}

Examples of how to use the states

To determine when to use each status, see the following table.
SituationValidation statusValidation issuesAction Required
Order looks good, ready for checkoutVALID[] (empty)Proceed to checkout
Missing shipping addressREQUIRES_ADDITIONAL_INFORMATION[{code: "DATA_ERROR", type: "MISSING_FIELD", context: {specific_issue: "MISSING_SHIPPING_ADDRESS"}}]Collect shipping address
Age verification neededREQUIRES_ADDITIONAL_INFORMATION[{code: "DATA_ERROR", type: "MISSING_FIELD", context: {specific_issue: "MISSING_CHECKOUT_FIELDS"}}]Complete age verification
Item out of stockINVALID[{code: "INVENTORY_ISSUE", type: "BUSINESS_RULE"}]Remove item or suggest alternatives
Price changedINVALID[{code: "PRICING_ERROR", type: "BUSINESS_RULE"}]Customer must accept new price
Invalid postal codeINVALID[{code: "SHIPPING_ERROR", type: "INVALID_DATA"}]Correct address format
Payment declinedINVALID[{code: "PAYMENT_ERROR", type: "BUSINESS_RULE"}]Try different payment method

Common status combinations

ScenarioHTTP StatusCart statusvalidation_statusvalidation_issues
Cart Created Successfully201 CreatedCREATEDVALID[]
Item Out of Stock200 OKINCOMPLETEINVALID[{code: "INVENTORY_ISSUE", type: "BUSINESS_RULE", context: {specific_issue: "ITEM_OUT_OF_STOCK"}}]
Missing Shipping200 OKINCOMPLETEREQUIRES_ADDITIONAL_INFORMATION[{code: "DATA_ERROR", type: "MISSING_FIELD", context: {specific_issue: "MISSING_SHIPPING_ADDRESS"}}]
Ready for Checkout200 OKREADYVALID[]
Order Completed200 OKCOMPLETEDVALID[]

HTTP status codes

The PayPal Cart API uses a combination of HTTP status codes and cart status fields to communicate the outcome of requests.
StatusDescriptionResponse contentAction
201 CreatedCart created successfullyFull cart object and the ec_token valueProceed to payment.
200 OKOperation was successfulFull cart objectCheck the status field.
200 OK with validation_issuesSpecific problems prevent PayPal from completing the transaction.Full cart object and the validation_issues arrayFix the issues in the validation_issues array.
400 Bad RequestInvalid request format or missing parametersError detailsFix the request format.
404 Not FoundCart doesn’t existError detailsUse a valid cart ID.
500 Server ErrorSystem problemError detailsRetry later or contact technical support.
For examples of how to use some of these error codes, see Error handling implementation strategy.

Business logic 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

Use proper HTTP error codes for technical problems. For the complete list of error codes, see HTTP status codes.

Example 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 through PayPal, orchestrating with the merchant’s API
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": "[email protected]"
  },
  "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"
  }
}

2. PayPal Cart API returns cart information

AI agent: “I found the perfect blue t-shirt in medium! $25 total. Ready to check out?“
{
  "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" }
  }
}

3. AI completes checkout

AI Agent: “Ready to check out with PayPal?” Customer: “Yes, go ahead.” AI Agent: seamlessly handles PayPal Smart Wallet approval (no redirect required).
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 on Tuesday.”

Customer information availability

This table explains what customer information is available at each stage of the transaction life cycle.
Transaction stageInformation availability
Initial cart creationFor anonymous shopping, customer information could be absent.
After PayPal checkout approvalFull customer information is available in the checkout completion request.
Returning customersFull customer information might be available, depending on the user’s account setup.

Authentication with PayPal-supplied JWT tokens

  • PayPal-issued: PayPal generates and manages the tokens.
  • Request authentication: Every API call includes the token in the authorization header.
  • Merchant identification: Tokens contain your merchant ID and permissions.
  • Security verification: Verify token signature using PayPal’s public keys. See Verify token.

Receive token in the authorization header

POST /api/paypal/v1/merchant-cart
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjaGFudF9pZCI6Ik1FUkNIQU5ULTEyMyIsInNjb3BlIjpbImNhcnQiXSwiaWF0IjoxNzE5MjQwMDAwLCJleHAiOjE3MTkyNDM2MDB9.signature
Content-Type: application/json

{
  ...cart create request body
}

Verify token

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

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 PayPal Orders API v2 to handle payment tokens and order updates. The following table explains when to create (POST) or update (PATCH) a cart.
ScenarioPayPal Orders ActionReason
Initial cart creation.POST /v2/ordersCreate new payment context
Add or remove items.PATCH /v2/orders/{id}Update totals
Apply or 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
Create a fresh payment context when a payment token expires.POST /v2/ordersCreate fresh payment context
Create a new cart after checkout.POST /v2/ordersNew transaction

Examples

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

Cart creation with an order

// 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 an order update

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

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:
  • Can you fix this automatically? If you can fix it, fix it for them.
  • Can the customer fix this? If you can’t fix it for them, show them how to fix it.

Error categories

CategoryDescription
INVENTORY_ISSUEStock, availability, back-orders, discontinued items
PRICING_ERRORPrice changes, discounts, tax calculation, currency issues
SHIPPING_ERRORAddress validation, delivery restrictions, shipping zones
PAYMENT_ERRORPayment limits, currency support, processor issues
DATA_ERRORField validation, format issues, required fields
BUSINESS_RULE_ERRORAccount restrictions, compliance, regional limits

Error types

TypeDescription
MISSING_FIELDNeed more info (address, checkout fields)
INVALID_DATAData validation failed
BUSINESS_RULEBusiness logic violation, such as inventory issues

Common error pattern

{
  "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

{
  "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

{
  "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

{
  "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

{
  "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

{
  "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 restrictions

{
  "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"
      }
    }
  ]
}
Some products or merchants have regional restrictions due to regulations or business policies. These errors help communicate limitations clearly to customers.

Regional sales restrictions

{
  "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

{
  "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

Use this error code when any validation_issue prevents you from creating a cart. For example, if you do not create a cart for an OUT_OF_STOCK issue, you can send a 422 Unprocessable Entity error with details about the error in the body. See the API Spec for how to format errors.

400 Bad request

  • Invalid JSON format
  • Missing required fields (for example, the items array)
  • Invalid field types or formats
  • Malformed request structure
  • Invalid cart ID format (for example, it doesn’t match an expected pattern, such as "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

These examples use GET /merchant-cart/{cartId}. Example: Invalid cart ID format (400 response)
{
  "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: Cart not found (404 response)
{
  "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

  • Provide Rich Context: Include all relevant information for smart resolution.
  • Customer-Friendly Messages: Write user_message for end customers.
  • Technical Details: Include technical message for developers.
  • Resolution Guidance: Always provide actionable next steps.
  • Cost Impact: Show financial implications of resolution options.
  • Time Estimates: Provide realistic timeframes for resolutions.

AI agent considerations for errors

Many errors are well-suited for AI agents to handle them 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

ActionUse CaseAuto-applicable
ACCEPT_NEW_PRICEPrice increasesNo
ACCEPT_BACK_ORDERInventory delaysDepends on customer preference
SUGGEST_ALTERNATIVEOut of stock itemsYes
UPDATE_ADDRESSAddress validationYes (if correction available)
REMOVE_ITEMRestriction violationsDepends on item importance
SPLIT_ORDERPayment limitsYes
CONTACT_SUPPORTComplex issuesNo
RETRY_LATERTemporary failuresYes

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

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": "[email protected]"
        },
        "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
{
  "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"

Next steps

Continue by testing your integration.