PHP
Un script de PHP que usa la API con la extensión curl. Enumera las variables etiquetadas de una plantilla, mide el dibujo que genera con los valores dados y lo exporta como PDF.
Descárguelo: 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";
}
Cómo funciona
- Configuración. La clave se toma de
PIQ_API_KEY, la dirección dePIQ_URL(el propio servicio si no está definida) y, opcionalmente, el nombre de un almacenamiento dePIQ_STORAGE. Sin clave, el script se detiene de inmediato. - La plantilla.
$templatees el cuerpo del que parte cada solicitud: el texto de la plantilla comotemplateo, cuandoPIQ_STORAGEestá definida, dónde está guardada en su almacenamiento comosource.$valuesdaLyWpor nombre. Cada solicitud le añade lo suyo con+. postenvía un cuerpo a una operación como JSON, con la clave en el encabezadoX-API-KEY, y recoge los encabezados de la respuesta (por nombre en minúsculas) a medida que llegan. Devuelve el cuerpo y los encabezados.- Errores. Si una solicitud no pudo enviarse, se imprime el motivo. De una respuesta que no es correcta se imprime
el estado y después la descripción del problema: su
title, sudetaily cada entrada deerrors, el campo y qué está mal en él. Un401no tiene cuerpo, así que no hay nada más que imprimir; un cuerpo que no es JSON se imprime tal cual. Después, el script termina con1. - Inputs.
POST /inputssolo necesita la plantilla. Cada uno de susinputstiene unname,label,kindyvalue. - Measure.
POST /measurecon los valores da elwidthy elheightdel dibujo, y las longitudes de sus líneas por capa enlayers; la longitud de corte es la longitud en la capaCut. - Export.
POST /export/pdfresponde con el propio PDF, no con JSON: se escribe tal cual enbox.pdf. El encabezadoX-PiQ-Warningsindica cuántas cosas no pudieron exportarse tal cual. - Save (opcional). Con un almacenamiento,
POST /save/pdfexporta el mismo dibujo y lo guarda en su almacenamiento endestination;'overwrite' => truereemplaza un archivo que ya exista. Responde con dónde lo ha guardado y su tamaño.
Cómo ejecutarlo
Guarde el script como box.php. Necesita la extensión curl: php -m muestra curl cuando está disponible (en Debian
y Ubuntu es el paquete php-curl; en Windows, quite el comentario de extension=curl en php.ini). Después:
export PIQ_API_KEY=XXXX-XXXX-XXXX-XXXXX
php box.php
Imprime las variables etiquetadas de la plantilla, el tamaño del dibujo y su longitud de corte, y guarda 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)
Con un valor que la plantilla no puede usar (por ejemplo, "L": "long"), imprime el problema y se detiene:
Error 400
One or more validation errors occurred.
Some of the values given can't be used.
L: L is a number.
Con una clave incorrecta, solo imprime Error 401: un 401 no tiene
descripción del problema.
Para probar la parte del almacenamiento, registre un almacenamiento (consulte
Registrar un almacenamiento), coloque en él una plantilla como templates/box.piq y
establezca PIQ_STORAGE con el nombre del almacenamiento. La plantilla se lee entonces desde su almacenamiento, y el
PDF también se guarda en él como drawings/box.pdf, reemplazando cualquier archivo que ya exista.
Consulte también: API, Inputs, Measure, Exportar un dibujo, Guardar en su almacenamiento, Registrar un almacenamiento, Clientes.