Download the PHP package arzcode/laravel-correos without Composer
On this page you can find all versions of the php package arzcode/laravel-correos. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package laravel-correos
Correos Shipping SDK
Laravel package for the Correos (Spanish postal service) APIs: shipment preregistration, label and customs document generation, and tracking. Built on Saloon 4.x for HTTP and Spatie Laravel Data 4.x for DTOs.
Requires PHP 8.4+ and Laravel 11, 12 or 13.
Collections (recogidas) are not covered: the API has no resource for them yet, so shipments are handed over at an office or picked up under a standing agreement.
Installation
Add your credentials to .env:
That is all production needs. Everything else in config/laravel-correos.php has a
working default — see Configuration reference for the rest.
Usage
Resolve the SDK from the container:
Or reach the same instance through the facade:
Outside Laravel, or with runtime credentials, build one by hand with
Arzcode\LaravelCorreos\Correos::make(['oauth_client_id' => ..., 'gateway_client_id' => ..., ...]).
Preregister a shipment
Print labels
labelPrintMode decides what that PDF contains, and the two modes are not interchangeable:
1 (A4) returns a full page with the labels already laid out on the sheet, 2 (labeler)
returns one label per page at label size.
To print from a package code rather than a shipment code, set preregisterInd to 1 and pass
the matching labelOrderType. Correos rejects the package code without it, because that flag is
what tells the API the codes belong to shipments preregistered earlier:
Composing your own A4 sheet with FPDI
To place labels yourself — starting at an arbitrary cell, or mixing carriers on one sheet — ask for mode `2` and compose the page; mode `1` gives you a sheet you would have to cut up again:Print customs documents (DCAF/DDP)
Track a shipment
All available methods
Every method takes and returns typed DTOs from Arzcode\LaravelCorreos\Data\*.
$correos->preregister()
| Method | Purpose |
|---|---|
validateShipments(DeliveryRequestData) |
Validate without creating |
createShipments(DeliveryRequestData) |
Create shipments |
createCnShipments(DeliveryRequestData) |
Create shipments with CN22/CN23 customs data |
modifyShipment(DeliveryRequestData) |
Modify an existing shipment |
cancelShipment(AnnulmentRequestData) |
Cancel a shipment |
cancelExpedition(AnnulmentExpeditionRequestData) |
Cancel a whole expedition |
generateShipmentCode(GenerateShipmentCodeRequestData) |
Reserve codes without preregistering |
queryShipments(QueryRequestData) |
Query shipments by code |
queryShipmentsIris(QueryRequestData) |
Same query against the IRIS backend |
getExpeditionPackages(string $expeditionCode) |
Packages of an expedition |
getPackagesByReference(string $clientReference, ?string $contractNumber, ?string $clientNumber) |
Look up by your own reference |
searchLabelsInfo(SearchLabelsInfoRequestData) |
Label metadata for a set of shipments |
getBackofficeShipment(string $shipmentCode) |
Backoffice detail for one shipment |
getBackofficeErrors(?$contractNumber, ?$clientNumber, ?$dateFrom, ?$dateTo) |
Shipments rejected by the backoffice |
getBackofficeTotal(?$contractNumber, ?$clientNumber, ?$dateFrom, ?$dateTo) |
Totals for a period |
getBackofficeWaiting(?$contractNumber, ?$clientNumber, ?$dateFrom, ?$dateTo) |
Shipments waiting for admission |
$correos->labels()
| Method | Purpose |
|---|---|
printLabels(PrintLabelsRequestData) |
Labels as PDF, XML or ZPL |
printDocuments(PrintDocumentsRequestData) |
Customs documents (DCAF/DDP) |
getDocumentBackoffice(string $shipment) |
Documents already generated for a shipment |
$correos->tracking()
| Method | Purpose |
|---|---|
searchShipment(string $shippingCode) |
Shipment status and event history |
getExpedition(string $expeditionCode) |
Expedition with its clients and packages |
Enums
Typed enums cover the API's magic numbers. Each case carries a human readable label(), and
every enum exposes options() — value => label pairs, ready for a select input:
The full set: ProductCode, DocumentationType, LabelFormat, LabelPrintMode,
LabelOrderType, ShipmentType, DoiType, AdmissionMethod and ErrorCodeLanguage.
Error handling
API errors are thrown as CorreosApiException, which extends Saloon's RequestException:
Part of the Correos surface answers failures with HTTP 200 and an error field instead of an
error status — printing a label for an unknown shipment comes back as 200 with a null pdf
and a filled error. Those payloads raise the same exception, so a call that returns a DTO
has returned a usable one:
The check covers the top-level error/errors field of every response. Nested errors stay on
the DTO, because there they are the answer rather than a failure: validateShipments() still
returns its per-shipment validationErrorCount and error list without throwing.
The raw response of the last call — including a failed one — stays on the resource:
Retries and idempotency
The API gateway rate limits, so transient failures are retried three times with exponential
backoff starting at 500 ms. Set CORREOS_RETRY_TIMES=1 to switch retries off.
What is retried is deliberately narrow, because a retried write can book the same shipment twice:
| Failure | Read (GET) |
Write (POST) |
|---|---|---|
429 Too Many Requests |
retried | retried — the gateway rejected it before Correos saw it |
401 Unauthorized |
retried | retried — the cached token is dropped and a fresh one fetched |
408, 5xx |
retried | not retried |
| Connection error, timeout | retried | not retried |
Any other 4xx |
not retried | not retried |
Making createShipments() safe to repeat
`createShipments()` is not idempotent: a request that times out after Correos has registered
the shipment leaves you unable to tell success from failure, and sending it again books a
duplicate. Guard it in your own service layer:
1. Give every package a stable reference of your own (`clientReference` on `PackageData`) and
store it, with the resulting shipment and package codes, against your order.
2. Before creating, skip orders that already carry a shipment code.
3. After a timeout or a `5xx`, reconcile rather than retry — ask Correos what it holds under
that reference:
Configuration reference
Every environment variable
| Variable | Default | Purpose | | --- | --- | --- | | `CORREOS_OAUTH_CLIENT_ID` | — | CorreosID OAuth client id | | `CORREOS_OAUTH_CLIENT_SECRET` | — | CorreosID OAuth client secret | | `CORREOS_GATEWAY_CLIENT_ID` | — | API gateway client id | | `CORREOS_GATEWAY_CLIENT_SECRET` | — | API gateway client secret | | `CORREOS_TOKEN_URL` | `https://apioauthcid.correos.es/Api/Authorize/Token` | OAuth token endpoint | | `CORREOS_OAUTH_SCOPE` | `AP3 LBS RCG` | Requested scopes | | `CORREOS_PREREGISTER_URL` | `https://api1.correos.es/admissions/preregister/api/v1` | Preregister base URL | | `CORREOS_LABELS_URL` | `https://api1.correos.es/support/labels/api/v1` | Labels base URL | | `CORREOS_TRACKING_URL` | `https://api1.correos.es/support/trackpub/api/v2` | Tracking base URL | | `CORREOS_VERIFY_SSL` | `true` | Verify TLS certificates | | `CORREOS_FORCE_IP_RESOLVE` | — | `v4` to force IPv4 | | `CORREOS_RETRY_TIMES` | `3` | Attempts per request | | `CORREOS_RETRY_INTERVAL` | `500` | Milliseconds before the first retry | | `CORREOS_RETRY_EXPONENTIAL_BACKOFF` | `true` | Double the interval each attempt | | `CORREOS_TIMEOUT` | Saloon's 30s | Request timeout, seconds | | `CORREOS_CONNECT_TIMEOUT` | Saloon's 10s | Connection timeout, seconds | | `CORREOS_USER_AGENT` | `Arzcode-LaravelCorreos/1.2.3` | Override to identify your own app |Pre-production environment
Override the four URLs: PRE tends to use self-signed certificates and to answer on IPv4 only, so you may also need: > **Warning:** never disable SSL verification in production. **Network access.** Correos whitelists the client IP for PRE: connections from a non-whitelisted address (and any IPv6 address, which CloudFront answers with a `403`) are rejected before they reach the API, and PRE is only up Monday to Friday, 08:00–20:00 CET. Confirm with your Correos commercial contact whether your production contract carries the same restriction; if it does, every host that calls the API — web servers, queue workers, scheduled jobs — has to egress from a fixed, whitelisted IPv4 address, which usually means pinning them to a static IP or routing them through a NAT gateway.Using it from Filament (or any Livewire component)
Nothing special is needed to call the SDK from a Filament page or action — but four things are worth knowing.
Strip nulls before hydrating a DTO
Optional fields are typed `string|Optional`, and a Filament form submits `null` for the ones the user left alone, which is a `TypeError` rather than a validation error:Keep writes off the request cycle
`createShipments()` is not idempotent and is not retried on transport failures, so run it from a queued job and report back with a notification. If you do call the API inline, lower the timeouts for that path — the defaults (30s per attempt, three attempts on reads) are sized for a worker, not for someone watching a spinner:Serve the PDF from the action
`decodedPdf()` gives you the bytes directly: Catching the failure is one `try`, and `errorCode` / `moreInformation` make a better notification body than the raw message, which falls back to the response body when Correos answers without one:Selects and DTO properties
`Enum::options()` feeds `Select::make(...)->options(...)` straight; note PHP turns numeric string values into integer keys, so cast back when hydrating a string-backed enum from form state (`ShipmentType::from((string) $state)`). And if you want to hold a DTO in a public component property, turn on spatie's Livewire synthesizers — they ship disabled:Testing
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Pull requests are welcome. Run composer test, composer analyse and composer format
before opening one.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- arzcode
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-correos with dependencies
composer-runtime-api Version ^2.2
illuminate/contracts Version ^11.0||^12.0||^13.0
saloonphp/saloon Version ^4.0
spatie/laravel-data Version ^4.19
spatie/laravel-package-tools Version ^1.16