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

> دليل الإعداد السريع لـ SDK Navio Node.js/TypeScript

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

  يوفر SDK Navio Node.js واجهة حديثة وآمنة من حيث الأنواع لدمج مدفوعات Navio في تطبيقات Node.js وTypeScript الخاصة بك. مبني باستخدام TypeScript وasync/await لأفضل تجربة للمطورين.

  <CardGroup cols={2}>
    <Card title="TypeScript أصيل" icon="shield-check" color="#0D9373">
      دعم TypeScript كامل مع تعريفات أنواع شاملة
    </Card>

    <Card title="قائم على Promises" icon="clock" color="#0D9373">
      دعم أصيل للـ Promises مع async/await
    </Card>

    <Card title="API بسيط" icon="code" color="#0D9373">
      واجهة نظيفة وبديهية
    </Card>

    <Card title="معالجة الأخطاء" icon="circle-exclamation" color="#0D9373">
      استثناءات مخصصة لأنواع الأخطاء المختلفة
    </Card>
  </CardGroup>

  ## المتطلبات

  * Node.js 16.0.0 أو أحدث
  * npm أو yarn أو pnpm

  ## التثبيت

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

  ```bash theme={null}
  npm install @oneclickdz/ocpay-sdk
  ```

  أو مع yarn:

  ```bash theme={null}
  yarn add @oneclickdz/ocpay-sdk
  ```

  أو مع pnpm:

  ```bash theme={null}
  pnpm add @oneclickdz/ocpay-sdk
  ```

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

  ### 1. تهيئة SDK

  ```typescript theme={null}
  import { OCPay } from '@oneclickdz/ocpay-sdk';

  // Initialize with your API access token
  const ocpay = new OCPay('your-api-access-token');
  ```

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

  ```bash theme={null}
  # .env file
  ONECLICK_API_KEY=your_api_key_here
  ```

  ```typescript theme={null}
  // Load from environment
  const ocpay = new OCPay(process.env.ONECLICK_API_KEY);
  ```

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

  ```typescript theme={null}
  import { OCPay, FeeMode } from '@oneclickdz/ocpay-sdk';

  const ocpay = new OCPay(process.env.ONECLICK_API_KEY);

  // Create payment link request
  const request = {
    productInfo: {
      title: 'Premium Subscription',
      amount: 5000, // Amount in DZD (500 - 500,000)
      description: 'Monthly access to premium features',
    },
    feeMode: FeeMode.NO_FEE, // Merchant pays fees
    successMessage: 'Thank you for your purchase!',
    redirectUrl: 'https://yourstore.com/success?orderId=12345',
  };

  // Create the payment link
  try {
    const response = await ocpay.createLink(request);
    
    // Redirect customer to payment page
    console.log('Payment URL:', response.paymentUrl);
    
    // IMPORTANT: Save this reference!
    console.log('Payment Reference:', response.paymentRef);
    // await saveOrderPaymentRef(orderId, response.paymentRef);
    
  } catch (error) {
    if (error instanceof ValidationException) {
      console.error('Validation error:', error.message);
    } else if (error instanceof UnauthorizedException) {
      console.error('Auth error:', error.message);
    } else if (error instanceof ApiException) {
      console.error('API error:', error.message);
    }
  }
  ```

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

  ```typescript theme={null}
  import { PaymentStatus } from '@oneclickdz/ocpay-sdk';

  // Check payment status using the payment reference
  try {
    const status = await ocpay.checkPayment('OCPL-A1B2C3-D4E5');
    
    if (status.status === PaymentStatus.CONFIRMED) {
      // Payment successful - fulfill the order
      console.log('Payment confirmed!');
      console.log('Amount:', status.transactionDetails?.amount, 'DZD');
      await fulfillOrder(orderId);
      
    } else if (status.status === PaymentStatus.FAILED) {
      // Payment failed or expired
      console.log('Payment failed:', status.message);
      await markOrderFailed(orderId);
      
    } else {
      // Still pending - check again later
      console.log('Payment pending...');
      await schedulePolling(orderId);
    }
    
  } catch (error) {
    if (error instanceof NotFoundException) {
      console.error('Payment not found');
    } else if (error instanceof PaymentExpiredException) {
      console.error('Payment link expired');
    } else if (error instanceof ApiException) {
      console.error('API error:', error.message);
    }
  }
  ```

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

  إليك تدفقاً كاملاً لعملية دفع في التجارة الإلكترونية:

  ```typescript theme={null}
  import {
    OCPay,
    FeeMode,
    PaymentStatus,
    ValidationException,
    ApiException,
  } from '@oneclickdz/ocpay-sdk';

  // Initialize SDK
  const ocpay = new OCPay(process.env.ONECLICK_API_KEY!);

  // Step 1: Create order in your system
  const orderId = await createOrder({
    customerId: 123,
    items: [
      { name: 'Product A', price: 5000 },
      { name: 'Product B', price: 3000 },
    ],
    total: 8000,
  });

  // Step 2: Create payment link
  try {
    const response = await ocpay.createLink({
      productInfo: {
        title: `Order #${orderId}`,
        amount: 8000,
        description: `Payment for order #${orderId}`,
      },
      feeMode: FeeMode.NO_FEE,
      successMessage: `Thank you! Your order #${orderId} is being processed.`,
      redirectUrl: `https://yourstore.com/orders/${orderId}/success`,
    });

    // Step 3: Save payment reference to order
    await updateOrder(orderId, {
      paymentRef: response.paymentRef,
      paymentUrl: response.paymentUrl,
      status: 'pending_payment',
    });

    // Step 4: Redirect customer to payment page
    // res.redirect(response.paymentUrl);
    console.log('Redirect to:', response.paymentUrl);
    
  } catch (error) {
    console.error('Payment link creation failed:', error.message);
    // showErrorPage('Failed to create payment link. Please try again.');
  }

  // Step 5: Poll payment status (in background job)
  async function checkOrderPayment(orderId: string): Promise<void> {
    const order = await getOrder(orderId);

    if (!order || !order.paymentRef) {
      return;
    }

    try {
      const status = await ocpay.checkPayment(order.paymentRef);

      if (status.status === PaymentStatus.CONFIRMED) {
        // Mark order as paid and fulfill
        await updateOrder(orderId, {
          status: 'paid',
          paidAt: new Date(),
        });
        await fulfillOrder(orderId);
        
      } else if (status.status === PaymentStatus.FAILED) {
        // Mark order as failed
        await updateOrder(orderId, {
          status: 'payment_failed',
        });
      }
      // If pending, do nothing and check again later
      
    } catch (error) {
      console.error('Payment status check failed:', error.message);
    }
  }
  ```

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

  ### Express.js

  ```typescript theme={null}
  import express from 'express';
  import { OCPay, FeeMode, PaymentStatus } from '@oneclickdz/ocpay-sdk';

  const app = express();
  const ocpay = new OCPay(process.env.ONECLICK_API_KEY!);

  app.use(express.json());

  // Create payment endpoint
  app.post('/api/orders/:orderId/payment', async (req, res) => {
    const { orderId } = req.params;
    const order = await getOrder(orderId);

    try {
      const response = await ocpay.createLink({
        productInfo: {
          title: `Order #${orderId}`,
          amount: order.total,
        },
        feeMode: FeeMode.NO_FEE,
        redirectUrl: `${req.protocol}://${req.get('host')}/orders/${orderId}/success`,
      });

      await updateOrder(orderId, { paymentRef: response.paymentRef });
      res.json({ paymentUrl: response.paymentUrl });
      
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });

  // Check payment status endpoint
  app.get('/api/payments/:paymentRef/status', async (req, res) => {
    try {
      const status = await ocpay.checkPayment(req.params.paymentRef);
      res.json(status);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });

  app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
  });
  ```

  ### NestJS

  ```typescript theme={null}
  import { Injectable } from '@nestjs/common';
  import { OCPay, CreateLinkRequest, FeeMode } from '@oneclickdz/ocpay-sdk';

  @Injectable()
  export class PaymentService {
    private readonly ocpay: OCPay;

    constructor() {
      this.ocpay = new OCPay(process.env.ONECLICK_API_KEY!);
    }

    async createPaymentLink(orderId: string, amount: number): Promise<string> {
      const response = await this.ocpay.createLink({
        productInfo: {
          title: `Order #${orderId}`,
          amount,
        },
        feeMode: FeeMode.NO_FEE,
        redirectUrl: `https://yourstore.com/orders/${orderId}/success`,
      });

      return response.paymentUrl;
    }

    async checkPaymentStatus(paymentRef: string) {
      return await this.ocpay.checkPayment(paymentRef);
    }
  }
  ```

  ### Next.js (App Router)

  ```typescript theme={null}
  // app/api/orders/[orderId]/payment/route.ts
  import { NextRequest, NextResponse } from 'next/server';
  import { OCPay, FeeMode } from '@oneclickdz/ocpay-sdk';

  const ocpay = new OCPay(process.env.ONECLICK_API_KEY!);

  export async function POST(
    request: NextRequest,
    { params }: { params: { orderId: string } }
  ) {
    try {
      const order = await getOrder(params.orderId);
      
      const response = await ocpay.createLink({
        productInfo: {
          title: `Order #${params.orderId}`,
          amount: order.total,
        },
        feeMode: FeeMode.NO_FEE,
        redirectUrl: `${process.env.NEXT_PUBLIC_URL}/orders/${params.orderId}/success`,
      });

      await updateOrder(params.orderId, { paymentRef: response.paymentRef });
      
      return NextResponse.json({ paymentUrl: response.paymentUrl });
    } catch (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
  }
  ```

  ## مرجع API

  ### فئة Navio

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

  #### المنشئ

  ```typescript theme={null}
  constructor(accessToken: string, options?: ClientOptions)
  ```

  **المعاملات:**

  * `accessToken` (string) - رمز الوصول إلى API الخاص بك
  * `options` (ClientOptions) - إعداد اختياري للعميل:
    * `timeout` (number) - مهلة الطلب بالميلي ثانية (الافتراضي: 30000)
    * `baseURL` (string) - URL أساسي مخصص (بشكل رئيسي للاختبار)
    * `headers` (object) - رؤوس إضافية

  **مثال:**

  ```typescript theme={null}
  const ocpay = new OCPay('your-api-key', {
    timeout: 60000, // 60 seconds
  });
  ```

  #### الطرق

  `createLink(request: CreateLinkRequest): Promise<CreateLinkResponse>`

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

  `checkPayment(paymentRef: string): Promise<CheckPaymentResponse>`

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

  ### الأنواع والواجهات

  #### ProductInfo

  ```typescript theme={null}
  interface ProductInfo {
    title: string;        // Product name (1-200 chars)
    amount: number;       // Amount in DZD (500 - 500,000)
    description?: string; // Optional (max 1000 chars)
  }
  ```

  #### CreateLinkRequest

  ```typescript theme={null}
  interface CreateLinkRequest {
    productInfo: ProductInfo;
    feeMode?: FeeMode;        // NO_FEE (default), SPLIT_FEE, CUSTOMER_FEE
    successMessage?: string;  // Optional success message
    redirectUrl?: string;     // Optional redirect URL
  }
  ```

  **Enum FeeMode:**

  ```typescript theme={null}
  enum FeeMode {
    NO_FEE = 'NO_FEE',           // Merchant pays (default)
    SPLIT_FEE = 'SPLIT_FEE',     // 50/50 split
    CUSTOMER_FEE = 'CUSTOMER_FEE' // Customer pays
  }
  ```

  #### CreateLinkResponse

  ```typescript theme={null}
  interface CreateLinkResponse {
    paymentLink: PaymentLink;  // Full payment link details
    paymentUrl: string;        // URL to redirect customer
    paymentRef: string;        // Payment reference (SAVE THIS!)
  }
  ```

  #### CheckPaymentResponse

  ```typescript theme={null}
  interface CheckPaymentResponse {
    status: PaymentStatus;            // Payment status enum
    message: string;                  // Status message
    paymentRef: string;               // Payment reference
    transactionDetails?: TransactionDetails; // Details (if available)
  }
  ```

  **Enum PaymentStatus:**

  ```typescript theme={null}
  enum PaymentStatus {
    PENDING = 'PENDING',     // Payment in progress
    CONFIRMED = 'CONFIRMED', // Payment successful
    FAILED = 'FAILED',       // Payment declined/expired
  }
  ```

  ### معالجة الاستثناءات

  جميع الاستثناءات ترث من `OCPayException`:

  | الاستثناء                 | كود HTTP | عند الإطلاق                       |
  | ------------------------- | -------- | --------------------------------- |
  | `ValidationException`     | 400      | بيانات طلب غير صالحة              |
  | `UnauthorizedException`   | 403      | مفتاح API غير صالح                |
  | `NotFoundException`       | 404      | الدفع غير موجود                   |
  | `PaymentExpiredException` | 410      | الرابط منتهي الصلاحية (>20 دقيقة) |
  | `ApiException`            | متنوعة   | أخطاء API أخرى                    |

  جميع الاستثناءات توفر:

  ```typescript theme={null}
  try {
    const response = await ocpay.createLink(request);
  } catch (error) {
    if (error instanceof ApiException) {
      console.log(error.message);         // Error message
      console.log(error.getStatusCode()); // HTTP status code
      console.log(error.getRequestId());  // Request ID for support
      console.log(error.getErrorData());  // Full error data
    }
  }
  ```

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

  ### التحقق من التاجر مطلوب

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

  ### حدود المبلغ

  * **الحد الأدنى**: 500 دج
  * **الحد الأقصى**: 500,000 دج
  * يجب أن يكون عدداً صحيحاً

  ### هيكل الرسوم

  <Info>
    **رسوم منخفضة**: 0% على الرصيد، رسوم سحب 1% فقط
  </Info>

  ### انتهاء صلاحية رابط الدفع

  تنتهي صلاحية الروابط بعد **20 دقيقة** من الإنشاء إذا لم يُبدأ الدفع.

  ### تدفق حالة الدفع

  1. **PENDING** - الدفع قيد التنفيذ → أعد التحقق لاحقاً
  2. **CONFIRMED** - الدفع ناجح → نفّذ الطلب
  3. **FAILED** - الدفع مرفوض/منتهي الصلاحية → علّم الطلب كفاشل

  ## دعم TypeScript

  هذا SDK مكتوب بـ TypeScript ويتضمن تعريفات أنواع كاملة. لا حاجة لتثبيت حزم `@types`!

  ```typescript theme={null}
  import { OCPay, CreateLinkRequest, PaymentStatus } from '@oneclickdz/ocpay-sdk';

  // Full IntelliSense and type checking
  const request: CreateLinkRequest = {
    productInfo: {
      title: 'Product',
      amount: 5000,
    },
  };
  ```

  ## الاستخدام مع JavaScript

  يعمل SDK بشكل مثالي مع JavaScript العادي أيضاً:

  ```javascript theme={null}
  const { OCPay, FeeMode } = require('@oneclickdz/ocpay-sdk');

  const ocpay = new OCPay(process.env.ONECLICK_API_KEY);

  async function createPayment() {
    const response = await ocpay.createLink({
      productInfo: {
        title: 'Premium Subscription',
        amount: 5000,
      },
      feeMode: FeeMode.NO_FEE,
    });
    
    console.log('Payment URL:', response.paymentUrl);
  }
  ```

  ## الاختبار

  ### استخدام Sandbox

  يستخدم API تلقائياً وضع sandbox لحسابات الاختبار:

  ```typescript theme={null}
  const response = await ocpay.createLink(request);

  if (response.paymentLink.isSandbox) {
    console.log('This is a test payment');
  }
  ```

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

  <AccordionGroup>
    <Accordion title="احفظ دائماً مرجع الدفع" icon="database">
      خزّن `paymentRef` فوراً بعد إنشاء الرابط. ستحتاجه للتحقق من حالة الدفع.
    </Accordion>

    <Accordion title="تحقق من حالة الدفع" icon="clock">
      قم بإعداد مهمة خلفية للتحقق من حالة الدفع كل 20 دقيقة للطلبات المعلقة.
    </Accordion>

    <Accordion title="تعامل مع جميع الاستثناءات" icon="shield-halved">
      التقط جميع أنواع الاستثناءات وتعامل معها بشكل مناسب. سجّل الأخطاء لأغراض التصحيح.
    </Accordion>

    <Accordion title="أمّن مفتاح API الخاص بك" icon="key">
      خزّن مفاتيح API في متغيرات البيئة، ولا تلتزم بها أبداً في نظام التحكم بالإصدار.
    </Accordion>

    <Accordion title="استخدم HTTPS فقط" icon="lock">
      استخدم دائماً HTTPS لعناوين URL لإعادة التوجيه ونقاط النهاية في تطبيقك.
    </Accordion>
  </AccordionGroup>

  ## الدعم والموارد

  <CardGroup cols={2}>
    <Card title="مستودع GitHub" icon="github" href="https://github.com/oneclickdz/ocpay-nodejs-sdk">
      الكود المصدري والأمثلة والمشاكل
    </Card>

    <Card title="توثيق API" icon="book" href="/ar/api-reference/ocpay/create-link">
      مرجع API مفصل
    </Card>

    <Card title="حزمة npm" icon="npm" href="https://www.npmjs.com/package/@oneclickdz/ocpay-sdk">
      عرض على سجل npm
    </Card>

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

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

  <Card title="أفضل ممارسات Navio" icon="star" href="/ar/ocpay-guides/4-best-practices">
    تعلم نصائح الإنتاج وأفضل ممارسات الأمان
  </Card>
</div>
