# REST API reference

All plugin REST routes use the namespace **`parcel2go-shipping/v1`**. Base URL is typically `rest_url('parcel2go-shipping/v1')` (e.g. `/wp-json/parcel2go-shipping/v1`). Endpoints require the user to have `manage_woocommerce` capability unless noted.

## Auth

| Method | Path | Purpose |
|--------|------|--------|
| POST | `/auth/authorise` | Generate PKCE pair, call accountlinking edge, return `{ authoriseUrl }` for the P2G consent page. Requires `manage_woocommerce`. |
| GET | `/auth/callback` | OAuth callback: receives `?code=` from the edge, exchanges code + stored PKCE verifier for tokens, stores them, then redirects to the plugin admin page. Public (unauthenticated). |
| GET | `/auth/status` | Returns `{ linked: true|false }` indicating whether an access token is stored. Requires `manage_woocommerce`. |
| GET | `/auth/user` | Returns linked account details parsed from JWT claims: `{ linked, accountNumber, email, name, forename, surname }`. Requires `manage_woocommerce`. |
| POST | `/auth/logout` | Removes stored access and refresh tokens. Requires `manage_woocommerce`. |

## Orders

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/orders` | List processing orders (paginated). Query: `page`, `per_page` |
| GET | `/orders/(?P<id>[\d]+)` | Get a single order by ID |
| GET | `/orders/(?P<id>[\d]+)/ship` | Get order data needed for the ship flow (order, quotes, dropshops) |
| POST | `/orders/(?P<id>[\d]+)/shipping-status` | Update order shipping status: Paid, Booked, or Fulfilled (see below) |
| GET | `/order/p2g-status` | Poll P2G order status (query/body: `orderId`, `hash`) |

### POST `/orders/{id}/shipping-status`

Updates the WooCommerce order’s P2G shipping state. Flow: **Paid** (after payment) → **Booked** (when P2G confirms) → **Fulfilled** (tracking available; marks WC order completed).

**Body (JSON):**

| Field | Type | When | Description |
|-------|------|------|-------------|
| `status` | string | Required | One of: `Paid`, `Booked`, `Fulfilled` |
| `paymentDetails` | object | For `Paid` | `orderId`, `completeHash` from P2G payment (stored for polling) |
| `trackingNumber` | string or array | For `Fulfilled` | Single tracking number or list |
| `parcelNumbers` | array | For `Fulfilled` | List of parcel/tracking numbers (alternative to `trackingNumber`) |
| `pickupPoint` | object | For `Paid`, optional | The locker or shop booked: `{ id, provider, name, address1, address2, postcode, isLocker }`. When it differs from the order's place, the order keeps it (details from the cached lookup when there) and an order note records the customer's choice. |

**Response (success):** `{ "success": true, "wcOrderId": <id>, "status": "<Paid|Booked|Fulfilled>" }`

## Quotes

| Method | Path | Purpose |
|--------|------|--------|
| POST | `/quotes` | Get Parcel2Go shipping quotes (body: origin, destination, parcels, etc.) |

## Requirements

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/requirements` | A service's rulesets and metadata on a lane, cached for 10 minutes. Query: `service`, `origin`, `destination` (country codes such as `GB`, `GBR` or `GBR-NIR`). Returns `{ ruleSets, metadata }`. |

## Countries

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/countries/origins` | List origin countries from P2G API (cached) |

## Dropshop

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/dropshops` | Get dropshops near a postcode (query: `postcode`) |

## Pickup points

