szymsza / ppl-create-package-label-api
一个使用 OAUTH 实现的 PHP 包,允许更轻松地与 PPL CPL API(即 MyAPI2)进行通信。
v0.0.3
2024-09-01 17:06 UTC
Requires
- php: ^7.3 || ^8.0
- league/oauth2-client: ^2.7
README
PPL(专业包裹物流)最近推出了其 API 的新版本,称为创建包裹标签或 MyApi2。此包允许您通过仅提供凭据即可连接到 API,无需设置 OAuth。此外,它还提供了一些用于编码请求或解码响应的辅助函数。
需求
- PHP 7.4 或更高版本
安装
$ composer require szymsza/ppl-create-package-label-api
凭据
您必须从 PPL 支持处请求凭据和 API 文档。Klient.ppl.cz 凭据将 不会 工作。
使用方法
库的主要目的是仅作为一个处理身份验证的 OAuth 包装器。因此,对于大多数端点,您将需要发送原始请求并自行解析接收到的数据。
然而,可以在 example/example.php
中找到一个涵盖常见用例的简单示例。填写您的凭据后,脚本应无需任何其他配置即可运行。在咨询此示例脚本和 API 文档后,使用其他端点应该是直观的。
初始化客户端
$clientId = 'XXX'; $clientSecret = 'YYY'; $development = true; $ppl = new PPL($clientId, $clientSecret, $development);
基本连接
调用 API 获取基本信息,例如 API 版本或当前时间。用于测试您的连接。
var_dump($ppl->versionInformation());
调用 API 获取描述可用 API 端点的 Swaggger JSON。您可以将此 JSON 粘贴到例如 https://editor.swagger.io/。
var_dump($ppl->getSwagger());
请求方法
该类提供了三种方法来初始化请求
requestJson(string $path, string $method = 'get', array $data = []): array|object|null
初始化请求并返回解码后的 JSON 数组或对象作为响应。当端点的响应是 JSON 且您不关心接收到的标题时很有用。requestHeader(string $path, string $method = 'get', array $data = [], string $header = 'Location'): string
初始化请求并返回响应中单个标题的值。当您不关心响应正文或其他标题的值时很有用。request(string $path, string $method = 'get', array $data = [])
初始化请求并返回原始ResponseInterface
对象。当您无法使用上述任一方法时很有用,例如,当您需要响应正文和标题时。
例如,您可以使用 requestJson
以这种方式获取可用产品:
var_dump($ppl->requestJson('codelist/product?limit=50&offset=0'));
创建运输标签
// Initialize the label batch $batchUrl = $ppl->requestHeader('shipment/batch', 'post', [ "labelSettings" => [ "format" => "Pdf", "completeLabelSettings" => [ "isCompleteLabelRequested" => true, "pageSize" => "A4" ] ], "shipments" => [ [ "referenceId" => "fe125c3a-3a36-487b-9e2b-e8919910ff63", "productType" => "BUSS", "sender" => [ "street" => "Novoveská 1262/95", "city" => "Ostrava", "zipCode" => "70900", "country" => "CZ", "phone" => "+420777888999", "email" => "sender@email.cz" ], "recipient" => [ "street" => "Františka a Anny Ryšových 1168", "city" => "Ostrava-Svinov", "zipCode" => "72100", "country" => "CZ", "phone" => "+420666777888", "email" => "recipient@email.cz" ] ] ], "shipmentsOrderBy" => "ShipmentNumber" ]); // Wait for the label to be created on the server // Note - you probably want to use some smarter solution on production... do { sleep(1); // Get the batch result $batchStatus = $ppl->requestJson($batchUrl); } while ($batchStatus->items[0]->importState !== "Complete"); // Save the two types of labels for the first shipment $bigLabelUrl = $ppl->relativizeUrl($batchStatus->completeLabel->labelUrls[0]); $singleLabelUrl = $ppl->relativizeUrl($batchStatus->items[0]->labelUrl); file_put_contents("big.pdf", $ppl->request($bigLabelUrl)->getBody()->getContents()); file_put_contents("single.pdf", $ppl->request($singleLabelUrl)->getBody()->getContents());
对于使用其他端点,请查阅文档并选择上面提到的适当 request
方法之一。