PHP
一个 PHP 脚本,使用 curl 扩展调用 API。它列出模板中带标签的变量,用给定的值测量所生成的图纸,并将其导出为 PDF。
下载:box.php。
<?php
// box.php: list a template's inputs, measure it and export it as a PDF with the PiQ SaaS API.
// PHP 8.0 or later, with the curl extension.
$key = getenv('PIQ_API_KEY');
$base = rtrim(getenv('PIQ_URL') ?: 'https://saas.parametriq.co.uk', '/');
$storage = getenv('PIQ_STORAGE'); // optional: a registered storage's name
if (!$key) {
fwrite(STDERR, "Set PIQ_API_KEY to your API key.\n");
exit(1);
}
const TEMPLATE = "L=400,\"Length\"\nW=300,\"Width\"\nP1=[L,0]\nP2=[L,W]\nP3=[0,W]\nPOLYLINE @1,[P0,P1,P2,P3],TRUE,0";
// the template itself, or (optional) where it is kept in your storage
$template = $storage ? ['source' => ['storage' => $storage, 'key' => 'templates/box.piq']] : ['template' => TEMPLATE];
$values = ['L' => 500, 'W' => 250];
/** Posts the body as JSON; returns the response body and headers, or stops with the problem. */
function post(string $path, array $body): array
{
global $key, $base;
$headers = [];
$curl = curl_init($base . $path);
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($body),
CURLOPT_HTTPHEADER => ["X-API-KEY: $key", 'Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADERFUNCTION => function ($curl, $line) use (&$headers) {
if (str_contains($line, ':')) {
[$name, $value] = explode(':', $line, 2);
$headers[strtolower(trim($name))] = trim($value);
}
return strlen($line);
},
]);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($response === false) {
fwrite(STDERR, curl_error($curl) . "\n");
exit(1);
}
if ($status >= 300) {
fwrite(STDERR, "Error $status\n");
$problem = json_decode($response, true); // a 401 has no body
if (!is_array($problem)) $problem = ['detail' => $response];
foreach (['title', 'detail'] as $part)
if (!empty($problem[$part])) fwrite(STDERR, $problem[$part] . "\n");
foreach ($problem['errors'] ?? [] as $field => $messages)
fwrite(STDERR, " $field: " . implode(' ', $messages) . "\n");
exit(1);
}
return [$response, $headers];
}
// 1. The template's labelled variables
[$json] = post('/inputs', $template);
foreach (json_decode($json, true)['inputs'] as $i)
echo "{$i['name']}: {$i['label']} ({$i['kind']}, " . json_encode($i['value']) . ")\n";
// 2. The drawing measured, with the values given
[$json] = post('/measure', $template + ['values' => $values]);
$m = json_decode($json, true);
$cut = 0;
foreach ($m['layers'] as $layer)
if ($layer['layer'] === 'Cut') $cut = $layer['length'];
echo "Size: {$m['width']} x {$m['height']}, cut length: $cut\n";
// 3. The drawing as a PDF
[$pdf, $headers] = post('/export/pdf', $template + ['values' => $values]);
file_put_contents('box.pdf', $pdf);
echo "Saved box.pdf ({$headers['x-piq-warnings']} warnings)\n";
// 4. Optional: the PDF saved to your storage instead of downloaded
if ($storage) {
$destination = ['storage' => $storage, 'key' => 'drawings/box.pdf'];
[$json] = post('/save/pdf', $template + ['values' => $values, 'destination' => $destination, 'overwrite' => true]);
$saved = json_decode($json, true);
echo "Saved {$saved['key']} to {$saved['storage']} ({$saved['size']} bytes)\n";
}
工作原理
- 设置。 密钥来自
PIQ_API_KEY,地址来自PIQ_URL(未设置时为服务本身的地址),还可以选择从PIQ_STORAGE读取存储名称。没有密钥时,脚本会立即停止。 - 模板。
$template是每个请求的起始正文:模板的文本作为template,或者在设置了PIQ_STORAGE时,以source给出模板在您存储中的保存位置。$values按名称给出L和W。每个请求都用+在其基础上添加内容。 post将正文以 JSON 形式发送到某个操作,并在X-API-KEY标头中携带密钥,同时在接收时收集响应的标头(按小写名称)。它交回正文和标头。- 错误。 无法发送的请求会打印原因。不成功的响应会先打印其状态,然后打印其问题描述:其
title、detail,以及errors中的每一项,即字段及其问题。401没有正文,因此没有更多内容可打印;不是 JSON 的正文按原样打印。然后脚本以1退出。 - Inputs。
POST /inputs只需要模板。其每个inputs都有name、label、kind和value。 - Measure。 使用这些值调用
POST /measure,可得到图纸的width和height,以及在layers中按图层统计的线长;切割长度即Cut图层上的长度。 - Export。
POST /export/pdf返回 PDF 本身而不是 JSON:按原样写入box.pdf。X-PiQ-Warnings标头表示有多少内容无法按原样导出。 - Save(可选)。 指定了存储时,
POST /save/pdf会导出同一图纸,并将其保存到您存储中的destination,'overwrite' => true表示替换已存在的文件。响应会说明保存位置及文件大小。
运行
将脚本保存为 box.php。它需要 curl 扩展:安装后 php -m 会列出 curl(在 Debian 和
Ubuntu 上为 php-curl 包;在 Windows 上,取消 php.ini 中 extension=curl 的注释)。然后:
export PIQ_API_KEY=XXXX-XXXX-XXXX-XXXXX
php box.php
它会打印模板中带标签的变量、图纸的尺寸和切割长度,并保存 box.pdf:
L: Length (Number, 400)
W: Width (Number, 300)
D: Depth (Number, 300)
Size: 500 x 250, cut length: 1500
Saved box.pdf (0 warnings)
如果给出模板无法使用的值(例如 "L": "long"),它会打印问题并停止:
Error 400
One or more validation errors occurred.
Some of the values given can't be used.
L: L is a number.
如果密钥不正确,它只会打印 Error 401:401 没有问题描述。
要试用存储部分,请注册一个存储(请参阅注册存储),将模板以 templates/box.piq
放入其中,并将 PIQ_STORAGE 设置为该存储的名称。这样,模板将从您的存储中读取,
PDF 也会以 drawings/box.pdf 保存到其中,替换已存在的任何文件。