osaris-uk / click-and-drop
Laravel client for the Royal Mail Click & Drop API (orders, labels, manifests, returns, services).
Requires
- php: ^8.2
- guzzlehttp/guzzle: ^7.8|^8.0
- illuminate/contracts: ^11.0|^12.0|^13.0
- illuminate/http: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
Requires (Dev)
- larastan/larastan: ^3.15
- orchestra/testbench: ^9.0|^10.0|^11.0
- phpunit/phpunit: ^11.0|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A Laravel client for the Royal Mail Click & Drop API (v1): orders, labels, manifests, returns, services and carriers.
- PHP 8.2+, Laravel 11, 12 or 13
- Built on Laravel's HTTP client, so
Http::fake()works in your tests - Typed request and response objects, with raw arrays accepted anywhere you'd rather pass the API's own shape
- Retries 429s, honouring
Retry-After(the API allows 5 calls per second)
Installation
composer require osaris-uk/click-and-drop
Add your API key (Click & Drop > Settings > Integrations > Click & Drop API) to .env:
CLICK_AND_DROP_API_KEY=your-key
Optionally publish the config:
php artisan vendor:publish --tag=click-and-drop-config
| Env | Default | |
|---|---|---|
CLICK_AND_DROP_API_KEY |
– | Sent as Authorization: Bearer {key} |
CLICK_AND_DROP_BASE_URL |
https://api.parcel.royalmail.com/api/v1 |
|
CLICK_AND_DROP_TIMEOUT |
30 |
Seconds |
CLICK_AND_DROP_CONNECT_TIMEOUT |
10 |
Seconds |
CLICK_AND_DROP_RETRY_TIMES |
3 |
Total attempts on a 429; 1 disables retries |
CLICK_AND_DROP_RETRY_SLEEP |
1000 |
Milliseconds between attempts when the 429 has no Retry-After |
CLICK_AND_DROP_RETRY_MAX_SLEEP |
10000 |
Upper bound in milliseconds on a Retry-After wait |
Usage
Use the facade, or inject Osaris\ClickAndDrop\ClickAndDrop.
use Osaris\ClickAndDrop\Facades\ClickAndDrop;
Multiple accounts
$store = ClickAndDrop::withApiKey($tenant->click_and_drop_key); $store->orders()->list();
withApiKey() returns a new client and leaves the configured one untouched.
Creating orders
use Osaris\ClickAndDrop\Enums\PackageFormat; use Osaris\ClickAndDrop\Requests\{Address, CreateOrder, Package, PostageDetails, ProductItem, Recipient}; $result = ClickAndDrop::orders()->create(new CreateOrder( recipient: new Recipient( address: new Address( addressLine1: '1 High Street', city: 'Lincoln', countryCode: 'GB', fullName: 'Sam Jones', postcode: 'LN1 1AA', ), emailAddress: 'sam@example.com', ), orderDate: now(), subtotal: 24.99, shippingCostCharged: 3.50, total: 28.49, orderReference: 'ORDER-1001', packages: [ new Package( weightInGrams: 450, packageFormatIdentifier: PackageFormat::SmallParcel, contents: [ new ProductItem(quantity: 1, name: '12" vinyl', sku: 'KF-001', unitValue: 24.99, unitWeightInGrams: 300), ], ), ], postageDetails: new PostageDetails(serviceCode: 'TPN'), )); if ($result->hasFailures()) { foreach ($result->failedOrders as $failed) { logger()->warning('Click & Drop rejected '.$failed->orderReference(), [ 'errors' => collect($failed->errors)->pluck('errorMessage')->all(), ]); } } $order = $result->first(); $order->orderIdentifier; // Click & Drop's ID $order->trackingNumber;
Creating orders is not all-or-nothing. The API answers 200 even when some orders in a batch are rejected, so no exception is thrown — check hasFailures().
create() takes a single CreateOrder, a list of them, or raw arrays in the API's own shape (handy for fields this package doesn't model):
ClickAndDrop::orders()->create([$orderA, $orderB, ['orderReference' => 'RAW-1', /* ... */]]);
OBA accounts can generate the label in the same call:
use Osaris\ClickAndDrop\Requests\LabelOptions; $result = ClickAndDrop::orders()->create(new CreateOrder(/* ... */, label: new LabelOptions(includeCN: true))); $result->first()->labelDocument()?->store("labels/{$result->first()->orderIdentifier}.pdf"); $result->first()->labelErrors; // why a label wasn't generated
Identifying orders
Anywhere orders are looked up, an int is a Click & Drop order identifier and a string is your own order reference — so 1001 and '1001' mean different things. Up to 100 per call.
ClickAndDrop::orders()->find(5001); // ?OrderInfo ClickAndDrop::orders()->get([5001, 'ORDER-1001']); // Collection<OrderInfo> ClickAndDrop::orders()->delete('ORDER-1001'); // DeleteOrdersResult
Listing orders
$page = ClickAndDrop::orders()->list(pageSize: 50, from: now()->subDay()); $page->items; // Collection<OrderInfo> $page->hasMorePages(); $next = ClickAndDrop::orders()->list(continuationToken: $page->continuationToken); // Or let the package follow the continuation tokens, one page at a time: ClickAndDrop::orders()->all(from: now()->subWeek())->each(fn ($order) => /* ... */);
getWithDetails(), listWithDetails() and allWithDetails() return full OrderDetails and are reserved for ChannelShipper accounts.
Order status
ClickAndDrop::orders()->markDespatched(5001, 'ORDER-1002'); ClickAndDrop::orders()->reset(5001); // back to "new"; any generated label is now invalid // ChannelShipper only ClickAndDrop::orders()->markDespatchedByOtherCourier('ORDER-1003', 'TRACK123', now(), 'DPD', 'Next Day');
Each returns an UpdateOrderStatusResult with updatedOrders, errors and hasErrors(). For mixed statuses in one call, pass OrderStatusUpdate objects to updateStatus().
Labels and documents (OBA only)
use Osaris\ClickAndDrop\Enums\DocumentType; $label = ClickAndDrop::labels()->get(5001); // postage label $cn23 = ClickAndDrop::labels()->get(5001, DocumentType::CN23); $batch = ClickAndDrop::labels()->get([5001, 5002], includeReturnsLabel: true, includeCN: true); $label->store('labels/5001.pdf', 's3'); // any filesystem disk $label->save('/tmp/5001.pdf'); $label->base64(); return $label->response('label-5001.pdf'); // from a controller
Manifests
$manifest = ClickAndDrop::manifests()->create(); // or create('Royal Mail OBA') if (! $manifest->hasDocument()) { // The API accepted the manifest but the PDF isn't ready yet - poll for it. $manifest = ClickAndDrop::manifests()->get($manifest->manifestNumber); } $manifest->status; // ManifestStatus enum (from get() only) $manifest->document()?->store('manifests/'.$manifest->manifestNumber.'.pdf'); ClickAndDrop::manifests()->retry($manifest->manifestNumber);
Services and carriers
ClickAndDrop::carriers(); // Collection<Carrier> ClickAndDrop::services()->list(); // full catalogue, grouped by carrier ClickAndDrop::services()->list('GBR', 'LN1 1AA', PackageFormat::SmallParcel, 450); // Royal Mail OLP accounts: services with prices ClickAndDrop::services()->olp('GBR', weight: 450, packageFormat: PackageFormat::SmallParcel);
Returns (OBA only)
use Osaris\ClickAndDrop\Requests\{CreateReturn, ReturnAddress}; ClickAndDrop::returns()->services(); // Collection<Service> $return = ClickAndDrop::returns()->create(new CreateReturn( serviceCode: 'TSN', shippingAddress: new ReturnAddress('Returns', 'Team', '1 Warehouse Way', 'Lincoln', 'LN1 1AA'), returnAddress: new ReturnAddress('Sam', 'Jones', '2 Low Road', 'Leeds', 'LS1 1AA'), customerReference: 'RMA-1', )); $return->trackingNumber; $return->qrCode; $return->label;
Anything else
ClickAndDrop::version(); // API version info ClickAndDrop::send('GET', 'orders', ['pageSize' => 10]); // raw Illuminate\Http\Client\Response
Errors
Everything thrown extends Osaris\ClickAndDrop\Exceptions\ClickAndDropException.
| Exception | When |
|---|---|
ValidationException |
400 |
AuthenticationException |
401 |
ForbiddenException |
403 — feature not on this account (OBA / ChannelShipper / OLP only) |
NotFoundException |
404 |
RateLimitException |
429 after retries ran out |
ServerException |
5xx |
TransportException |
The API couldn't be reached |
MissingApiKeyException |
No API key configured |
The first six extend ApiException:
try { ClickAndDrop::labels()->get(5001); } catch (ApiException $e) { $e->status(); // 403 $e->errors(); // error entries from the body, normalised to a flat list $e->response; // the Illuminate response }
Only 429s are retried. The wait comes from the response's Retry-After header (seconds or an HTTP date) when it has one, capped at max_sleep, and from sleep otherwise. A 429 means the request wasn't processed, so retrying a POST /orders can't duplicate an order; timeouts and 5xx responses are deliberately not retried for the same reason.
Testing your app
Http::fake([ 'api.parcel.royalmail.com/api/v1/orders' => Http::response([ 'successCount' => 1, 'errorsCount' => 0, 'createdOrders' => [['orderIdentifier' => 5001, 'createdOn' => now()->toIso8601String()]], ]), ]);
Notes on the API
- The spec marks a few request fields as deprecated (
guaranteedSaturdayDelivery,postageDetails.commercialInvoiceNumber/commercialInvoiceDate,customPackageFormatIdentifier,ReferenceId). They are left out of the request objects; pass a raw array if you need one. dangerousGoodsDescriptionis typed as a number in the spec but carries a 500-character limit, so it is sent as a string.
Development
composer install composer test composer analyse # PHPStan (Larastan) at level 9
Licence
MIT