> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oneclickdz.com/llms.txt
> Use this file to discover all available pages before exploring further.

# تقديم الطلبات

> تقديم طلبات بطاقات الهدايا بعد التحقق من المخزون والرصيد

<div dir="rtl">
  ## نظرة عامة

  بعد التحقق من توفر المنتج، قدّم طلب بطاقة الهدية عبر endpoint الطلب. يستدعي الطلب الناجح إرجاع معرّف الطلب الذي ستستخدمه لتتبع الحالة.

  <Warning>
    **تحقق دائماً من المخزون والرصيد** قبل تقديم الطلب لتجنب الأخطاء.
  </Warning>

  ## مرجع API

  <Card title="POST /v3/gift-cards/placeOrder" icon="cart-shopping" href="/ar/api-reference/gift-cards/placeOrder">
    التوثيق الكامل للـ endpoint
  </Card>

  ## تقديم طلب أساسي

  <CodeGroup>
    ```javascript Node.js theme={null}
    async function placeOrder(orderData) {
      const response = await fetch(
        "https://api.oneclickdz.com/v3/gift-cards/placeOrder",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-Access-Token": process.env.API_KEY,
          },
          body: JSON.stringify({
            productId: orderData.productId,
            typeId: orderData.typeId,
            ref: orderData.ref,
          }),
        }
      );

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error?.message || `HTTP ${response.status}`);
      }

      const result = await response.json();
      return result.data;
    }

    // Usage
    const order = await placeOrder({
      productId: "507f1f77bcf86cd799439011",
      typeId: "type_10",
      ref: `order-${Date.now()}`
    });

    console.log('Order placed:', order.orderId);
    ```

    ```python Python theme={null}
    import requests
    import os
    import time

    def place_order(order_data):
        response = requests.post(
            'https://api.oneclickdz.com/v3/gift-cards/placeOrder',
            headers={
                'Content-Type': 'application/json',
                'X-Access-Token': os.getenv('API_KEY')
            },
            json={
                'productId': order_data['productId'],
                'typeId': order_data['typeId'],
                'ref': order_data['ref']
            }
        )

        if not response.ok:
            error = response.json()
            raise Exception(error.get('error', {}).get('message', f'HTTP {response.status_code}'))

        return response.json()['data']

    # Usage
    order = place_order({
        'productId': '507f1f77bcf86cd799439011',
        'typeId': 'type_10',
        'ref': f'order-{int(time.time() * 1000)}'
    })

    print(f'Order placed: {order["orderId"]}')
    ```

    ```php PHP theme={null}
    <?php

    function placeOrder($orderData, $apiKey) {
        $data = [
            'productId' => $orderData['productId'],
            'typeId' => $orderData['typeId'],
            'ref' => $orderData['ref']
        ];

        $ch = curl_init('https://api.oneclickdz.com/v3/gift-cards/placeOrder');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'X-Access-Token: ' . $apiKey
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 400) {
            $error = json_decode($response, true);
            throw new Exception($error['error']['message'] ?? "HTTP {$httpCode}");
        }

        $result = json_decode($response, true);
        return $result['data'];
    }

    // Usage
    $order = placeOrder([
        'productId' => '507f1f77bcf86cd799439011',
        'typeId' => 'type_10',
        'ref' => 'order-' . (int)(microtime(true) * 1000)
    ], getenv('API_KEY'));

    echo "Order placed: {$order['orderId']}\n";
    ?>
    ```

    ```bash cURL theme={null}
    curl https://api.oneclickdz.com/v3/gift-cards/placeOrder \
      -X POST \
      -H "Content-Type: application/json" \
      -H "X-Access-Token: YOUR_API_KEY" \
      -d '{
        "productId": "507f1f77bcf86cd799439011",
        "typeId": "type_10",
        "ref": "order-123456"
      }'
    ```
  </CodeGroup>

  ## مثال على الاستجابة

  ```json theme={null}
  {
    "success": true,
    "data": {
      "orderId": "6901616fe9e88196b4eb64b2",
      "orderRef": "order-123456"
    },
    "meta": {
      "timestamp": "2025-11-01T12:00:00.000Z"
    }
  }
  ```

  ## معالجة الأخطاء

  <CodeGroup>
    ```python Python theme={null}
    try:
        order_id = place_order(product_id, type_id, quantity)
        print(f"Success: {order_id}")
    except Exception as error:
        if 'stock' in str(error):
            print("Out of stock")
        elif 'balance' in str(error):
            print("Insufficient balance")
        else:
            print(f"Order failed: {error}")
    ```

    ```php PHP theme={null}
    <?php
    try {
        $orderId = placeOrder($productId, $typeId, $quantity, $apiKey);
        echo "Success: {$orderId}\n";
    } catch (Exception $error) {
        $errorMsg = strtolower($error->getMessage());

        if (strpos($errorMsg, 'stock') !== false) {
            echo "Out of stock\n";
        } elseif (strpos($errorMsg, 'balance') !== false) {
            echo "Insufficient balance\n";
        } else {
            echo "Order failed: " . $error->getMessage() . "\n";
        }
    }
    ?>
    ```

    ```javascript Node.js theme={null}
    try {
      const orderId = await placeOrder(productId, typeId, quantity);
      console.log(`Success: ${orderId}`);
    } catch (error) {
      const errorMsg = error.message.toLowerCase();

      if (errorMsg.includes("stock")) {
        console.log("Out of stock");
      } else if (errorMsg.includes("balance")) {
        console.log("Insufficient balance");
      } else {
        console.log(`Order failed: ${error.message}`);
      }
    }
    ```
  </CodeGroup>

  ## أفضل الممارسات

  <CardGroup cols={2}>
    <Card title="التحقق أولاً" icon="check">
      تحقق دائماً من المخزون والرصيد قبل تقديم أي طلب
    </Card>

    <Card title="مرجعيات فريدة" icon="fingerprint">
      أنشئ `ref` فريداً لكل طلب لتجنب التكرار
    </Card>

    <Card title="تخزين orderId" icon="database">
      احفظ `orderId` فوراً في قاعدة البيانات بعد نجاح الطلب
    </Card>

    <Card title="بدء الاستعلام" icon="arrows-rotate">
      ابدأ استعلام الحالة فور تقديم الطلب بنجاح
    </Card>
  </CardGroup>

  ## الخطوات التالية

  <CardGroup cols={3}>
    <Card title="تتبع الحالة" icon="chart-line" href="/ar/gift-card-guides/4-status-tracking">
      استعلام حالة الطلب حتى اكتماله
    </Card>

    <Card title="التسليم الآمن" icon="shield" href="/ar/gift-card-guides/5-secure-delivery">
      تسليم البطاقات بأمان للعملاء
    </Card>

    <Card title="مرجع API" icon="book" href="/ar/api-reference/gift-cards/placeOrder">
      التوثيق الكامل للـ endpoint
    </Card>
  </CardGroup>
</div>
