Search by

graystackit / laravel-pingen-api

bharb

Laravel package for the Pingen print-and-post API and its webhooks, powered by Saloon v4

Package info

github.com/GraystackIT/laravel-pingen-api

pkg:composer/graystackit/laravel-pingen-api

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

v0.2.0 2026-12-03 16:43 UTC

This package is auto-updated.

Last update: 2026-12-03 16:44:30 UTC


README

A Laravel package for the Pingen API, built on Saloon 4.

Upload a PDF and Pingen prints and posts it as a physical letter. Create drafts, price them before they cost anything, submit, cancel, track delivery events, and receive signed webhooks as Laravel events — all with a clean, Laravel-native interface.

Requirements

  • PHP 8.3+
  • Laravel 12 or 13
  • A Pingen account with an OAuth client (client_credentials grant)

Installation

composer require graystackit/laravel-pingen-api

Laravel auto-discovers the service provider. Then publish the config file and, optionally, the migrations:

php artisan vendor:publish --tag=pingen-config
php artisan vendor:publish --tag=pingen-migrations   # optional, see "Tables" below

Configuration

Add the following to your .env file:

PINGEN_CLIENT_ID=your-oauth-client-id
PINGEN_CLIENT_SECRET=your-oauth-client-secret
PINGEN_ORGANISATION_ID=your-organisation-uuid

# Optional — defaults shown
PINGEN_STAGING=false
PINGEN_SCOPES=
PINGEN_ADDRESS_POSITION=left
PINGEN_ADDRESS_PLACEMENT=place
PINGEN_ADDRESS_QUEUE_CONNECTION=
PINGEN_ADDRESS_QUEUE=
PINGEN_ADDRESS_POLL_SECONDS=10
PINGEN_ADDRESS_TIMEOUT_MINUTES=30
PINGEN_AUTO_SEND=false
PINGEN_DELIVERY_PRODUCT=
PINGEN_PRINT_MODE=
PINGEN_PRINT_SPECTRUM=
PINGEN_WEBHOOK_ENABLED=true
PINGEN_WEBHOOK_PATH=pingen/webhook
PINGEN_WEBHOOK_SIGNING_KEY=
PINGEN_WEBHOOK_THROTTLE=120,1
PINGEN_MIGRATIONS=true
PINGEN_STORE_LOGS=false
PINGEN_STORAGE_DRIVER=log
PINGEN_RETRY_TIMES=3
PINGEN_RETRY_DELAY_MS=500

PINGEN_STAGING=true switches both the identity server and the API host at once — Pingen runs staging as a separate world with its own accounts and data. Keep it on until you mean to post something real.

If the OAuth client or the organisation is not configured, a ConfigurationException is thrown before any request is sent.

Don't know your organisation UUID yet?

use GraystackIT\Pingen\PingenService;

foreach (PingenService::fromConfig()->organisations()->list() as $organisation) {
    echo $organisation->id.' '.$organisation->name.PHP_EOL;
}

Usage

Inject PingenService via the constructor or resolve it from the container.

Send a letter

use GraystackIT\Pingen\Data\LetterDraft;
use GraystackIT\Pingen\PingenService;

$letter = app(PingenService::class)->send(new LetterDraft(
    contents: $pdfBytes,
    fileName: 'invoice-2026-0042.pdf',
));

$letter->id;      // the UUID Pingen assigned
$letter->status;  // LetterStatus::Validating — Pingen inspects the file next

That one call does three HTTP requests: it asks for an upload slot, PUTs the file to the signed URL it gets back, and creates the letter quoting that slot's signature.

Retries without a second letter

Creating a letter is the one call in this package that cannot be safely repeated. A retry after a response that never arrived — a timeout, a worker killed between the answer and the save — posts a second physical letter while the first is already being printed, and nothing on the caller's side can see across that gap.

Pass a key of your own, the same one on every attempt at the same letter:

$service->send($draft, idempotencyKey: 'invoice-'.$invoice->id);

Pingen answers a repeat of that key with the letter it created the first time instead of creating another. Derive the key from the record you are posting, not from the attempt.

Send a file from disk

$letter = app(PingenService::class)->send(
    LetterDraft::fromPath(storage_path('invoices/inv-42.pdf'))
);

Price first, then submit

