Częste scenariusze
Gotowe rozwiązania dla typowych zadań. Przykłady używają klientów PHP, Node.js i Python (jeden plik, do pobrania w sekcji „Gotowe rozwiązania”).
Klienci: PHP · Node.js · Python
Masowy zakup etykiet
Pętla po zamówieniach: taryfa, wybór najtańszej, zakup z kluczem idempotentnym z numeru zamówienia. Skrypt można bezpiecznie uruchamiać wielokrotnie: już zakupione zamówienia zwrócą się jako powtórka, a nie zostaną kupione ponownie. Przy 402 saldo się wyczerpało, przy 429 limit został przekroczony.
<?php
require __DIR__ . '/shippickup.php';
$api = new ShipPickup(); // key from the SHIPPICKUP_API_KEY environment variable
foreach ($orders as $id => $order) { // $id is your order number, $order is the API body: from, to, parcel, items, declared_value_cents
$request = ['from' => $order['from'], 'to' => $order['to'], 'parcel' => $order['parcel'], 'declared_value_cents' => $order['declared_value_cents']];
try {
$rate = $api->rates($request)['data'][0]; // sorted by price, the first is the cheapest
$shipment = $api->create($order + ['rate_id' => $rate['rate_id']], ShipPickup::idempotencyKey('order-' . $id));
echo $id, ' ', $shipment['data']['tracking_number'], "\n";
} catch (ShipPickupException $e) {
if ($e->status === 402) { break; } // top up the balance and run again, finished orders will not be repeated
if ($e->status === 429) { sleep(60); } // limit reached: wait and re-run
fwrite(STDERR, $id . ' ' . $e->errorCode . ': ' . $e->getMessage() . "\n");
}
}import time
from shippickup import ShipPickup, ShipPickupError
api = ShipPickup() # key from the SHIPPICKUP_API_KEY environment variable
for order_id, order in orders.items(): # order_id is your order number, order is the API body: from, to, parcel, items, declared_value_cents
request = {k: order[k] for k in ("from", "to", "parcel", "declared_value_cents")}
try:
rate = api.rates(request)["data"][0] # sorted by price, the first is the cheapest
shipment = api.create({**order, "rate_id": rate["rate_id"]}, ShipPickup.idempotency_key("order-" + str(order_id)))
print(order_id, shipment["data"]["tracking_number"])
except ShipPickupError as e:
if e.status == 402:
break # top up the balance and run again, finished orders will not be repeated
if e.status == 429:
time.sleep(60) # limit reached: wait and re-run
print(order_id, e.code, e)import { ShipPickup, ShipPickupError } from "./shippickup.js";
const api = new ShipPickup(); // key from the SHIPPICKUP_API_KEY environment variable
for (const [id, order] of Object.entries(orders)) { // id is your order number, order is the API body: from, to, parcel, items, declared_value_cents
const { from, to, parcel, declared_value_cents } = order;
try {
const rate = (await api.rates({ from, to, parcel, declared_value_cents })).data[0]; // the cheapest
const shipment = await api.create({ ...order, rate_id: rate.rate_id }, ShipPickup.idempotencyKey(`order-${id}`));
console.log(id, shipment.data.tracking_number);
} catch (e) {
if (!(e instanceof ShipPickupError)) throw e;
if (e.status === 402) break; // top up the balance and run again, finished orders will not be repeated
if (e.status === 429) await new Promise((r) => setTimeout(r, 60000)); // limit reached: wait and re-run
console.error(id, e.code, e.message);
}
}Przeliczenie taryfy
rate_id jest ważny 15 minut. Jeśli między wyliczeniem a zakupem minęło więcej czasu lub paczka się zmieniła, pojawi się 409 rate_expired. Pobierz taryfy ponownie i powtórz zakup z tym samym kluczem idempotentności, etykieta zostanie kupiona dokładnie raz.
<?php
// rate_id lives 15 minutes and works only for the same parcel and route. On 409 rate_expired ask for rates again.
try {
$shipment = $api->create($order + ['rate_id' => $rateId], $key);
} catch (ShipPickupException $e) {
if ($e->errorCode !== 'rate_expired') { throw $e; }
$rate = $api->rates($request)['data'][0];
$shipment = $api->create($order + ['rate_id' => $rate['rate_id']], $key); // the same key: still one order
}# rate_id lives 15 minutes and works only for the same parcel and route. On 409 rate_expired ask for rates again.
try:
shipment = api.create({**order, "rate_id": rate_id}, key)
except ShipPickupError as e:
if e.code != "rate_expired":
raise
rate = api.rates(request)["data"][0]
shipment = api.create({**order, "rate_id": rate["rate_id"]}, key) # the same key: still one order// rate_id lives 15 minutes and works only for the same parcel and route. On 409 rate_expired ask for rates again.
let shipment;
try {
shipment = await api.create({ ...order, rate_id: rateId }, key);
} catch (e) {
if (!(e instanceof ShipPickupError) || e.code !== "rate_expired") throw e;
const rate = (await api.rates(request)).data[0];
shipment = await api.create({ ...order, rate_id: rate.rate_id }, key); // the same key: still one order
}Anulowanie zamówienia
Pieniądze za anulowane zamówienie wracają na saldo, kwota w meta.refund_cents. Jeśli anulowanie nie jest już możliwe, pojawi się 409 z powodem.
<?php
$result = $api->cancel($orderId, 'Customer cancelled the order');
echo $result['meta']['refund_cents'], " cents returned to the balance\n"; // a repeated cancel is safe: meta.already_cancelled = trueresult = api.cancel(order_id, "Customer cancelled the order")
print(result["meta"]["refund_cents"], "cents returned to the balance") # a repeated cancel is safe: meta.already_cancelled = trueconst result = await api.cancel(orderId, "Customer cancelled the order");
console.log(result.meta.refund_cents, "cents returned to the balance"); // a repeated cancel is safe: meta.already_cancelled = trueStatusy bez webhooków
Jeśli webhook nie pasuje, sprawdzaj GET /shipments/{id}/tracking dla otwartych zamówień nie częściej niż co kilka godzin i pamiętaj o limicie zapytań.
Odbiór przez kuriera
Procedura jest następująca: GET /shipments/{id}/pickup_slots, wybierz okno, POST /shipments/{id}/pickup z slot_id. Koszt odbioru podany jest w meta.fee_cents pierwszej odpowiedzi. Anulować odbiór można metodą pickup/cancel.