PHP client

What it does

The opotopo/seller-api package is a PHP Seller API client for a site on any framework or none: it uploads the catalog to the platform, uploads files, withdraws items that dropped out of the catalog, receives purchase notifications, hands the buyer a key from your own licensing system and handles orders. A Laravel site fits the Laravel client, a WooCommerce store — the WooCommerce client, a 1C-Bitrix store — the 1C-Bitrix client: all are built on this package.

The package is open source under the MIT license: code and releases — github.com/AdzerKI/seller-api-php, supported PHP versions — the package page on Packagist.

Installation

composer require opotopo/seller-api guzzlehttp/guzzle

Requests go through any PSR-18 HTTP client with PSR-17 factories; Guzzle is one of them.

The client

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Opotopo\SellerApi\ClientConfig;
use Opotopo\SellerApi\SellerApiClient;

$factory = new HttpFactory;
$client = new SellerApiClient(new Client(['timeout' => 60]), $factory, $factory, new ClientConfig(
    url: 'https://api.opotopo.com',
    key: getenv('OPOTOPO_API_KEY'),
    organizationId: getenv('OPOTOPO_ORGANIZATION_ID') ?: null,
));
  • key — a key of the "API" section with the write listings, remove listings and file upload permissions, plus deliver purchase data for data delivery
  • organizationId — the seller organization; without it items are created on behalf of the key organization, for a personal key — on behalf of its owner
  • publish: false keeps new items as drafts
  • retryTimes and retrySleepMs — the number of request attempts and the pause between them when the platform sends no Retry-After

The catalog

A site catalog is a class with the CatalogSource interface: mapping() returns the item mapping, records() — catalog records with the ItemRecord interface.

use Opotopo\SellerApi\Catalog\CatalogSource;
use Opotopo\SellerApi\Catalog\ItemRecord;
use Opotopo\SellerApi\Files\FileSource;

final class DrawingRecord implements ItemRecord
{
    public function __construct(private readonly array $row) {}

    public function key(): string
    {
        return (string) $this->row['id'];
    }

    public function value(string $path): mixed
    {
        return $this->row[$path] ?? null;
    }

    public function file(mixed $entry): FileSource
    {
        return new LocalFile('/var/www/storage/'.$entry);
    }
}
  • key() — the stable record key on the site
  • value() — the value at a mapping path
  • file() — a file from a media value that is not an address: a class with the FileSource interface — a stable source string, existence, name, size, modification time, content type and a read stream

The mapping:

[
    'category' => 'opotopo_category_id',
    'fields' => [
        'sku' => 'article',
        'title' => 'name',
        'description' => 'description',
        'price' => 'price',
    ],
    'attributes' => [
        'Load capacity, t' => 'capacity',
    ],
    'images' => [
        'cover' => 'cover_path',
        'second' => 'second_photo_path',
        'gallery' => 'photo_paths',
    ],
    'model3d' => [
        'url' => 'model_url',
        'orientation' => 'model_orientation',
    ],
    'variants' => [
        ['name' => 'Drawings', 'price' => 'price', 'files' => 'drawing_paths'],
        ['name' => 'Drawings + 3D', 'price' => 'price_with_model', 'files' => 'drawing_paths', 'includes_3d_model' => true],
    ],
]
  • category — the path of the platform category identifier
  • shop_category — the path of your own shop category instead of category: a list of level names from the root or a single-level string; the platform category comes from the shop category mapping in the “Developers” section
  • fields — item fields; sku — the article number, unique per seller; a price or quantity given as a numeric string, for instance from a database decimal, is sent as a number
  • attributes — platform category attributes by name; for items with their own set of attributes — the path of a “name — value” array of the record
  • images — the cover, the second card photo and the gallery; a value is an http(s) address, a FileSource, any other value — a record file, or a list of them. Uploaded files go before addresses, so a cover given as an address is rejected when files are among the images
  • model3d.orientation — an array or JSON with the rollDeg, pitchDeg, yawDeg angles in degrees
  • variants — at least one variant; a variant without a price is not sent, files — files the buyer receives after payment, update_months — the path of the licence variant update period in months, image — the path of the variant photo: a value as in images, the photo is also sent among the item images; for items with their own set of variants — an array with the each key: the path of the record's variant list, an element is an ItemRecord, and name, price, files, update_months, image and includes_3d_model are paths inside the element
  • package — a program delivered from a repository: the paths of the package manager manager — COMPOSER, NPM or PYPI, the package name name and the address of the git repository of versions git
  • parcel — the product package for the platform delivery service: the paths of the weight weight in grams, the length length, width width and height height in centimetres and the packaging kind packaging; fractions are rounded up, and without a positive weight and all three dimensions the package is not sent and the listing keeps the previous one

Synchronization

use Opotopo\SellerApi\Files\FileUploader;
use Opotopo\SellerApi\Sync\Synchronizer;

$synchronizer = new Synchronizer($client, new FileUploader($client, $fileStore, $factory), $itemStore, 100);
$catalogs = ['drawings' => new DrawingCatalog];