Lockers and shops the customer collects from, for pickup point services: any service whose quote is tagged `shopdelivery`, for example InPost Locker to Locker (provider `INPOST`) or Evri ParcelShop to ParcelShop (provider `MYHRMS`). The provider is the service's `dropOffProviderGroup`. Both routes return up to 10 places that accept deliveries, nearest first, cached for 24 hours per provider and postcode.

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/pickup-points` | For checkout. Public, but needs the Store API nonce (`Nonce` or `X-WC-Store-API-Nonce` header) and Live courier rates switched on. Limited to 20 lookups a minute per visitor. Query: `provider`, `postcode` (full UK postcode). Returns `{ provider, pickupPoints }`. Errors: `400 p2g_pickup_points_unknown_provider`, `400 p2g_pickup_points_bad_postcode`, `403 p2g_pickup_points_forbidden`, `429 p2g_pickup_points_rate_limited`, `503 p2g_pickup_points_unavailable`. |
| GET | `/pickup-points/search` | For the ship page, which checks the customer's place is still offered and lets the merchant change it or pick one. Requires `manage_woocommerce`; works whether or not Live courier rates are on. Same query and errors (no rate limit). |

Each place: `id` (sent to Parcel2Go as `destination.useAddress.shopId` when booking), `name`, `address1`, `address2`, `postcode`, `distanceMiles`, `isLocker`, and `openingTimes`.

The block checkout also adds `extensions.parcel2go-shipping` to the Store API cart (the places for each pickup rate and the customer's choice) and takes the choice through `extensionCartUpdate` with namespace `parcel2go-shipping` and data `{ package, id, provider }`.

Orders placed with a pickup point service carry the place in `shipping_method.checkout.pickupPoint` (`GET /orders`, `GET /orders/{id}`). Bulk booking skips orders with no place of the service's provider, with `bulkError: "no-pickup-point"`: the merchant picks one on the ship page.

Each booked item's `metadata` carries `wooShop` (site URL), `wooOrderId` (the booking ref) and, for orders placed with Live courier rates, `wooCheckoutService` (the service slug the customer chose at checkout). They are built in `src/features/order-ship/utils/wooMetadata.ts`.

## Checkout

| Method | Path | Purpose |
|--------|------|--------|
| POST | `/checkout` | Create order at Parcel2Go checkout |
| POST | `/checkout/validate` | Validate checkout/order at Parcel2Go |

## Payment

| Method | Path | Purpose |
|--------|------|--------|
| POST | `/payment/providers` | Get available payment providers |
| POST | `/payment/braintree/token` | Get Braintree client token |
| POST | `/payment/braintree` | Submit Braintree payment |
| GET | `/payment/prepay/balance` | Get prepay account balance |
| POST | `/payment/prepay` | Submit prepay payment |

## Settings

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/settings` | Get plugin settings |
| GET | `/settings/store` | Get store settings (address etc.) |
| GET | `/settings/default-services` | Get default services configuration |
| GET | `/settings/checkout` | Live courier rates settings, plus `linked`, `currency`, `zones`, `tax` and `checkoutPhone` (`{ field: required, optional or hidden, editUrl }`) status for the settings screen. See [Live courier rates](designs/checkout-live-rates.md). |
| PUT | `/settings/checkout` | Update Live courier rates settings (any fields): `enabled`, `services` (slugs, or `{ slug, name, courier, courierSlug, customerName, pickup }`, where `pickup` is `locker`, `shop` or empty), `markup` (`{ direction: increase or decrease, percent, fixed }`), `rounding`, `maxRates`. Errors: `400 p2g_invalid_checkout_settings`, `403 p2g_not_linked`, `409 p2g_zone_without_fallback`. |
| PATCH | `/settings` | Update plugin settings (partial) |
| POST | `/settings` | Update plugin settings (full) |

## Shipments

| Method | Path | Purpose |
|--------|------|--------|
| GET | `/shipments` | List fulfilled shipments only (paginated). Returns orders where `_p2g_ship_status` = Fulfilled. Query: `page`, `per_page` |
| GET | `/shipments/(?P<id>[\d]+)/label` | Label download URL for a shipment (query: `size`, 0-2). Built on each request from the live or test Parcel2Go site, never cached |
| GET | `/shipments/(?P<id>[\d]+)/tracking` | Tracking for a shipment: `{ currentStage, parcels: [{ number, currentStage, events: [{ description, timestamp, stage }], images: [{ key, value }] }] }` (images are base64 JPEG). Calls Parcel2Go `{base}/{tenant}/tracking/{orderLineId}?postcode=…&findMostRecentParcelTracking=true` for each order line. Cached 5 minutes, keyed on the order, its order lines, the postcode and the live or test API, so a rebooked order never gets the old tracking; failures and empty answers are not cached. Errors: `400 not_shipped`, `400 no_order_line`, `404 order_not_found`, `502 p2g_tracking_failed` |