auto_send defaults to false, so send() creates a draft. Nothing is printed and nothing is charged until it is submitted:

$price = $service->estimate(country: 'AT');   // 1.65 CHF

$service->submit($letter->id);                // now it costs money

Set PINGEN_AUTO_SEND=true, or pass autoSend: true, to do both in one call. Auto-sending requires deliveryProduct, printMode and printSpectrum — from the draft or the configured defaults — because there is no later call in which to name them.

Let Pingen put the address on

By default Pingen reads the recipient off the PDF (see PDF Requirements). Pass a Recipient instead and Pingen prints it onto the letter itself:

use GraystackIT\Pingen\Data\Recipient;
use GraystackIT\Pingen\Enums\AddressPlacement;

$service->send(new LetterDraft(
    contents:  $pdfBytes,
    fileName:  'invoice-2026-0042.pdf',
    autoSend:  true,
    recipient: new Recipient(['Hans Beispiel', 'Musterweg 5', '3011 Bern'], 'CH'),
    addressPlacement: AddressPlacement::Place,   // or CoverPage; default from PINGEN_ADDRESS_PLACEMENT
));

Leave the country out of the lines: Pingen appends its name itself. The address may be at most 255 characters, and the country is an ISO 3166-1 alpha-2 code; both are checked before anything is uploaded.

Placement What Pingen does Use when
Place (default) Prints the address into the window of your file. No extra sheet. Your PDF leaves the address window empty
CoverPage Puts a cover page with the address in front of your file. One extra sheet. The PDF is not yours, or already carries an address

Pingen accepts the address only after it has inspected the file, so this cannot happen in the create call. send() therefore creates the letter as a draft — even with autoSend: true — and queues ApplyLetterAddress, which:

  1. waits while the letter is validating / processing / fixing
  2. sends the address once Pingen has settled on action_required (address_empty) or valid
  3. waits for the second inspection, until the letter's history shows address_placed or cover_page_created and the letter is valid
  4. fires LetterAddressApplied, then submits the letter if autoSend asked for it (LetterSubmitted)

Anything else fires LetterAddressFailed with the reason and leaves the letter an unsubmitted draft — nothing is posted to whatever the file says. That covers a file that still fails inspection (a font that is not embedded), a letter in a state that takes no address, Place on a file that has an address of its own, and a letter that has not settled by PINGEN_ADDRESS_TIMEOUT_MINUTES.

This needs a running queue worker. The job looks again every PINGEN_ADDRESS_POLL_SECONDS; set PINGEN_ADDRESS_QUEUE / PINGEN_ADDRESS_QUEUE_CONNECTION to run it somewhere specific. Running it twice is harmless: a repeat finds the fix in the letter's history and neither applies the address again nor announces it twice.

To do the steps yourself instead, the same calls are on the letter service:

$service->letters()->placeAddress($letterId, $recipient);   // letter must be action_required
$service->letters()->addCoverPage($letterId, $recipient);   // valid or action_required

Both answer at once and leave the letter on fixing while Pingen works.

Using dependency injection

use GraystackIT\Pingen\Data\LetterDraft;
use GraystackIT\Pingen\PingenService;

class InvoiceController extends Controller
{
    public function __construct(private PingenService $pingen) {}

    public function post(Invoice $invoice): void
    {
        $this->pingen->send(new LetterDraft(
            contents: $invoice->renderPdf(),
            fileName: "invoice-{$invoice->number}.pdf",
        ));
    }
}

Several Pingen accounts

The configured organisation is the default. Ask for another and you get a separate service rather than a mutated one, so a letter cannot leave from the wrong account by accident:

$other = app(PingenService::class)->forOrganisation('another-organisation-uuid');

Letter Management

$service->find($letterId);                    // read one letter
$service->cancel($letterId);                  // stop it before printing
$service->letters()->list(limit: 50);         // paginated
$service->letters()->update($id, [...]);      // edit a draft
$service->letters()->delete($id);             // delete a draft
$service->letters()->downloadFile($id);       // the PDF as it will be printed
$service->letters()->placeAddress($id, $r);   // print an address into the empty window
$service->letters()->addCoverPage($id, $r);   // put a cover page with an address in front
$service->events()->list($letterId);          // tracking history

PDF Requirements

