PHP code example of beziworld / laravel-allegro

1. Go to this page and download the library: Download beziworld/laravel-allegro library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

beziworld / laravel-allegro example snippets


use Beziworld\Allegro\Facades\Allegro;
use Beziworld\Allegro\OAuth\Pkce;

// Redirect
$verifier = Pkce::generateVerifier();
session(['allegro_verifier' => $verifier, 'allegro_state' => $state = Str::random(40)]);

return redirect(Allegro::authorizationUrl($state, $verifier));

// Callback (the code is valid for a few seconds)
abort_unless($request->query('state') === session('allegro_state'), 403);

Allegro::exchangeCode($request->query('code'), session('allegro_verifier'));            // default account
Allegro::forUser('seller-' . $seller->id)->exchangeCode($request->query('code'), session('allegro_verifier')); // SaaS

$code = Allegro::startDeviceFlow();
// show $code->verificationUri and $code->formattedUserCode(), or the clickable $code->verificationUriComplete

$token = Allegro::forUser('seller-42')->waitForDeviceToken($code);   // honours "interval" and "slow_down"
// or poll yourself: Allegro::forUser('seller-42')->pollDeviceToken($code)->isGranted()

Allegro::application()->catalog()->categories();

// config/allegro.php
'accounts' => [
    'default' => ['refresh_token' => env('ALLEGRO_REFRESH_TOKEN')],
    'outlet' => ['token_key' => 'outlet-shop', 'language' => 'en-US'],
],

Allegro::orders()->checkoutForms();                       // default account
Allegro::account('outlet')->orders()->checkoutForms();    // named account
Allegro::forUser('seller-42')->orders()->checkoutForms(); // seller connected at runtime (SaaS)
Allegro::forUser('seller-42')->isConnected();
Allegro::forUser('seller-42')->disconnect();

// routes/console.php
Schedule::command('allegro:poll-orders --all')->everyMinute()->withoutOverlapping();
// sellers connected at runtime: --user=seller-1 --user=seller-2, or call the poller yourself:
// app(OrderEventPoller::class)->poll(Allegro::forUser($key));

use Beziworld\Allegro\Data\OrderEvent;
use Beziworld\Allegro\Events\OrderEventReceived;
use Beziworld\Allegro\Facades\Allegro;

Event::listen(function (OrderEventReceived $received): void {
    if ($received->event->type !== OrderEvent::READY_FOR_PROCESSING) {
        return;
    }

    $order = Allegro::forUser($received->account)->orders()->checkoutForm($received->event->checkoutFormId);

    $order->buyer->login;
    $order->delivery?->address?->fullName();
    $order->delivery?->pickupPointId;          // parcel locker or pickup point
    $order->invoice?->taxId;                   // NIP when the buyer wants an invoice
    $order->payment?->isCashOnDelivery();
    $order->totalToPay?->amount;               // "123.45" (string)
    foreach ($order->lineItems as $item) {
        $item->externalId;                     // your SKU (offer external.id)
        $item->quantity;
        $item->price?->amount;
    }
});

$page = Allegro::orders()->checkoutForms([
    'status' => 'READY_FOR_PROCESSING',
    'fulfillment.status' => ['NEW', 'PROCESSING'],
    'lineItems.boughtAt.gte' => now()->subDay(),
    'sort' => '-lineItems.boughtAt',
], limit: 100, offset: 0);                      // $page->checkoutForms, $page->totalCount

foreach (Allegro::orders()->allCheckoutForms(['status' => 'READY_FOR_PROCESSING']) as $order) {
    // every page, within the 10 000 orders window of the API
}

use Beziworld\Allegro\Enums\FulfillmentStatus;

Allegro::orders()->setFulfillmentStatus($order->id, FulfillmentStatus::ReadyForShipment, $order->revision);
// a stale revision throws ApiException with isConflict() === true

Allegro::orders()->carriers();                                         // ids such as INPOST, DPD, DHL, POCZTA_POLSKA
Allegro::orders()->addTrackingNumber($order->id, 'INPOST', '620000000000000');
Allegro::orders()->addTrackingNumber($order->id, 'OTHER', 'X123', 'Local courier', [$lineItemId]);
Allegro::orders()->shipments($order->id);
Allegro::orders()->setFulfillmentStatus($order->id, FulfillmentStatus::Sent);

