Skip to main content

What This Guide Covers

This guide explains everything you need to integrate PayPal’s Cart API v1 into your e-commerce platform using the unified PayPalCart schema. By the end of this guide, you’ll understand:
  • How the PayPal Cart API fits into your checkout flow
  • When to use each API endpoint and why
  • How to handle complex scenarios (variants, discounts, age verification, gift cards)
  • Common integration mistakes and how to avoid them
  • Complete HTTP examples and implementation patterns you can adapt to your tech stack

Quick Overview

The Modern Commerce Architecture

PayPal’s Cart API enables agentic commerce - where AI agents handle shopping on behalf of customers through a sophisticated integration chain:
Customer ↔ AI Agent ↔ PayPal Commerce Platform ↔ PayPal ↔ Your Merchant API
What this means:
  1. Customers interact naturally with AI agents using voice or chat
  2. AI Agents understand intent and make shopping decisions automatically
  3. PayPal Commerce Platform orchestrates the entire payment and cart flow
  4. PayPal Catalog provides catalog ingestion, product discovery, and validation - routing to the right merchant API based on product selection
  5. Your Merchant API handles inventory, pricing, and order fulfillment

The Complete Flow

1. Product Discovery

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 & Management

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

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

Key Architecture Benefits

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

Understanding Cart Status Fields

The PayPal Cart API uses three key status indicators that work together to tell PayPal what’s happening with a cart:
{
  "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"
      }
    }
  ]
}

The Three Status Fields Explained

1. status - Business Outcome (Merchant Controlled)

What it means: What happened in your merchant system for this operation Values:
  • CREATED - Cart successfully created, ready for use
  • INCOMPLETE - Cart has issues that need resolution
  • READY - Cart is validated and ready for checkout
  • COMPLETED - Order has been finalized and payment captured

2. validation_status - Item & Data Validation

What it means: Whether the cart contents and data are valid for checkout Values: VALID - Ready for Checkout
  • All items available with current pricing
  • Required information complete (shipping address, customer data)
  • No business rule violations
  • validation_issues array is empty
  • Can proceed directly to checkout
INVALID - Has Problems That Block Checkout
  • Items out of stock, price changes, business rule violations
  • Invalid or incomplete data that needs correction
  • validation_issues array contains specific problems
  • Customer/AI agent must resolve issues before checkout
REQUIRES_ADDITIONAL_INFORMATION - Needs More Data
  • Missing optional but required fields (shipping address, checkout fields)
  • Age verification, custom fields, delivery preferences needed
  • Items and pricing are valid, just needs customer input
  • validation_issues array indicates what information is needed

3. validation_issues - Specific Problems with Type Classification

What it means: Detailed list of issues that need resolution with clear categorization Structure:
[
  {
    "code": "DATA_ERROR",
    "type": "MISSING_FIELD",
    "message": "Shipping address is required",
    "context": {
      "specific_issue": "MISSING_SHIPPING_ADDRESS"
    },
    "variant_id": "optional-if-item-specific"
  }
]
ValidationIssue Type Classification:
  • 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.)

validation_status Decision Matrix

When to use each validation_status:
Situationvalidation_statusvalidation_issuesAction Required
All 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
Key Principle:
  • REQUIRES_ADDITIONAL_INFORMATION = “We need more input, but what you’ve provided is valid”
  • INVALID = “There’s a problem that must be fixed before we can proceed”

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 Code Strategy

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

Real-World Scenario

Simple T-Shirt Store

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
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 Info

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

Key Points

  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

How to Handle JWT Tokens:

1. Receive Token in Authorization Header

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 Explained

Unified PayPalCart Schema

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

POST /merchant-cart - Create Cart

Basic Creation

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)

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/ - Update Cart

Note: PUT replaces the ENTIRE cart - any fields not included in your request will be removed/reset. This is a complete replacement operation, not a merge.
WRONG: This will remove customer info, shipping address, checkout fields, etc. Result: Cart now ONLY has items field - everything else is gone!
{
  "items": [{ "variant_id": "NEW-ITEM", "quantity": 1 }]
}
RIGHT: Include ALL current cart data when making changes
{
  "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//checkout - Complete Checkout

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

Overview

When implementing the PayPal Cart API, merchants must integrate with PayPal Orders API v2 to handle payment tokens and order updates. This section clarifies when to CREATE vs PATCH orders based on cart lifecycle.

Key Integration Points

1. Initial Cart Creation → CREATE Order

2. Cart Updates → PATCH Order

When to CREATE vs PATCH

ScenarioPayPal Orders ActionReason
Initial cart creationPOST /v2/ordersCreate new payment context
Add/remove itemsPATCH /v2/orders/{id}Update totals
Apply/remove couponsPATCH /v2/orders/{id}Update totals
Update shipping addressPATCH /v2/orders/{id}Update shipping + tax
Change quantitiesPATCH /v2/orders/{id}Update totals
Payment token expiredPOST /v2/ordersCreate fresh payment context
New cart after checkoutPOST /v2/ordersNew transaction

Implementation Examples

Cart Creation with 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 Order PATCH

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

Instead of handling dozens of specific error cases, focus on these 3 essential patterns:
  1. Can you fix this automatically? → Fix it
  2. Can the customer fix this? → Show them how

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 & Stock Management Errors

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 & Financial Errors

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 & Address Errors

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"
      }
    }
  ]
}

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 & Store Errors

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

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 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/)

Example 1: 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 2: 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

  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: High priority = immediate action needed
  • Context-rich: Enough information for intelligent decision making
  • Resolution metadata: Helps AI choose best resolution path

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

Gift Card Advanced Features

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

Lat/Lng 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"

Testing Your Integration

Integration Checklist

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 Scenarios

Scenario 1: Happy Path Test

# 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"
  }
}
I