Skip to main content

أمثلة برمجية

برمجة جاهزة للتعديل ترسل منتجاتك على دفعات من 100، وتنتظر بأدب حين يُطلب منها، وتُبلغ عن أي منتج لم يأخذه مزاد. احفظ مفتاحك في متغير بيئة اسمه MAZAD_KEY.

curl

bash
# 1. Who am I? (checks your key)
curl https://api.mazad.market/api/v1/developer/me \
  -H "Authorization: Bearer $MAZAD_KEY"

# 2. Send products (up to 100 at a time)
curl -X POST "https://api.mazad.market/api/v1/developer/products:bulk" \
  -H "Authorization: Bearer $MAZAD_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: sync-2026-11-28-page-1" \
  --data @products.json

# 3. See how the send went
curl https://api.mazad.market/api/v1/developer/batches/48213 \
  -H "Authorization: Bearer $MAZAD_KEY"

# 4. Change stock only
curl -X PATCH "https://api.mazad.market/api/v1/developer/products/stock:bulk" \
  -H "Authorization: Bearer $MAZAD_KEY" \
  -H "Content-Type: application/json" \
  -d '{"updates":[{"external_id":"SKU-1001","stock_quantity":12}]}'

PHP

php
<?php
// Mazad Developer — send products from your system (PHP 8+, no extra library).
$key  = getenv('MAZAD_KEY');
$base = 'https://api.mazad.market/api/v1/developer';

function mazad(string $method, string $path, ?array $body = null, array $headers = []): array
{
    global $key, $base;
    $ch = curl_init($base . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 60,
        CURLOPT_HTTPHEADER     => array_merge([
            'Authorization: Bearer ' . $key,
            'Accept: application/json',
            'Content-Type: application/json',
        ], $headers),
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
    }
    $raw    = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    return ['status' => $status, 'body' => json_decode((string) $raw, true)];
}

// Your products, in pages of 100.
$all = loadProductsFromYourDatabase(); // your own code
foreach (array_chunk($all, 100) as $i => $page) {
    $sent = mazad('POST', '/products:bulk', [
        'variants_are_complete' => true,
        'products' => $page,
    ], ['Idempotency-Key: sync-' . date('Y-m-d') . '-page-' . $i]);

    if ($sent['status'] === 429) {      // too fast: wait and try the same page again
        sleep(60);
        continue;
    }
    if ($sent['status'] !== 202) {
        error_log('Mazad refused page ' . $i . ': ' . json_encode($sent['body']));
        continue;
    }

    // Ask how it went (a few seconds later).
    do {
        sleep(3);
        $batch = mazad('GET', '/batches/' . $sent['body']['batch_id']);
    } while (in_array($batch['body']['status'] ?? '', ['queued', 'processing'], true));

    foreach ($batch['body']['failed'] ?? [] as $f) {
        error_log("Mazad could not take {$f['external_id']}: {$f['reason']}");
    }
}

JavaScript (Node.js)

javascript
// Mazad Developer — send products from your system (Node 18+, built-in fetch).
const KEY = process.env.MAZAD_KEY;
const BASE = "https://api.mazad.market/api/v1/developer";

async function mazad(method, path, body, headers = {}) {
  const res = await fetch(BASE + path, {
    method,
    headers: {
      Authorization: `Bearer ${KEY}`,
      Accept: "application/json",
      "Content-Type": "application/json",
      ...headers,
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  return { status: res.status, body: await res.json().catch(() => null) };
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function syncProducts(products) {
  for (let i = 0; i < products.length; i += 100) {
    const page = products.slice(i, i + 100);
    const sent = await mazad(
      "POST",
      "/products:bulk",
      { variants_are_complete: true, products: page },
      { "Idempotency-Key": `sync-${new Date().toISOString().slice(0, 10)}-${i}` },
    );

    if (sent.status === 429) { await sleep(60_000); i -= 100; continue; } // same page again
    if (sent.status !== 202) { console.error("Refused:", sent.body); continue; }

    let batch;
    do {
      await sleep(3000);
      batch = await mazad("GET", `/batches/${sent.body.batch_id}`);
    } while (["queued", "processing"].includes(batch.body?.status));

    for (const f of batch.body?.failed ?? []) {
      console.warn(`Mazad could not take ${f.external_id}: ${f.reason}`);
    }
  }
}

Python

python
# Mazad Developer — send products from your system (Python 3.9+, "requests").
import os, time, datetime
import requests

KEY = os.environ["MAZAD_KEY"]
BASE = "https://api.mazad.market/api/v1/developer"
session = requests.Session()
session.headers.update({"Authorization": f"Bearer {KEY}", "Accept": "application/json"})


def sync_products(products):
    today = datetime.date.today().isoformat()
    i = 0
    while i < len(products):
        page = products[i:i + 100]
        sent = session.post(
            f"{BASE}/products:bulk",
            json={"variants_are_complete": True, "products": page},
            headers={"Idempotency-Key": f"sync-{today}-{i}"},
            timeout=60,
        )
        if sent.status_code == 429:      # too fast: wait, then the same page again
            time.sleep(60)
            continue
        if sent.status_code != 202:
            print("Refused:", sent.json())
            i += 100
            continue

        batch_id = sent.json()["batch_id"]
        while True:
            time.sleep(3)
            batch = session.get(f"{BASE}/batches/{batch_id}", timeout=30).json()
            if batch["status"] not in ("queued", "processing"):
                break
        for f in batch.get("failed", []):
            print(f"Mazad could not take {f['external_id']}: {f['reason']}")
        i += 100
مزاد للمطورين مخصّص للبائعين المعتمدين في مزاد الذين يملكون نظامهم الخاص.مزاد ماركت