خلاصة
تمكّن واجهة برمجة تطبيقات iPay (API) المطورين من دمج معالجة المدفوعات والفواتير والمعاملات المالية برمجيًا. تستخدم مصادقة OAuth 2.0 ومفتاح API، ونقاط نهاية RESTful للمدفوعات، والاسترداد، والمعاملات، والتسوية، مع متطلبات الامتثال لمعيار PCI DSS وحدود المعدل القياسية في الصناعة. يغطي هذا الدليل إعداد المصادقة، ومعالجة المدفوعات، ودمج الويب هوك، والامتثال الأمني، واستراتيجيات النشر للإنتاج.
مقدمة
تتجاوز معالجة المدفوعات الرقمية 8 تريليونات دولار سنويًا على مستوى العالم. بالنسبة للمطورين الذين يبنون منصات التجارة الإلكترونية، أو تطبيقات SaaS، أو حلول الأسواق، فإن دمج واجهة برمجة تطبيقات الدفع ليس اختياريًا - إنه ضروري لقبول مدفوعات العملاء بشكل آمن ومتوافق.
إليك بعض الحقائق المهمة: الشركات تخسر 5-10% من إيراداتها بسبب المدفوعات الفاشلة، والتسوية اليدوية، والاحتيال في الدفع. دمج واجهة برمجة تطبيقات دفع قوية يتيح لك أتمتة معالجة المدفوعات، تقليل حالات الفشل عبر منطق إعادة المحاولة الذكي، تمكين التسوية التلقائية، وتنفيذ الكشف عن الاحتيال.
هذا الدليل يركز على خطوات التنفيذ العملية: إعداد المصادقة، معالجة المدفوعات، إدارة الاسترداد، التعامل مع الويب هوك، الامتثال لمعيار PCI DSS، أفضل ممارسات الأمان، واستراتيجيات النشر للإنتاج. بنهاية الدليل، ستتمكن من بناء تكامل دفع جاهز للإنتاج.
💡يعمل Apidog على تبسيط اختبار واجهة برمجة تطبيقات الدفع. اختبر نقاط نهاية الدفع في وضع الحماية (sandbox)، وتحقق من توقيعات الويب هوك، وافحص استجابات المعاملات، وقم بتصحيح أخطاء التكامل في مساحة عمل واحدة. استورد مواصفات API، استجب للردود الوهمية (mock responses)، وشارك سيناريوهات الاختبار مع فريقك.
ملاحظة: هذا الدليل يغطي أنماط دمج واجهة برمجة تطبيقات الدفع العامة التي تنطبق على iPay ومعالجات الدفع المماثلة. راجع دائمًا وثائق iPay الرسمية لتفاصيل التنفيذ.
ما هي واجهة برمجة تطبيقات iPay؟
تقدم iPay واجهات RESTful لإدارة المعاملات المالية. أهم العمليات:
- تفويض الدفع والتقاطه
- المبالغ المستردة وعمليات رد المبالغ المدفوعة
- سجل المعاملات والتقارير
- ترميز العملاء (الخزنة)
- الاشتراكات والفواتير المتكررة
- إنشاء الفواتير وإدارتها
- المصالحة والتسوية
- الكشف عن الاحتيال ومنعه
الميزات الرئيسية
| الميزة | الوصف |
|---|---|
| واجهة برمجة تطبيقات RESTful | نقاط نهاية قائمة على JSON |
| OAuth 2.0 + مفاتيح API | مصادقة آمنة |
| الويب هوك (Webhooks) | إشعارات الدفع في الوقت الفعلي |
| الترميز (Tokenization) | تخزين آمن للبطاقة |
| 3D Secure | الامتثال لمعيار SCA |
| PCI DSS | مطلوب الامتثال للمستوى 1 |
| متعدد العملات | يدعم أكثر من 100 عملة |
| أدوات منع الاحتيال | تسجيل المخاطر، فحوصات السرعة |
نظرة عامة على سير عمل الدفع
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Customer │───▶│ Merchant │───▶│ Payment │
│ (Browser) │ │ (Server) │ │ Gateway │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
│ 1. Enter Card │ │
│───────────────────▶│ │
│ │ │
│ 2. Tokenize │ │
│───────────────────▶│ 3. Create Intent │
│ │───────────────────▶│
│ │ │
│ │ 4. Confirm Payment│
│ │───────────────────▶│
│ │ │
│ │ 5. Result │
│ │◀───────────────────│
│ │ │
│ 6. Receipt │ │
│◀───────────────────│ │
بيئة واجهة برمجة التطبيقات
| البيئة | عنوان URL | حالة الاستخدام |
|---|---|---|
| Sandbox (بيئة اختبار) | https://sandbox.ipay.com/api |
التطوير، الاختبار |
| Production (الإنتاج) | https://api.ipay.com/api |
المعاملات الحية |
البدء: إعداد المصادقة
الخطوة 1: إنشاء حساب iPay
- قم بزيارة صفحة تسجيل التجار في iPay.
- أكمل التحقق التجاري (KYB).
- قدم المستندات المطلوبة (سجل النشاط التجاري، تفاصيل الحساب المصرفي، هوية حكومية).
- انتظر الموافقة (1-3 أيام عمل).
الخطوة 2: الحصول على بيانات اعتماد واجهة برمجة التطبيقات
- سجل الدخول إلى لوحة تحكم التاجر في iPay.
- اذهب إلى الإعدادات > مفاتيح API.
- أنشئ مفتاح API جديد واحفظ البيانات في مكان آمن.
# .env file (NEVER commit to git)
IPAY_API_KEY="live_xxxxxxxxxxxxxxxxxxxx"
IPAY_API_SECRET="secret_xxxxxxxxxxxxxxxxxxxx"
IPAY_WEBHOOK_SECRET="whsec_xxxxxxxxxxxxxxxxxxxx"
ملاحظة أمنية: استخدم مفاتيح منفصلة لبيئة الاختبار والإنتاج.
الخطوة 3: فهم طرق المصادقة
| الطريقة | الأفضل لـ | مستوى الأمان |
|---|---|---|
| المصادقة الأساسية | من الخادم إلى الخادم | عالي |
| OAuth 2.0 | تطبيقات متعددة المستأجرين | أعلى |
| JWT | خدمات مصغرة | عالي |
الخطوة 4: إجراء استدعاءات API موثقة
أنشئ عميل API قابل لإعادة الاستخدام:
const IPAY_BASE_URL = process.env.IPAY_SANDBOX
? 'https://sandbox.ipay.com/api'
: 'https://api.ipay.com/api';
const ipayRequest = async (endpoint, options = {}) => {
const apiKey = process.env.IPAY_API_KEY;
const apiSecret = process.env.IPAY_API_SECRET;
// Basic authentication (Base64 encoded)
const authHeader = Buffer.from(`${apiKey}:${apiSecret}`).toString('base64');
const response = await fetch(`${IPAY_BASE_URL}${endpoint}`, {
...options,
headers: {
'Authorization': `Basic ${authHeader}`,
'Content-Type': 'application/json',
'Idempotency-Key': options.idempotencyKey || generateIdempotencyKey(),
...options.headers
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(`iPay API Error: ${error.message}`);
}
return response.json();
};
function generateIdempotencyKey() {
return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
// Usage
const account = await ipayRequest('/account');
console.log(`Merchant: ${account.business_name}`);
معالجة المدفوعات
إنشاء نية دفع
const createPayment = async (paymentData) => {
const payment = {
amount: paymentData.amount, // In smallest currency unit (cents)
currency: paymentData.currency || 'USD',
customer: paymentData.customerId,
payment_method: paymentData.paymentMethodId,
confirm: true,
description: paymentData.description,
metadata: {
orderId: paymentData.orderId,
customerId: paymentData.customerId
},
capture_method: paymentData.captureMethod || 'automatic', // 'automatic' or 'manual'
statement_descriptor: paymentData.statementDescriptor || 'MYCOMPANY'
};
const response = await ipayRequest('/payments', {
method: 'POST',
body: JSON.stringify(payment),
idempotencyKey: paymentData.idempotencyKey
});
return response;
};
// Usage
const payment = await createPayment({
amount: 2999, // $29.99
currency: 'USD',
customerId: 'cus_12345',
paymentMethodId: 'pm_67890',
description: 'Order #ORD-001',
orderId: 'ORD-001',
statementDescriptor: 'MYCOMPANY INC'
});
console.log(`Payment status: ${payment.status}`);
console.log(`Payment ID: ${payment.id}`);
تدفق حالة الدفع
requires_payment_method → requires_confirmation → requires_action
→ processing → requires_capture → succeeded
→ failed
→ canceled
طرق الدفع
| الطريقة | النوع | حالة الاستخدام |
|---|---|---|
card |
بطاقة ائتمان/خصم | مدفوعات قياسية |
bank_transfer |
ACH، SEPA | تحويلات برسوم منخفضة |
digital_wallet |
Apple Pay, Google Pay | الدفع عبر الهاتف المحمول |
buy_now_pay_later |
Klarna, Afterpay | مدفوعات بالتقسيط |
ترميز تفاصيل البطاقة
const tokenizeCard = async (cardData) => {
// NEVER send raw card data to your server
// Use client-side tokenization instead
// Client-side (browser/mobile)
const response = await fetch(`${IPAY_BASE_URL}/tokens`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${CLIENT_PUBLISHABLE_KEY}`
},
body: JSON.stringify({
card: {
number: cardData.number,
exp_month: cardData.expMonth,
exp_year: cardData.expYear,
cvc: cardData.cvc
}
})
});
const token = await response.json();
return token; // Send token.id to your server
};
// Server-side: Use token to create payment method
const createPaymentMethod = async (tokenId, customerId) => {
const response = await ipayRequest('/payment_methods', {
method: 'POST',
body: JSON.stringify({
type: 'card',
token: tokenId,
customer: customerId
})
});
return response;
};
مصادقة 3D Secure
const createPaymentWith3DS = async (paymentData) => {
const payment = await createPayment({
...paymentData,
confirmation_token: true // Return client secret for 3DS
});
if (payment.status === 'requires_action') {
// Client must complete 3DS challenge
return {
requiresAction: true,
clientSecret: payment.client_secret,
nextAction: payment.next_action
};
}
return { success: true, payment };
};
// Client-side: Handle 3DS challenge
// Use iPay.js or mobile SDK to present authentication challenge
إدارة المبالغ المستردة
معالجة استرداد كامل
const refundPayment = async (paymentId, reason = null) => {
const refund = {
payment: paymentId,
reason: reason || 'requested_by_customer'
};
const response = await ipayRequest('/refunds', {
method: 'POST',
body: JSON.stringify(refund),
idempotencyKey: `refund_${paymentId}_${Date.now()}`
});
return response;
};
// Usage
const refund = await refundPayment('pay_12345', 'duplicate');
console.log(`Refund status: ${refund.status}`);
console.log(`Refund ID: ${refund.id}`);
معالجة استرداد جزئي
const partialRefund = async (paymentId, amount, reason = null) => {
const refund = {
payment: paymentId,
amount: amount, // In smallest currency unit
reason: reason || 'requested_by_customer'
};
const response = await ipayRequest('/refunds', {
method: 'POST',
body: JSON.stringify(refund),
idempotencyKey: `refund_${paymentId}_${amount}_${Date.now()}`
});
return response;
};
// Usage - Refund $15.00 of $29.99 payment
const refund = await partialRefund('pay_12345', 1500, 'partial_ship');
console.log(`Refunded: $${refund.amount / 100}`);
أسباب الاسترداد
| رمز السبب | الوصف |
|---|---|
duplicate |
رسوم مكررة |
fraudulent |
معاملة احتيالية |
requested_by_customer |
طلب العميل |
order_canceled |
إلغاء الطلب |
product_not_received |
لم يتم تسليم العنصر |
product_not_as_described |
العنصر يختلف عن الوصف |
إدارة العملاء
إنشاء عميل
const createCustomer = async (customerData) => {
const customer = {
email: customerData.email,
name: customerData.name,
phone: customerData.phone,
metadata: {
internalId: customerData.internalId,
tier: customerData.tier
}
};
const response = await ipayRequest('/customers', {
method: 'POST',
body: JSON.stringify(customer)
});
return response;
};
// Usage
const customer = await createCustomer({
email: 'customer@example.com',
name: 'John Doe',
phone: '+1-555-0123',
internalId: 'USR-12345',
tier: 'premium'
});
console.log(`Customer created: ${customer.id}`);
إرفاق طريقة دفع بالعميل
const attachPaymentMethod = async (paymentMethodId, customerId) => {
const response = await ipayRequest(`/payment_methods/${paymentMethodId}/attach`, {
method: 'POST',
body: JSON.stringify({
customer: customerId
})
});
return response;
};
// Usage
await attachPaymentMethod('pm_67890', 'cus_12345');
إدراج طرق دفع العميل
const getCustomerPaymentMethods = async (customerId) => {
const response = await ipayRequest(`/customers/${customerId}/payment_methods`);
return response;
};
// Usage
const methods = await getCustomerPaymentMethods('cus_12345');
methods.data.forEach(method => {
console.log(`${method.card.brand} ending in ${method.card.last4}`);
console.log(`Expires: ${method.card.exp_month}/${method.card.exp_year}`);
});
الويب هوك (Webhooks)
تكوين الويب هوك
- سجل الدخول إلى لوحة تحكم iPay.
- انتقل إلى المطورون > الويب هوك.
- أضف نقطة نهاية HTTPS الخاصة بك.
- حدد الأحداث المراد الاشتراك بها.
أحداث الويب هوك
| الحدث | المحفز |
|---|---|
payment.succeeded |
اكتمل الدفع |
payment.failed |
رفض الدفع |
payment.refunded |
تمت معالجة الاسترداد |
payment.disputed |
تم تقديم طلب رد المبلغ |
customer.created |
عميل جديد |
customer.subscription.updated |
تغيير الاشتراك |
معالجة الويب هوك
const express = require('express');
const crypto = require('crypto');
const app = express();
app.post('/webhooks/ipay', express.raw({ type: 'application/json' }), async (req, res) => {
const signature = req.headers['ipay-signature'];
const payload = req.body;
// Verify webhook signature
const isValid = verifyWebhookSignature(payload, signature, process.env.IPAY_WEBHOOK_SECRET);
if (!isValid) {
console.error('Invalid webhook signature');
return res.status(401).send('Unauthorized');
}
const event = JSON.parse(payload.toString());
// Route to appropriate handler
switch (event.type) {
case 'payment.succeeded':
await handlePaymentSucceeded(event.data);
break;
case 'payment.failed':
await handlePaymentFailed(event.data);
break;
case 'payment.refunded':
await handlePaymentRefunded(event.data);
break;
case 'payment.disputed':
await handlePaymentDisputed(event.data);
break;
default:
console.log('Unhandled event type:', event.type);
}
// Acknowledge receipt
res.status(200).send('OK');
});
function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedSignature, 'hex')
);
}
async function handlePaymentSucceeded(data) {
console.log(`Payment succeeded: ${data.id}`);
// Update order status
await db.orders.update(data.metadata.orderId, {
status: 'paid',
paymentId: data.id,
paidAt: new Date()
});
// Send confirmation email
await sendOrderConfirmation(data.metadata.orderId);
}
async function handlePaymentFailed(data) {
console.log(`Payment failed: ${data.id} - ${data.failure_code}`);
// Notify customer
await sendPaymentFailedEmail(data.customer, data.failure_message);
// Retry logic or mark order as failed
await db.orders.update(data.metadata.orderId, {
status: 'payment_failed',
failureReason: data.failure_message
});
}
الأمان والامتثال
متطلبات PCI DSS
يجب أن تتوافق عمليات دمج الدفع مع معيار PCI DSS:
| المتطلب | التطبيق |
|---|---|
| شبكة آمنة | استخدم HTTPS، جدران الحماية، تكوينات آمنة |
| حماية بيانات حامل البطاقة | لا تقم أبدًا بتخزين CVV، قم بتشفير PAN |
| إدارة الثغرات الأمنية | تحديثات أمنية منتظمة، برامج مكافحة الفيروسات |
| التحكم في الوصول | أقل الامتيازات، MFA، معرفات فريدة |
| المراقبة | التسجيل، الكشف عن الاختراقات |
| سياسة الأمان | سياسات موثقة، تدريب منتظم |
أفضل ممارسات الأمان
// 1. Use tokenization - NEVER handle raw card data
const token = await tokenizeCard(cardData); // Client-side
// 2. Implement idempotency for all payment operations
const idempotencyKey = `pay_${orderId}_${Date.now()}`;
// 3. Validate amounts server-side
if (req.body.amount !== calculatedAmount) {
throw new Error('Amount mismatch - possible tampering');
}
// 4. Log all payment operations (without sensitive data)
logger.info('Payment attempted', {
orderId,
amount,
currency,
customerId,
timestamp: new Date().toISOString()
// NEVER log: card numbers, CVV, full payment method details
});
// 5. Use environment variables for secrets
const apiKey = process.env.IPAY_API_KEY; // Not hardcoded
// 6. Implement rate limiting on payment endpoints
const paymentLimiter = rateLimit({
windowMs: 60000,
max: 10 // 10 payment attempts per minute
});
قائمة التحقق من نشر الإنتاج
قبل معالجة المدفوعات المباشرة، تأكد من:
- [ ] أكمل استبيان التقييم الذاتي لـ PCI DSS
- [ ] استخدم HTTPS لجميع نقاط النهاية
- [ ] قم بتخزين مفاتيح API في إدارة آمنة للأسرار
- [ ] نفذ التحقق من توقيع الويب هوك
- [ ] أضف خاصية عدم التكرارية (idempotency) لجميع عمليات الدفع
- [ ] أعد إعداد تسجيل شامل (بدون بيانات حساسة)
- [ ] قم بتكوين قواعد الكشف عن الاحتيال
- [ ] اختبر تدفقات الاسترداد والنزاعات
- [ ] أنشئ دليل تشغيل لإخفاقات الدفع
- [ ] أعد إعداد المراقبة والتنبيه
- [ ] طبق معالج دفع احتياطي
حالات الاستخدام في العالم الحقيقي
الدفع في التجارة الإلكترونية
- التحدي: معالجة المدفوعات اليدوية، معدل تخلي مرتفع عن الشراء
- الحل: صفحة دفع واحدة مع بطاقات مرمزة
- النتيجة: زيادة في التحويل بنسبة 35%، مدفوعات فورية
فوترة الاشتراكات لـ SaaS
- التحدي: إنشاء الفواتير وتحصيلها يدويًا
- الحل: مدفوعات متكررة مع إعادة محاولة تلقائية
- النتيجة: 95% دفع في الوقت المحدد، توفير 80% من وقت الإدارة
الضمان في السوق (Marketplace Escrow)
- التحدي: مدفوعات مقسمة معقدة بين البائعين
- الحل: نوايا الدفع مع جدولة التحويلات
- النتيجة: مدفوعات تلقائية للبائعين، انخفاض الاحتيال
الخاتمة
يتطلب دمج واجهة برمجة تطبيقات الدفع اهتمامًا دقيقًا بالأمان والامتثال ومعالجة الأخطاء. النقاط الرئيسية لتكامل ناجح:
- لا تتعامل أبدًا مع بيانات البطاقة الخام - استخدم الترميز (tokenization)
- طبق خاصية عدم التكرارية (idempotency) لجميع عمليات الدفع
- تحقق من توقيعات الويب هوك لمنع الاحتيال
- امتثل لمتطلبات PCI DSS
- اختبر بدقة في بيئة الحماية (sandbox) قبل الإنتاج
- استخدم أدوات مثل Apidog لاختبار واجهات API والتعاون الجماعي
قسم الأسئلة الشائعة
كيف أقوم بالمصادقة مع واجهة برمجة تطبيقات iPay؟
استخدم المصادقة الأساسية (Basic authentication) مع مفتاح API وسر، أو OAuth 2.0 للتطبيقات متعددة المستأجرين.
هل يمكنني تخزين تفاصيل بطاقة العميل؟
نعم، ولكن يجب أن تكون متوافقًا مع PCI DSS. استخدم الترميز (tokenization) لتخزين البطاقات بأمان في خزنة iPay.
كيف أتعامل مع المدفوعات الفاشلة؟
طبق منطق إعادة المحاولة مع التراجع الأسي (exponential backoff)، وأبلغ العملاء، ووفر طرق دفع بديلة.
ما هي خاصية عدم التكرارية (Idempotency) ولماذا هي مهمة؟
تضمن خاصية عدم التكرارية أن الطلبات المكررة بنفس المفتاح تنتج نفس النتيجة، مما يمنع رسومًا مكررة.
كيف يمكنني اختبار المدفوعات دون فرض رسوم على البطاقات؟
استخدم وضع الاختبار (sandbox) مع أرقام بطاقات الاختبار المتوفرة في وثائق iPay.
ما هي توقيعات الويب هوك؟
توقيعات تشفيرية تتحقق من أن الويب هوك جاءت من iPay، وليس من جهة خبيثة.
Top comments (0)