$report = $synchronizer->run($catalogs);
$report = $synchronizer->run($catalogs, only: 'drawings');
$report = $synchronizer->run($catalogs, full: true);
  • $itemStore — the item registry with the ItemStore interface: the state of catalog items between runs; $fileStore — the file registry with the FileStore interface: uploaded files. Both are kept on the site side, for instance in its database
  • the fourth argument is the batch size
  • Changed items and items rejected by the previous run are sent; full: true sends all of them
  • Items go in batches with a batch idempotency key; a batch rejected by validation is sent again item by item
  • Connection failures, 429, 5xx and a batch the platform is still processing are retried with the same key after the Retry-After pause of the response
  • A file is uploaded once; a changed file is uploaded again
  • An item with a file the platform is still scanning for viruses is accepted: the listing is published after the scan; a file that fails the scan is removed from the listing — with the "File removed by moderation or virus scan" notification carrying the scanRejection reason, and in the dashboard
  • An item that dropped out of the catalog is withdrawn by archiving its listing
  • gitSources of the report — the git source of sent package items: catalog, article number, the public deploy key deployPublicKey and the webhook address webhookUrl for setting up the repository, version fetch failures failure and tagFailures
  • Scheduled runs go through the site server scheduler; runs must not overlap

Rejections

The run SyncReport holds the numbers of created, updated, unchanged and withdrawn items and the rejections: catalog, article number, code and details. A rejected item is retried by the next run.

  • FILE_NOT_FOUND — the item file is missing
  • COVER_URL_AFTER_FILES — the cover is given as an address while files are among the images
  • VALIDATION_ERROR with the category field — the item has no platform category: the path of an unmapped shop category or REQUIRED; files of such an item are not uploaded
  • FILES_SCAN_REJECTED — the item files failed the platform check, the scanRejections detail gives the reason per file: FILE_INFECTED — a virus was found, FILE_SCAN_LIMITS_EXCEEDED — the file or archive exceeds the check limits; the same file is not uploaded again, replace it
  • FILE_TOO_LARGE and other codes with the file detail — the platform refused the item file: its size or type is outside the upload rules, FILE_INFECTED or FILE_SCAN_LIMITS_EXCEEDED — the file failed the check
  • other codes — the "API reference" of the "API" section

Purchases and data delivery

For a program with its own licensing system the client passes purchases on and hands the buyer a key from that system — delivering purchase data from your own system.

  1. In the "Webhooks" block of the "API" section add the notification address of the site with the "New order" and "Purchase revoked" events, and put its signing secret into OPOTOPO_WEBHOOK_SECRET.
  2. Receive the notification at that address:
use Opotopo\SellerApi\Webhooks\PurchaseCreated;
use Opotopo\SellerApi\Webhooks\PurchaseRevoked;
use Opotopo\SellerApi\Webhooks\WebhookReceiver;

$receiver = new WebhookReceiver(getenv('OPOTOPO_WEBHOOK_SECRET'), $deliveryStore);
$result = $receiver->receive(file_get_contents('php://input'), [
    WebhookReceiver::ID_HEADER => $_SERVER['HTTP_WEBHOOK_ID'] ?? null,
    WebhookReceiver::TIMESTAMP_HEADER => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? null,
    WebhookReceiver::SIGNATURE_HEADER => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? null,
], function (object $event) use ($client) {
    if ($event instanceof PurchaseCreated && $event->delivery === 'DATA') {
        $client->deliverData($event->fulfillmentId, License::issue($event->purchaseId));
    }
    if ($event instanceof PurchaseRevoked) {
        License::revoke($event->purchaseId);
    }
});
http_response_code($result->status());
  • $deliveryStore — the delivery store with the DeliveryStore interface: a delivery lock and a processed mark by webhook-id, for instance in the site cache or database
  • The client verifies the notification signature, a foreign signature is rejected with status 401
  • One notification gives one event even when delivered again; a repeat during processing is rejected with status 409
  • An exception in the handler leaves the delivery unmarked: answer the platform with an error, and it retries the delivery
  • deliverData retries connection failures, 429 and 5xx with the same idempotency key — the data is never delivered twice; a replacement goes with the third argument, the identifier of the replaced record from the delivery response

Orders

The key needs the "Read orders" and "Fulfill orders" permissions; the orders of a company come with its organizationId in the client configuration.

use Opotopo\SellerApi\Webhooks\FulfillmentStatusChanged;

$page = $client->fulfillments(['PENDING'], from: new DateTimeImmutable('-7 days'));
foreach ($page['content'] as $order) {
    $client->dispatch($order['id'], ['carrierName' => 'Shop courier', 'trackingNumber' => 'TRK-1']);
}
$client->cancel($fulfillmentId, 'Out of stock');
$label = $client->shipmentDocument($order['shipmentId'], 'LABEL');

if ($event instanceof FulfillmentStatusChanged) {
    Order::syncStatus($event->fulfillmentId, $event->status);
}
  • fulfillments — orders by statuses and checkout period, newest first, the page is page and size; fulfillment — a single order
  • dispatch hands the order over: by your own delivery — the carrier and tracking number, by a platform carrier at the tariff the buyer chose — the drop-off point and the packages with their items, without packages — the item package per unit, without a drop-off point — collection by the carrier courier where the tariff allows it, pickup — no body; cancel cancels the order with a refund to the buyer
  • A platform carrier shipment leaves from the address the buyer tariff was quoted from; dropOffPoints lists the carrier drop-off points near it, the point externalId is the dispatch dropOffPointId
  • shipmentDocument returns the PDF label (LABEL) or waybill (WAYBILL) of a platform carrier shipment
  • dispatch and cancel retry a failure with the same idempotency key — the action never runs twice
  • The "Order status changed" event of the notification address reaches the handler as a FulfillmentStatusChanged object: the order, the status and the moment of the change
Was this article helpful?

Did not find the answer to your question?

Create a request