> ## 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.

# الخطوة 4: أفضل الممارسات

> الأمان الأساسي ومعالجة الأخطاء للإنتاج

<div dir="rtl">
  ## الأمان

  ### 1. احمِ مفاتيح API الخاصة بك

  <Warning>
    **لا تكشف أبداً** عن مفاتيح API في كود frontend أو المستودعات العامة!
  </Warning>

  ```bash theme={null}
  # .env file (add to .gitignore)
  ONECLICK_API_KEY=your_key_here
  ```

  <CodeGroup>
    ```javascript Node.js theme={null}
    const apiKey = process.env.ONECLICK_API_KEY;
    ```

    ```python Python theme={null}
    import os
    api_key = os.getenv('ONECLICK_API_KEY')
    ```

    ```php PHP theme={null}
    <?php
    $apiKey = getenv('ONECLICK_API_KEY');
    ?>
    ```
  </CodeGroup>

  ### 2. Backend فقط

  استدعِ دائماً API Navio من backend، ولا تفعل ذلك أبداً من frontend:

  ```javascript theme={null}
  // ❌ WRONG - Frontend
  fetch("https://api.oneclickdz.com/v3/ocpay/createLink", {
    headers: { "X-Access-Token": "YOUR_KEY" }, // Exposed to users!
  });

  // ✅ CORRECT - Backend
  // Frontend calls YOUR API, your backend calls OneClick
  fetch("/api/create-payment", { method: "POST" });
  ```

  ### 3. تحقق من المدخلات

  ```javascript theme={null}
  function validateOrderData(data) {
    if (!Number.isInteger(data.amount)) {
      throw new Error("Amount must be integer");
    }

    if (data.amount < 500 || data.amount > 500000) {
      throw new Error("Amount must be between 500 and 500,000 DZD");
    }

    if (!data.title || data.title.trim().length === 0) {
      throw new Error("Title is required");
    }

    return data;
  }
  ```

  ### 4. تحقق قبل التنفيذ

  <Warning>
    تحقق دائماً من حالة الدفع في backend قبل تنفيذ الطلبات!
  </Warning>

  ```javascript theme={null}
  async function fulfillOrder(orderId) {
    const order = await db.orders.findOne({ id: orderId });

    // CRITICAL: Verify payment status
    const response = await fetch(
      `https://api.oneclickdz.com/v3/ocpay/checkPayment/${order.paymentRef}`,
      {
        headers: { "X-Access-Token": process.env.ONECLICK_API_KEY },
      }
    );

    const data = await response.json();

    if (data.data.status !== "CONFIRMED") {
      throw new Error("Payment not confirmed");
    }

    // Safe to fulfill
    await processOrder(order);
  }
  ```

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

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

  <CodeGroup>
    ```javascript Node.js theme={null}
    async function createPaymentSafe(orderId, amount, title) {
      try {
        const response = await fetch(
          "https://api.oneclickdz.com/v3/ocpay/createLink",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-Access-Token": process.env.ONECLICK_API_KEY,
            },
            body: JSON.stringify({
              productInfo: { title, amount },
            }),
          }
        );

        if (!response.ok) {
          if (response.status === 403) {
            throw new Error("Merchant not validated");
          }
          throw new Error("API request failed");
        }

        const data = await response.json();

        if (!data.success) {
          throw new Error(data.error?.message || "Unknown error");
        }

        return data.data;
      } catch (error) {
        console.error("Payment creation failed:", error);
        throw error;
      }
    }
    ```

    ```python Python theme={null}
    def create_payment_safe(order_id, amount, title):
        try:
            response = requests.post(
                'https://api.oneclickdz.com/v3/ocpay/createLink',
                headers={
                    'Content-Type': 'application/json',
                    'X-Access-Token': os.getenv('ONECLICK_API_KEY')
                },
                json={
                    'productInfo': {'title': title, 'amount': amount}
                }
            )

            if response.status_code == 403:
                raise Exception('Merchant not validated')

            response.raise_for_status()

            data = response.json()

            if not data['success']:
                raise Exception(data['error'].get('message', 'Unknown error'))

            return data['data']

        except Exception as e:
            print(f'Payment creation failed: {e}')
            raise
    ```

    ```php PHP theme={null}
    <?php
    function createPaymentSafe($orderId, $amount, $title) {
        try {
            $ch = curl_init('https://api.oneclickdz.com/v3/ocpay/createLink');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'X-Access-Token: ' . getenv('ONECLICK_API_KEY')
            ]);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
                'productInfo' => ['title' => $title, 'amount' => $amount]
            ]));

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

            if ($httpCode === 403) {
                throw new Exception('Merchant not validated');
            }

            if ($httpCode !== 200) {
                throw new Exception('API request failed');
            }

            $data = json_decode($response, true);

            if (!$data['success']) {
                throw new Exception($data['error']['message'] ?? 'Unknown error');
            }

            return $data['data'];

        } catch (Exception $e) {
            error_log('Payment creation failed: ' . $e->getMessage());
            throw $e;
        }
    }
    ?>
    ```
  </CodeGroup>

  ## الاختبار

  ### استخدم Sandbox

  اختبر بمفاتيح sandbox قبل الإنتاج:

  ```bash theme={null}
  # Development
  ONECLICK_API_KEY=sk_sandbox_abc123...

  # Production
  ONECLICK_API_KEY=sk_live_xyz789...
  ```

  ### سيناريوهات الاختبار

  اختبر هذه الحالات:

  * ✅ دفع ناجح
  * ✅ دفع فاشل
  * ✅ انتهاء صلاحية رابط الدفع (20 دقيقة)
  * ✅ العميل يعود دون دفع
  * ✅ أخطاء API

  ## قائمة تحقق الإنتاج

  **قبل الإطلاق:**

  ### الأمان

  * [ ] مفاتيح API في متغيرات البيئة
  * [ ] لا استدعاءات API من frontend
  * [ ] التحقق من المدخلات منفَّذ
  * [ ] HTTPS مُفعَّل

  ### الوظائف

  * [ ] إنشاء الطلب يعمل
  * [ ] روابط الدفع تُولَّد بشكل صحيح
  * [ ] التحقق من الحالة يعمل
  * [ ] تنفيذ الطلبات فقط عند CONFIRMED
  * [ ] مهمة cron تعمل

  ### الاختبار

  * [ ] اختبار sandbox مكتمل
  * [ ] جميع الحالات الحدية مختبرة
  * [ ] معالجة الأخطاء مُتحقَّق منها

  ### المراقبة

  * [ ] تسجيل الأخطاء مُفعَّل
  * [ ] إمكانية عرض الطلبات المعلقة
  * [ ] إمكانية التحقق اليدوي من الحالة

  ## الأخطاء الشائعة

  <Warning>
    **تجنّب هذه الأخطاء:**

    * ❌ ترميز مفاتيح API مباشرةً في الكود
    * ❌ استدعاء API من frontend
    * ❌ عدم حفظ paymentRef
    * ❌ التنفيذ دون التحقق
    * ❌ غياب معالجة الأخطاء
    * ❌ التحقق بتكرار مفرط (احترم حدود معدل الطلبات)
    * ❌ عدم الاختبار في sandbox أولاً
  </Warning>

  ## أفضل ممارسات قاعدة البيانات

  أضف فهارس لتحسين الأداء:

  ```sql theme={null}
  -- Speed up pending order queries
  CREATE INDEX idx_orders_pending
  ON orders(status, payment_ref)
  WHERE status = 'PENDING';

  -- Speed up paymentRef lookups
  CREATE INDEX idx_payment_ref ON orders(payment_ref);
  ```

  ## التسجيل

  سجّل الأحداث المهمة:

  ```javascript theme={null}
  // Log payment creation
  console.log("[Payment] Created", {
    orderId,
    paymentRef,
    amount,
    timestamp: new Date(),
  });

  // Log status changes
  console.log("[Payment] Status changed", {
    orderId,
    oldStatus: "PENDING",
    newStatus: "PAID",
    timestamp: new Date(),
  });
  ```

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

  <CardGroup cols={2}>
    <Card title="مرجع API" icon="book" href="/ar/api-reference/ocpay/create-link">
      توثيق API الكامل
    </Card>

    <Card title="التواصل مع الدعم" icon="headset" href="/ar/contact">
      احصل على مساعدة فريقنا
    </Card>

    <Card title="لوحة التحكم" icon="gauge" href="https://app.oneclickdz.com">
      راقب مدفوعاتك
    </Card>

    <Card title="دليل الأمان" icon="shield" href="/ar/security-best-practices">
      ممارسات أمان متقدمة
    </Card>
  </CardGroup>

  ## أنت جاهز! 🎉

  أصبح لديك الآن كل ما تحتاجه لقبول المدفوعات عبر Navio. ابدأ بالـ sandbox، اختبر بدقة، ثم انشر في الإنتاج!
</div>