$documentId = Allegro::orders()->uploadInvoice($order->id, $pdfContents, invoiceNumber: 'FV/1/11/2026');
Allegro::orders()->addBillingDocumentLink($order->id, 'https://shop.example/invoices/1.pdf');
Allegro::orders()->billingDocuments($order->id);

use Beziworld\Allegro\Data\Money;

$page = Allegro::offers()->list(['publication.status' => ['ACTIVE'], 'external.id' => 'SKU-1'], limit: 1000);
$offer = Allegro::offers()->get('7712345678');           // ProductOffer: price, stockAvailable, status, raw

$result = Allegro::offers()->create([
    'productSet' => [['product' => ['id' => $productId]]],
    'sellingMode' => ['price' => Money::of(49.99)->toArray()],
    'stock' => ['available' => 10],
    'external' => ['id' => 'SKU-1'],
    'publication' => ['status' => 'ACTIVE'],
]);
$offer = Allegro::offers()->waitForOperation($result);   // polls the operation when Allegro answered 202

Allegro::offers()->edit('7712345678', ['stock' => ['available' => 5]]);

// Batch commands (a UUID commandId is generated unless you pass one)
$report = Allegro::offers()->changePrice(['7712345678', '7712345679'], Money::of('39.90'));
$report = Allegro::offers()->changeQuantity(['7712345678'], 3, 'GAIN');
Allegro::offers()->priceChangeReport($report->id)->isCompleted();
Allegro::offers()->priceChangeTasks($report->id);         // per-offer SUCCESS / FAIL with errors

$wza = Allegro::shipmentManagement();

$proposal = $wza->deliveryProposals($order->id);         // recommended input for the shipment
$command = $wza->createShipment([
    'deliveryMethodId' => $order->delivery->methodId,
    'sender' => [...], 'receiver' => [...],
    'packages' => [['type' => 'PACKAGE',
        'length' => ['value' => 30, 'unit' => 'CENTIMETER'], 'width' => ['value' => 20, 'unit' => 'CENTIMETER'],
        'height' => ['value' => 10, 'unit' => 'CENTIMETER'], 'weight' => ['value' => 1.5, 'unit' => 'KILOGRAMS']]],
    'labelFormat' => 'PDF',
]);
$shipment = $wza->waitForShipment($command);              // Shipment: id, carrier, waybills

$pdf = $wza->label([$shipment->id], 'A6');                // null when no label is available
$protocol = $wza->protocol([$shipment->id]);              // null for carriers without protocols
$slots = $wza->pickupProposals([$shipment->id], $pickupAddress, now()->addDay());
$wza->createPickup([$shipment->id], $pickupAddress, ['date' => '2026-11-05', 'minTime' => '10:00', 'maxTime' => '14:00']);
$wza->waitForCancellation($wza->cancelShipment($shipment->id));

Allegro::billing()->entries(['occurredAt.gte' => now()->subMonth(), 'type.id' => ['SUC']]);
Allegro::messaging()->threads(['read' => false]);
Allegro::messaging()->reply($threadId, 'Your parcel ships today.');
Allegro::messaging()->send('buyer-login', 'Thank you!', $orderId, [Allegro::messaging()->uploadAttachment('invoice.pdf', $pdf)]);
Allegro::customerReturns()->list(['status' => 'DELIVERED']);       // beta media type
Allegro::customerReturns()->rejectRefund($returnId, 'REFUND_REJECTED', 'Item was used');
Allegro::catalog()->matchingCategories('wool socks');
Allegro::catalog()->searchProducts('5901234123457', 'GTIN');
Allegro::catalog()->parameters('257931');

// Any other endpoint
Allegro::request('GET', '/sale/shipping-rates');
Allegro::request('PUT', "/sale/offer-modification-commands/{$uuid}", body: [...]);
Allegro::send('GET', '/sale/offers', ['limit' => 1])->header('Trace-Id');   // raw Response
bash
php artisan allegro:device-login            # default account
php artisan allegro:device-login second     # named account
php artisan allegro:device-login --user=seller-42