İçeriğe geç
SiparişTakip ana sayfa

Örnekler: curl, PHP ve Node.js

Token alma, Idempotency-Key ile gönderi oluşturma ve değişen gönderileri cursor ile çekme; curl, PHP ve Node.js örnekleri.

Güncelleme:

Üç örnek aynı akışı izler: token alır, Idempotency-Key ile bir gönderi oluşturur, değişen gönderileri cursor ile çeker. Örneklerdeki CLIENT_ID, CLIENT_SECRET ve hesap kimliği yerine kendi değerlerinizi yazın. Denemeyi test kargo hesabıyla yapın (Test ortamı).

curl

# 1) Token
TOKEN=$(curl -s -X POST https://api.siparistakip.com/oauth/token \
  -d grant_type=client_credentials \
  -d client_id=CLIENT_ID \
  -d client_secret=CLIENT_SECRET \
  -d "scope=shipments:read shipments:write" | jq -r .access_token)

# 2) Gönderi
curl -s -X POST https://api.siparistakip.com/api/v3/shipments \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "reference": "TEST-1001",
    "carrier": "ptt",
    "carrier_account_id": 7,
    "recipient": {"name": "Ayşe Yılmaz", "phone": "5321234567",
                  "address_line": "Atatürk Cad. No: 10 D: 3", "district": "Altındağ", "city": "Ankara"},
    "parcels": [{"weight_grams": 1500, "quantity": 1}]
  }'

# 3) Son bir saatte değişen gönderiler
curl -s -G https://api.siparistakip.com/api/v3/shipments \
  -H "Authorization: Bearer $TOKEN" \
  --data-urlencode "updated_since=$(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%SZ)" \
  --data-urlencode "limit=100"

PHP

Ek paket gerektirmez (cURL eklentisi yeter).

<?php

const API = 'https://api.siparistakip.com';

function request(string $method, string $url, array $headers = [], ?string $body = null): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    return [$status, json_decode((string) $response, true)];
}

// 1) Token: süresi dolana kadar saklayıp yeniden kullanın.
[$status, $token] = request('POST', API.'/oauth/token', ['Content-Type: application/x-www-form-urlencoded'], http_build_query([
    'grant_type' => 'client_credentials',
    'client_id' => 'CLIENT_ID',
    'client_secret' => 'CLIENT_SECRET',
    'scope' => 'shipments:read shipments:write',
]));
$auth = 'Authorization: Bearer '.$token['access_token'];

// 2) Gönderi. Anahtarı ilk denemede üretip siparişle saklayın; ağ hatasından sonraki tekrar aynı anahtarla yapılır.
$idempotencyKey = bin2hex(random_bytes(16));
[$status, $body] = request('POST', API.'/api/v3/shipments', [$auth, 'Content-Type: application/json', 'Idempotency-Key: '.$idempotencyKey], json_encode([
    'reference' => 'TEST-1001',
    'carrier' => 'ptt',
    'carrier_account_id' => 7,
    'recipient' => [
        'name' => 'Ayşe Yılmaz',
        'phone' => '5321234567',
        'address_line' => 'Atatürk Cad. No: 10 D: 3',
        'district' => 'Altındağ',
        'city' => 'Ankara',
    ],
    'parcels' => [['weight_grams' => 1500, 'quantity' => 1]],
]));

if ($status === 202) {
    $shipmentId = $body['data']['id'];
} elseif ($status === 409 && $body['code'] === 'reference_in_use') {
    $shipmentId = $body['shipment_id'];
} else {
    throw new RuntimeException($body['code'].': '.($body['detail'] ?? ''));
}

// 3) Değişen gönderiler: cursor'ı kalıcı olarak saklayın (ör. veritabanında).
$cursor = null;
do {
    $query = $cursor ? ['cursor' => $cursor] : ['updated_since' => gmdate('Y-m-d\TH:i:s\Z', time() - 3600)];
    [$status, $page] = request('GET', API.'/api/v3/shipments?'.http_build_query($query + ['limit' => 100]), [$auth]);
    foreach ($page['data'] as $shipment) {
        // $shipment['reference'], $shipment['state'], $shipment['tracking_number'] …
    }
    // next_cursor son sayfada da doludur: saklayın, sonraki çağrı (ör. 5 dk sonra) buradan devam eder.
    $cursor = $page['meta']['next_cursor'];
} while ($page['meta']['has_more']);

Node.js

Node.js 18 ve üstünde ek paket gerekmez (yerleşik fetch).

import { randomUUID } from "node:crypto";

const API = "https://api.siparistakip.com";

// 1) Token
const tokenRes = await fetch(`${API}/oauth/token`, {
  method: "POST",
  body: new URLSearchParams({
    grant_type: "client_credentials",
    client_id: "CLIENT_ID",
    client_secret: "CLIENT_SECRET",
    scope: "shipments:read shipments:write",
  }),
});
const { access_token: token } = await tokenRes.json();
const auth = { Authorization: `Bearer ${token}` };

// 2) Gönderi
const res = await fetch(`${API}/api/v3/shipments`, {
  method: "POST",
  headers: { ...auth, "Content-Type": "application/json", "Idempotency-Key": randomUUID() },
  body: JSON.stringify({
    reference: "TEST-1001",
    carrier: "ptt",
    carrier_account_id: 7,
    recipient: {
      name: "Ayşe Yılmaz",
      phone: "5321234567",
      address_line: "Atatürk Cad. No: 10 D: 3",
      district: "Altındağ",
      city: "Ankara",
    },
    parcels: [{ weight_grams: 1500, quantity: 1 }],
  }),
});
const body = await res.json();
if (res.status !== 202) throw new Error(`${body.code}: ${body.detail ?? ""}`);

// 3) Değişen gönderiler
let cursor = null;
let page;
do {
  const query = new URLSearchParams(
    cursor ? { cursor, limit: "100" } : { updated_since: new Date(Date.now() - 3600_000).toISOString(), limit: "100" },
  );
  page = await (await fetch(`${API}/api/v3/shipments?${query}`, { headers: auth })).json();
  for (const shipment of page.data) {
    // shipment.reference, shipment.state, shipment.tracking_number …
  }
  // next_cursor son sayfada da doludur: saklayın, sonraki çağrı (ör. 5 dk sonra) buradan devam eder.
  cursor = page.meta.next_cursor;
} while (page.meta.has_more);

Gerçek bir entegrasyonda token'ı süresi dolana kadar saklayın. 429'da Retry-After kadar, 5xx'te bir süre bekleyip aynı Idempotency-Key ile tekrar deneyin (Hatalar ve sınırlar).

Kargo entegrasyonunuzu bugün kurun

Ücretsiz paketle başlayın, kart bilgisi istemiyoruz. Kargo hesabınızı bağlayın, ilk gönderinizi oluşturun.

Fiyatları görÜcretsiz başla