Pingen inspects the PDF before anything is printed. A file that does not pass the inspection doesn't fail outright: it lands on LetterStatus::ActionRequired and waits for a corrected file. Fonts must be embedded; a PDF relying on the viewer's own Helvetica is rejected.

The address goes on the page

Pingen reads the recipient off the PDF through the address window; the package says where that window is (addressPosition, left or right). Either your PDF carries the address there, or you leave the window empty and pass a Recipient — see Let Pingen put the address on.

Layout (A4, left address)

Region x y w h
Restricted border 5mm on every side
Postage area 20mm 40mm 89.5mm 47.5mm
Address area 22mm 60mm 85.5mm 25.5mm

The address area sits inside the postage area, which is the trap: an address block starting above y=60 is still inside the postage area and is rejected as content found there, while one starting lower overflows past y=85.5 and silently loses its first lines. The whole address has 25.5mm of height.

Why a letter was rejected

The reason is in the event's data, and nowhere else:

foreach ($service->events()->list($letterId) as $event) {
    echo $event->code;   // 'content_failed_inspection'
    print_r($event->data);   // ['protected_stamp_area'] — the actual reason
}
Reason Meaning
protected_stamp_area Content found in the postage area
address_insufficient_lines Too few address lines read in the window
address_empty Nothing found in the address window

Print Options

delivery_product, print_mode and print_spectrum are passed through as plain strings rather than modelled as enums: the catalogue differs per country and changes without this package being released, and a hard-coded list would eventually block a product that works.

To constrain them for your own application, fill the allowlists in config/pingen.php:

'allowed' => [
    'delivery_product' => ['cheap', 'fast'],
    'print_mode'       => ['simplex', 'duplex'],
    'print_spectrum'   => ['grayscale', 'color'],
],

An empty list means anything goes. A value outside a non-empty list throws ConfigurationException before the file is uploaded, so a typo costs nothing.

Webhooks

Register one per event category. The categories are issues, sent, undeliverable, delivered and channel_subscriptions — there is no letters, and anything else is refused with a 422. A letter-sending application wants the first four.

The signing key is yours: Pingen never returns it, so store it before the first delivery arrives.

php artisan pingen:webhooks                                  # what is registered
php artisan pingen:webhooks --url=https://app.test/pingen/webhook

With no --url the command lists the registrations and says, per row, whether the key each was registered with still matches pingen.webhook.signing_key — compared, never printed. With a --url it replaces them all, which is what a development tunnel that renamed itself needs; pass --keep to add rather than replace, and --category= to choose.

Both failures this guards against are silent ones. A webhook pointing at a host that no longer answers, and a webhook registered under a key the application no longer has, look identical from the inside: no deliveries, no errors, nothing in any log.

In code:

$service->webhooks()->create(
    eventCategory: 'sent',
    url:           route('pingen.webhook'),
    signingKey:    config('pingen.webhook.signing_key'),
);

The package registers POST /pingen/webhook and dispatches a Laravel event per delivery:

Event When
LetterCreated A letter was created (fired locally, not by a webhook)
LetterSubmitted A letter went to production
LetterAddressApplied Pingen put the Recipient on the letter (fired locally by the job)
LetterAddressFailed It could not; the letter stays a draft (fired locally by the job)
LetterSent Handed to the postal service
LetterDelivered Reported delivered
LetterCancelled Stopped before printing
LetterFailed Will not be sent
LetterUndeliverable Could not be delivered — the copy was still produced and paid for
LetterStatusChanged Any status this version does not model, carrying the raw string

That last row matters: Pingen extends its vocabulary without this package being released, so an unrecognised status is announced rather than dropped.

Signature and replay protection

Pingen signs a delivery as Signature: hash_hmac('sha256', $rawBody, $signingKey) in plain hex. Nothing time-bound is signed, so a signature never expires and a delivery captured off the wire stays replayable forever. Verifying it proves the body came from Pingen at some point, not that it is arriving for the first time.

The pingen_webhook_events table closes that gap: every delivery id is recorded, and a repeat is answered {"status":"ok","duplicate":true} without firing anything. It also makes Pingen's own retries harmless. Setting PINGEN_MIGRATIONS=false removes that guard.

Prune the table on a schedule:

php artisan pingen:prune-webhook-events --days=30

Tables

