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 deliveryorganizationId— the seller organization; without it items are created on behalf of the key organization, for a personal key — on behalf of its ownerpublish: falsekeeps new items as draftsretryTimesandretrySleepMs— the number of request attempts and the pause between them when the platform sends noRetry-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 sitevalue()— the value at a mapping pathfile()— a file from a media value that is not an address: a class with theFileSourceinterface — 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 identifiershop_category— the path of your own shop category instead ofcategory: 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” sectionfields— item fields;sku— the article number, unique per seller; a price or quantity given as a numeric string, for instance from a databasedecimal, is sent as a numberattributes— platform category attributes by name; for items with their own set of attributes — the path of a “name — value” array of the recordimages— the cover, the second card photo and the gallery; a value is an http(s) address, aFileSource, 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 imagesmodel3d.orientation— an array or JSON with therollDeg,pitchDeg,yawDegangles in degreesvariants— 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 inimages, the photo is also sent among the item images; for items with their own set of variants — an array with theeachkey: the path of the record's variant list, an element is anItemRecord, andname,price,files,update_months,imageandincludes_3d_modelare paths inside the elementpackage— a program delivered from a repository: the paths of the package managermanager—COMPOSER,NPMorPYPI, the package namenameand the address of the git repository of versionsgitparcel— the product package for the platform delivery service: the paths of the weightweightin grams, the lengthlength, widthwidthand heightheightin centimetres and the packaging kindpackaging; 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 theItemStoreinterface: the state of catalog items between runs;$fileStore— the file registry with theFileStoreinterface: 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: truesends 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-Afterpause 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
scanRejectionreason, and in the dashboard - An item that dropped out of the catalog is withdrawn by archiving its listing
gitSourcesof the report — the git source of sent package items: catalog, article number, the public deploy keydeployPublicKeyand the webhook addresswebhookUrlfor setting up the repository, version fetch failuresfailureandtagFailures- 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 missingCOVER_URL_AFTER_FILES— the cover is given as an address while files are among the imagesVALIDATION_ERRORwith thecategoryfield — the item has no platform category: the path of an unmapped shop category orREQUIRED; files of such an item are not uploadedFILES_SCAN_REJECTED— the item files failed the platform check, thescanRejectionsdetail 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 itFILE_TOO_LARGEand other codes with thefiledetail — the platform refused the item file: its size or type is outside the upload rules,FILE_INFECTEDorFILE_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.
- 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. - 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 theDeliveryStoreinterface: a delivery lock and a processed mark bywebhook-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
deliverDataretries 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 ispageandsize;fulfillment— a single orderdispatchhands 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;cancelcancels the order with a refund to the buyer- A platform carrier shipment leaves from the address the buyer tariff was quoted from;
dropOffPointslists the carrier drop-off points near it, the pointexternalIdis thedispatchdropOffPointId shipmentDocumentreturns the PDF label (LABEL) or waybill (WAYBILL) of a platform carrier shipmentdispatchandcancelretry 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
FulfillmentStatusChangedobject: the order, the status and the moment of the change
Did not find the answer to your question?
Create a request