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

# تكامل SDK Python

> دليل الإعداد السريع لـ SDK Navio Python

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

  يوفر SDK Navio Python واجهة نظيفة وأصيلة لدمج مدفوعات Navio في تطبيقات Python الخاصة بك. مبني باستخدام تلميحات أنواع Python 3.8+ وdataclasses لأفضل تجربة للمطورين.

  <CardGroup cols={2}>
    <Card title="API أصيل بـ Python" icon="code" color="#0D9373">
      واجهة نظيفة مع تلميحات أنواع كاملة وdataclasses
    </Card>

    <Card title="آمن من حيث الأنواع" icon="shield-check" color="#0D9373">
      تعليقات توضيحية كاملة مع dataclasses وenums
    </Card>

    <Card title="التحقق من المدخلات" icon="circle-check" color="#0D9373">
      التحقق من جانب العميل للحصول على تغذية راجعة سريعة للأخطاء
    </Card>

    <Card title="اعتمادات محدودة" icon="box" color="#0D9373">
      يتطلب فقط حزمة `requests`
    </Card>
  </CardGroup>

  ## المتطلبات

  * Python 3.8 أو أحدث
  * pip

  ## التثبيت

  قم بالتثبيت عبر pip:

  ```bash theme={null}
  pip install ocpay-python-sdk
  ```

  أو قم بالتثبيت من المصدر:

  ```bash theme={null}
  git clone https://github.com/oneclickdz/ocpay-python-sdk.git
  cd ocpay-python-sdk
  pip install -e .
  ```

  ## البدء السريع

  ### 1. تهيئة SDK

  ```python theme={null}
  from ocpay import OCPay

  ocpay = OCPay("your-api-access-token")
  ```

  <Warning>
    خزّن مفتاح API الخاص بك في متغيرات البيئة، ولا تضعه مباشرة في الكود المصدري.
  </Warning>

  ### 2. إنشاء رابط دفع

  ```python theme={null}
  from ocpay import OCPay, FeeMode
  from ocpay.types import ProductInfo, CreateLinkRequest

  ocpay = OCPay("your-api-key")

  request = CreateLinkRequest(
      product_info=ProductInfo(
          title="Premium Subscription",
          amount=5000,  # Amount in DZD (500–500,000)
          description="Monthly access to all premium features",
      ),
      fee_mode=FeeMode.NO_FEE,
      success_message="Thank you for your purchase!",
      redirect_url="https://yourstore.com/success?orderId=12345",
  )

  response = ocpay.create_link(request)

  # Share this URL with your customer
  print("Payment URL:", response.payment_url)

  # Save this reference for tracking
  print("Payment Reference:", response.payment_ref)
  ```

  ### 3. التحقق من حالة الدفع

  ```python theme={null}
  from ocpay import OCPay

  ocpay = OCPay("your-api-key")

  status = ocpay.check_payment("OCPL-A1B2C3-D4E5")

  if status.is_confirmed():
      print("Payment confirmed!")
      if status.transaction_details:
          print(f"Amount: {status.transaction_details.amount} DZD")
  elif status.is_pending():
      print("Payment still pending...")
  elif status.is_failed():
      print(f"Payment failed: {status.message}")
  ```

  ## مثال تجارة إلكترونية كامل

  <Accordion title="تدفق طلب تجارة إلكترونية كامل">
    ```python theme={null}
    from ocpay import (
        OCPay,
        FeeMode,
        ValidationException,
        ApiException,
    )
    from ocpay.types import ProductInfo, CreateLinkRequest

    # Initialize SDK
    ocpay = OCPay("your-api-key")

    # Step 1: Create payment link for your order
    order_id = "ORD-12345"
    response = ocpay.create_link(CreateLinkRequest(
        product_info=ProductInfo(
            title=f"Order #{order_id}",
            amount=8000,
            description=f"Payment for order #{order_id}",
        ),
        fee_mode=FeeMode.NO_FEE,
        success_message=f"Thank you! Your order #{order_id} is being processed.",
        redirect_url=f"https://yourstore.com/orders/{order_id}/success",
    ))

    # Step 2: Save payment reference to your database
    print(f"Payment URL: {response.payment_url}")
    print(f"Payment Ref: {response.payment_ref}")

    # Step 3: Check payment status (in webhook or polling job)
    status = ocpay.check_payment(response.payment_ref)

    if status.is_confirmed():
        print("✅ Payment confirmed - fulfilling order")
    elif status.is_failed():
        print("❌ Payment failed")
    else:
        print("⏳ Payment is pending")
    ```
  </Accordion>

  ## مرجع API

  ### فئة Navio

  نقطة الدخول الرئيسية لـ SDK.

  #### المنشئ

  ```python theme={null}
  OCPay(access_token: str, options: ClientOptions = None)
  ```

  <ParamField body="access_token" type="string" required>
    رمز الوصول إلى API OneClickDz الخاص بك.
  </ParamField>

  <ParamField body="options" type="ClientOptions">
    إعداد اختياري للعميل.

    <Expandable title="خصائص ClientOptions">
      <ParamField body="timeout" type="int">
        مهلة الطلب بالثواني. الافتراضي: `30`.
      </ParamField>

      <ParamField body="base_url" type="string">
        URL أساسي مخصص، يُستخدم بشكل رئيسي للاختبار.
      </ParamField>

      <ParamField body="headers" type="dict">
        رؤوس إضافية لتضمينها في كل طلب.
      </ParamField>
    </Expandable>
  </ParamField>

  **مثال:**

  ```python theme={null}
  from ocpay import OCPay, ClientOptions

  ocpay = OCPay("your-api-key", options=ClientOptions(timeout=60))
  ```

  #### `create_link(request)`

  ينشئ رابط دفع جديداً.

  <ParamField body="request" type="CreateLinkRequest" required>
    طلب إنشاء رابط الدفع.

    <Expandable title="خصائص CreateLinkRequest">
      <ParamField body="product_info" type="ProductInfo" required>
        معلومات المنتج.

        <Expandable title="خصائص ProductInfo">
          <ParamField body="title" type="string" required>
            اسم المنتج أو الخدمة (1–200 حرف).
          </ParamField>

          <ParamField body="amount" type="int" required>
            المبلغ بالدينار الجزائري (500–500,000). يجب أن يكون عدداً صحيحاً.
          </ParamField>

          <ParamField body="description" type="string">
            وصف اختياري للمنتج (حد أقصى 1000 حرف).
          </ParamField>
        </Expandable>
      </ParamField>

      <ParamField body="fee_mode" type="FeeMode">
        من يدفع رسوم المعاملات. الافتراضي: `FeeMode.NO_FEE`.
      </ParamField>

      <ParamField body="success_message" type="string">
        رسالة اختيارية تُعرض للعميل بعد الدفع (حد أقصى 500 حرف).
      </ParamField>

      <ParamField body="redirect_url" type="string">
        URL اختياري لإعادة توجيه العميل بعد اكتمال الدفع.
      </ParamField>
    </Expandable>
  </ParamField>

  **يُرجع:**

  <ResponseField name="payment_url" type="string">
    URL صفحة الدفع لمشاركتها مع عميلك.
  </ResponseField>

  <ResponseField name="payment_ref" type="string">
    كود مرجعي فريد للدفع (مثال: `OCPL-A1B2C3-D4E5`). احفظه لتتبع حالة الدفع.
  </ResponseField>

  **يرفع:** `ValidationException` (400)، `UnauthorizedException` (403)، `ApiException`

  #### `check_payment(payment_ref)`

  يتحقق من حالة دفع.

  <ParamField body="payment_ref" type="string" required>
    كود مرجعي للدفع تم إرجاعه بواسطة `create_link` (مثال: `"OCPL-A1B2C3-D4E5"`).
  </ParamField>

  **يُرجع:**

  <ResponseField name="status" type="PaymentStatus">
    حالة الدفع الحالية: `PENDING` أو `CONFIRMED` أو `FAILED`.
  </ResponseField>

  <ResponseField name="message" type="string">
    رسالة حالة مقروءة للإنسان.
  </ResponseField>

  <ResponseField name="transaction_details" type="TransactionDetails">
    تفاصيل المعاملة المؤكدة. موجود فقط عندما يكون `status` هو `CONFIRMED`.
  </ResponseField>

  **يرفع:** `NotFoundException` (404)، `PaymentExpiredException` (410)، `ApiException`

  ### Enums

  #### FeeMode

  | القيمة                 | الوصف                                 |
  | ---------------------- | ------------------------------------- |
  | `FeeMode.NO_FEE`       | التاجر يدفع جميع الرسوم (الافتراضي)   |
  | `FeeMode.SPLIT_FEE`    | الرسوم مقسمة 50/50 بين التاجر والعميل |
  | `FeeMode.CUSTOMER_FEE` | العميل يدفع جميع الرسوم               |

  #### PaymentStatus

  | القيمة                    | الوصف                                      |
  | ------------------------- | ------------------------------------------ |
  | `PaymentStatus.PENDING`   | الدفع قيد التنفيذ                          |
  | `PaymentStatus.CONFIRMED` | اكتمل الدفع بنجاح                          |
  | `PaymentStatus.FAILED`    | تم رفض الدفع أو انتهت صلاحيته أو تم إلغاؤه |

  ### فئات الاستثناء

  <AccordionGroup>
    <Accordion title="ValidationException - HTTP 400">
      تُطلق عندما تكون بيانات الطلب غير صالحة (مثال: مبلغ خارج النطاق، حقول مطلوبة مفقودة).

      **الخصائص:** `message`، `status_code`، `request_id`، `error_data`
    </Accordion>

    <Accordion title="UnauthorizedException - HTTP 403">
      تُطلق عند فشل المصادقة. تحقق من أن مفتاح API الخاص بك صالح ونشط.

      **الخصائص:** `message`، `status_code`، `request_id`، `error_data`
    </Accordion>

    <Accordion title="NotFoundException - HTTP 404">
      تُطلق عندما لا يوجد مرجع الدفع.

      **الخصائص:** `message`، `status_code`، `request_id`، `error_data`
    </Accordion>

    <Accordion title="PaymentExpiredException - HTTP 410">
      تُطلق عند انتهاء صلاحية رابط الدفع. تنتهي صلاحية الروابط بعد 20 دقيقة من الإنشاء.

      **الخصائص:** `message`، `status_code`، `request_id`، `error_data`
    </Accordion>

    <Accordion title="ApiException - متنوعة">
      الاستثناء الأساسي لجميع أخطاء API الأخرى. التقطه كخيار احتياطي.

      **الخصائص:** `message`، `status_code`، `request_id`، `error_data`
    </Accordion>
  </AccordionGroup>

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

  ```python theme={null}
  from ocpay import (
      OCPay,
      ApiException,
      ValidationException,
      UnauthorizedException,
      NotFoundException,
      PaymentExpiredException,
  )

  ocpay = OCPay("your-api-key")

  try:
      response = ocpay.create_link(request)
  except ValidationException as e:
      print(f"Validation error: {e.message}")
      print(f"Request ID: {e.request_id}")
  except UnauthorizedException as e:
      print("Authentication failed. Check your API key.")
  except NotFoundException as e:
      print(f"Not found: {e.message}")
  except PaymentExpiredException as e:
      print(f"Payment expired: {e.message}")
  except ApiException as e:
      print(f"API error: {e.message} (status {e.status_code})")
      print(f"Request ID: {e.request_id}")
  ```

  ## التكامل مع الأطر

  <Tabs>
    <Tab title="Flask">
      ```python theme={null}
      from flask import Flask, jsonify, request
      from ocpay import OCPay, FeeMode
      from ocpay.types import CreateLinkRequest, ProductInfo

      app = Flask(__name__)
      ocpay = OCPay("your-api-key")

      @app.route("/api/payment", methods=["POST"])
      def create_payment():
          data = request.json
          response = ocpay.create_link(CreateLinkRequest(
              product_info=ProductInfo(
                  title=data["title"],
                  amount=data["amount"],
              ),
              fee_mode=FeeMode.NO_FEE,
          ))
          return jsonify({
              "payment_url": response.payment_url,
              "payment_ref": response.payment_ref,
          })
      ```
    </Tab>

    <Tab title="Django">
      ```python theme={null}
      from ocpay import OCPay, FeeMode
      from ocpay.types import CreateLinkRequest, ProductInfo

      ocpay = OCPay(settings.OCPAY_API_KEY)

      def create_order_payment(order):
          response = ocpay.create_link(CreateLinkRequest(
              product_info=ProductInfo(
                  title=f"Order #{order.id}",
                  amount=order.total,
              ),
              fee_mode=FeeMode.NO_FEE,
              redirect_url=f"https://yourstore.com/orders/{order.id}/success",
          ))
          order.payment_ref = response.payment_ref
          order.save()
          return response.payment_url
      ```
    </Tab>

    <Tab title="FastAPI">
      ```python theme={null}
      from fastapi import FastAPI
      from ocpay import OCPay, FeeMode
      from ocpay.types import CreateLinkRequest, ProductInfo

      app = FastAPI()
      ocpay = OCPay("your-api-key")

      @app.post("/api/payment")
      async def create_payment(title: str, amount: int):
          response = ocpay.create_link(CreateLinkRequest(
              product_info=ProductInfo(title=title, amount=amount),
              fee_mode=FeeMode.NO_FEE,
          ))
          return {
              "payment_url": response.payment_url,
              "payment_ref": response.payment_ref,
          }
      ```
    </Tab>
  </Tabs>

  ## ملاحظات مهمة

  <Warning>
    **التحقق من التاجر مطلوب** - أكمل التحقق من التاجر على [enterprise.oneclickdz.com/profile](https://app.oneclickdz.com/profile) قبل استخدام API.
  </Warning>

  <Warning>
    **حدود المبلغ** - الحد الأدنى 500 دج، الحد الأقصى 500,000 دج. يجب أن تكون أعداداً صحيحة (بدون كسور عشرية).
  </Warning>

  <Note>
    **انتهاء صلاحية الرابط** - تنتهي صلاحية روابط الدفع بعد 20 دقيقة من الإنشاء. بعد انتهاء الصلاحية يصبح الحالة `FAILED`.
  </Note>

  <Note>
    **اختبار Sandbox** - استخدم مفتاح API sandbox الخاص بك للاختبار. تحقق من `response.payment_link.is_sandbox` لتأكيد وضع الاختبار.
  </Note>

  <CardGroup cols={3}>
    <Card title="مرجع API" icon="square-terminal" href="/ar/api-reference/ocpay/create-link">
      عرض نقاط نهاية API Navio
    </Card>

    <Card title="الدعم" icon="envelope" href="mailto:support@oneclickdz.com">
      التواصل مع فريق الدعم
    </Card>

    <Card title="GitHub" icon="github" href="https://github.com/oneclickdz/ocpay-python-sdk">
      عرض الكود المصدري على GitHub
    </Card>
  </CardGroup>
</div>