Table Purpose
pingen_webhook_events The replay guard above
pingen_letters Optional record of letters sent, only with PINGEN_STORE_LOGS=true and PINGEN_STORAGE_DRIVER=database

Neither is read to make a decision — the first is a guard, the second is a record. Set PINGEN_MIGRATIONS=false to inherit no tables at all, and read the warning above first.

Error handling

All API errors throw GraystackIT\Pingen\Exceptions\PingenException (extends RuntimeException) or one of its subclasses.

use GraystackIT\Pingen\Exceptions\LetterRejectedException;
use GraystackIT\Pingen\Exceptions\PingenException;
use GraystackIT\Pingen\Exceptions\RateLimitExceededException;

try {
    $letter = $service->send($draft);
} catch (LetterRejectedException $e) {
    // 400/409/422 — fix the input, do not retry
    print_r($e->errors);         // JSON:API error objects
} catch (RateLimitExceededException $e) {
    echo $e->retryAfter;         // seconds to wait
} catch (PingenException $e) {
    echo $e->getMessage();
    echo $e->status;             // HTTP status code
}
Exception Meaning
ConfigurationException Missing credentials, or an option outside the allowlist — thrown before anything is sent
LetterRejectedException Pingen refused the input (400/409/422): fix it, do not retry
RateLimitExceededException 429, carrying retryAfter, limit, remaining and resetsAt
FileUploadExpiredException The signed upload slot expired before the bytes were sent — request a new one
PingenException Everything else; ->status and ->errors carry the JSON:API error objects

The distinction is not cosmetic: an application that meters sends reacts in opposite ways to a 422 and a 429, and that decision should not be a string match on a message.

Access tokens

Fetched with the client_credentials grant and cached until shortly before they expire. The cache key includes the client id and the identity host, so staging and production — and two OAuth clients — never share a token. A 401 against a cached token forgets it and retries once.

Testing

Tests use Saloon's MockClient — no real API calls are made. The access token comes from Laravel's HTTP client, so fake the identity server alongside it:

use GraystackIT\Pingen\PingenService;
use GraystackIT\Pingen\Requests\Letters\GetLetterRequest;
use Illuminate\Support\Facades\Http;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;

Http::fake([
    'identity-staging.pingen.com/*' => Http::response(['access_token' => 'test-token', 'expires_in' => 3600]),
]);

$service = PingenService::fromConfig();

$service->connector()->withMockClient(new MockClient([
    GetLetterRequest::class => MockResponse::make([
        'data' => [
            'id' => 'letter-uuid',
            'type' => 'letters',
            'attributes' => ['status' => 'sent'],
        ],
    ], 200),
]));

$letter = $service->find('letter-uuid');

Run the package test suite:

vendor/bin/pest

Fixtures are invented throughout: a genuine Pingen payload carries a recipient's postal address, which is personal data and does not belong in a public repository.

Against a real account

Install the package into a throwaway Laravel application, point it at a staging account, and drive it from php artisan tinker:

composer create-project laravel/laravel pingen-sandbox
cd pingen-sandbox
composer config repositories.pingen path ../laravel-pingen-api
composer require graystackit/laravel-pingen-api:@dev

A path repository symlinks the package, so edits to it are live in the sandbox with no reinstall. Work up from the reads — nothing costs money until submit().

A caveat on completeness

Pingen's documentation page renders in the browser from an OpenAPI document served at https://api.pingen.com/documentation/swagger-docs. The endpoints and field names here follow that document and were checked against a staging account.

Confirmed live: the three-call send flow, the price calculator, the letter and event reads, the print options cheap / registered / simplex / grayscale, the statuses validating, valid, action_required, fixing and submitted, and the three address endpoints.

The address endpoints (resolve/place-address, resolve/cover-page, create-cover-page) carry request schemas in that document but are not rendered on the documentation page, and which letter status each accepts is not written down anywhere — the rules in this package are what staging answered. The LetterStatus cases are the list the specification gives for its statistics endpoint; the status attribute itself is typed as a plain string. That is why an unknown status still degrades to LetterStatus::Unknown with the raw string kept beside it. Please open an issue if you find one that differs.

meta_data is not modelled. Pingen defines it as a fixed recipient/sender structure rather than free storage — anything else is refused with a 400 — and on staging it neither placed an address nor was it returned, so it has no observable effect to offer.

License

MIT.