الانتقال إلى المحتوى الرئيسي

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 Navio Node.js واجهة حديثة وآمنة من حيث الأنواع لدمج مدفوعات Navio في تطبيقات Node.js وTypeScript الخاصة بك. مبني باستخدام TypeScript وasync/await لأفضل تجربة للمطورين.

TypeScript أصيل

دعم TypeScript كامل مع تعريفات أنواع شاملة

قائم على Promises

دعم أصيل للـ Promises مع async/await

API بسيط

واجهة نظيفة وبديهية

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

استثناءات مخصصة لأنواع الأخطاء المختلفة

المتطلبات

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

التثبيت

قم بالتثبيت عبر npm:
npm install @oneclickdz/ocpay-sdk
أو مع yarn:
yarn add @oneclickdz/ocpay-sdk
أو مع pnpm:
pnpm add @oneclickdz/ocpay-sdk

البدء السريع

1. تهيئة SDK

import { OCPay } from '@oneclickdz/ocpay-sdk';

// Initialize with your API access token
const ocpay = new OCPay('your-api-access-token');
خزّن مفتاح API الخاص بك في متغيرات البيئة، وليس في الكود مباشرة
# .env file
ONECLICK_API_KEY=your_api_key_here
// Load from environment
const ocpay = new OCPay(process.env.ONECLICK_API_KEY);

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

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. التحقق من حالة الدفع

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);
  }
}

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

إليك تدفقاً كاملاً لعملية دفع في التجارة الإلكترونية:
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

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

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)

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

المنشئ

constructor(accessToken: string, options?: ClientOptions)
المعاملات:
  • accessToken (string) - رمز الوصول إلى API الخاص بك
  • options (ClientOptions) - إعداد اختياري للعميل:
    • timeout (number) - مهلة الطلب بالميلي ثانية (الافتراضي: 30000)
    • baseURL (string) - URL أساسي مخصص (بشكل رئيسي للاختبار)
    • headers (object) - رؤوس إضافية
مثال:
const ocpay = new OCPay('your-api-key', {
  timeout: 60000, // 60 seconds
});

الطرق

createLink(request: CreateLinkRequest): Promise<CreateLinkResponse>ينشئ رابط دفع.checkPayment(paymentRef: string): Promise<CheckPaymentResponse>يتحقق من حالة الدفع.

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

ProductInfo

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

CreateLinkRequest

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:
enum FeeMode {
  NO_FEE = 'NO_FEE',           // Merchant pays (default)
  SPLIT_FEE = 'SPLIT_FEE',     // 50/50 split
  CUSTOMER_FEE = 'CUSTOMER_FEE' // Customer pays
}

CreateLinkResponse

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

CheckPaymentResponse

interface CheckPaymentResponse {
  status: PaymentStatus;            // Payment status enum
  message: string;                  // Status message
  paymentRef: string;               // Payment reference
  transactionDetails?: TransactionDetails; // Details (if available)
}
Enum PaymentStatus:
enum PaymentStatus {
  PENDING = 'PENDING',     // Payment in progress
  CONFIRMED = 'CONFIRMED', // Payment successful
  FAILED = 'FAILED',       // Payment declined/expired
}

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

جميع الاستثناءات ترث من OCPayException:
الاستثناءكود HTTPعند الإطلاق
ValidationException400بيانات طلب غير صالحة
UnauthorizedException403مفتاح API غير صالح
NotFoundException404الدفع غير موجود
PaymentExpiredException410الرابط منتهي الصلاحية (>20 دقيقة)
ApiExceptionمتنوعةأخطاء API أخرى
جميع الاستثناءات توفر:
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
  }
}

ملاحظات مهمة

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

أكمل التحقق من التاجر على app.oneclickdz.com قبل استخدام API

حدود المبلغ

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

هيكل الرسوم

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

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

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

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

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

دعم TypeScript

هذا SDK مكتوب بـ TypeScript ويتضمن تعريفات أنواع كاملة. لا حاجة لتثبيت حزم @types!
import { OCPay, CreateLinkRequest, PaymentStatus } from '@oneclickdz/ocpay-sdk';

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

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

يعمل SDK بشكل مثالي مع JavaScript العادي أيضاً:
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 لحسابات الاختبار:
const response = await ocpay.createLink(request);

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

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

خزّن paymentRef فوراً بعد إنشاء الرابط. ستحتاجه للتحقق من حالة الدفع.
قم بإعداد مهمة خلفية للتحقق من حالة الدفع كل 20 دقيقة للطلبات المعلقة.
التقط جميع أنواع الاستثناءات وتعامل معها بشكل مناسب. سجّل الأخطاء لأغراض التصحيح.
خزّن مفاتيح API في متغيرات البيئة، ولا تلتزم بها أبداً في نظام التحكم بالإصدار.
استخدم دائماً HTTPS لعناوين URL لإعادة التوجيه ونقاط النهاية في تطبيقك.

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

مستودع GitHub

الكود المصدري والأمثلة والمشاكل

توثيق API

مرجع API مفصل

حزمة npm

عرض على سجل npm

اتصل بالدعم

احصل على المساعدة من فريقنا

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

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

تعلم نصائح الإنتاج وأفضل ممارسات الأمان