Node.js SDK
استخدم Node.js SDK الرسمية من OrcaRail لقبول مدفوعات الكريبتو بأقل قدر من كود التكامل. تتولى الـ SDK المصادقة وتنسيق الطلبات والتحقق من توقيعات الـ webhooks.
التثبيت
ثبّت الحزمة من npm:
npm install @orcarail/node
الإعداد
أنشئ عميل OrcaRail بمفتاح API وسرّه. واختياريًا اضبط رابطًا أساسيًا مخصصًا (مثل التطوير المحلي) ومهلة انتظار.
import OrcaRail from '@orcarail/node'
const orcarail = new OrcaRail(
process.env.ORCARAIL_API_KEY!, // e.g., "ak_live_xxx"
process.env.ORCARAIL_API_SECRET!, // e.g., "sk_live_xxx"
{
baseUrl: 'https://api.orcarail.com/api/v1', // optional; default
timeout: 30000, // optional; ms, default 30000
}
)
للتطوير المحلي، وجّه baseUrl إلى API الخاصة بك:
const orcarail = new OrcaRail(apiKey, apiSecret, {
baseUrl: 'http://127.0.0.1:3000/api/v1',
timeout: 65000, // /complete can take up to ~65s
})
الإنتاج مقابل الـ sandbox
تبدأ مفاتيح مؤسسة sandbox بـ ak_test_ (شبكات تجريبية، دون أموال حقيقية). معها تكون orcarail.livemode قيمتها false، وتكمل await orcarail.paymentIntents.simulate(id) دفعة sandbox دون محفظة. تحمل أحداث الـ webhook قيمة livemode: لا تنفّذ أبدًا طلبات حقيقية من أحداث livemode: false.
العمولة (التقسيم والحصول على حصتك)
يمكن أن يكون لمفاتيح API نسبة عمولة اختيارية (0–100). اضبطها في لوحة التحكم ← مفاتيح API أو عبر PATCH /api/v1/api-keys/:id مع commissionPercent. تتضمن المدفوعات المنشأة بذلك المفتاح العمولة في عرض السعر (مرئية للدافع)، ويُرسل مبلغ العمولة إلى عنوان إعدادات السحب لديك عند سحب الأموال.
Payment Intents
إنشاء Payment Intent
أنشئ payment intent بالمبلغ والعملة والرمز والشبكة وروابط العودة/الإلغاء.
const intent = await orcarail.paymentIntents.create({
amount: '100.00',
currency: 'usd',
payment_method_types: ['crypto'],
tokenId: 1, // e.g., USDC
networkId: 1, // e.g., Ethereum
return_url: 'https://yourapp.com/success',
cancel_url: 'https://yourapp.com/cancel',
description: 'Order #12345',
metadata: { order_id: '12345' },
withdrawal_address: '0x...', // optional: override where funds are withdrawn; omit to use your account default
})
console.log(intent.id) // e.g., "550e8400-e29b-41d4-a716-446655440000"
console.log(intent.client_secret)
console.log(intent.payment_link?.link)
التأكيد والتوجيه إلى الدفع
أكّد الـ intent للحصول على رابط صفحة الدفع المستضافة، ثم وجّه العميل:
const confirmed = await orcarail.paymentIntents.confirm(intent.id, {
client_secret: intent.client_secret!,
return_url: 'https://yourapp.com/success',
})
// Redirect user to confirmed.pay_url or nextAction.redirectToUrl.url
استرجاع Payment Intent
اجلب الحالة الحالية لـ payment intent:
const intent = await orcarail.paymentIntents.retrieve(
'550e8400-e29b-41d4-a716-446655440000'
)
console.log(intent.status)
تحديث Payment Intent
حدّث المبلغ أو البيانات الوصفية أو الروابط أو عنوان السحب قبل أن يدفع العميل:
const updated = await orcarail.paymentIntents.update(
'550e8400-e29b-41d4-a716-446655440000',
{
amount: '150.00',
metadata: { order_id: '12345' },
withdrawal_address: '0x...', // optional: override withdrawal address for this payment
}
)
إلغاء Payment Intent
ألغِ عندما يترك المستخدم الدفع أو يصل إلى رابط الإلغاء:
const canceled = await orcarail.paymentIntents.cancel(
'550e8400-e29b-41d4-a716-446655440000'
)
إكمال Payment Intent
عندما يصل المستخدم إلى رابط النجاح/العودة، علّم الـ intent بأنه قيد المعالجة (يطلق ذلك الـ webhook payment_intent.processing):
const completed = await orcarail.paymentIntents.complete(
'550e8400-e29b-41d4-a716-446655440000'
)
الدفع حسب الـ slug
إذا كنت تستخدم روابط دفع بـ slug، يمكنك الحصول على تفاصيل الدفع والإلغاء حسب الـ slug:
// Get pay details by slug
const pay = await orcarail.pay.get('pl_abc123')
// Cancel by slug
await orcarail.pay.cancel('pl_abc123')
الـ webhooks
تحقق من توقيعات الـ webhooks وحلّل الأحداث باستخدام الـ SDK.
التحقق من التوقيع
استخدم جسم الطلب الخام وترويسة x-webhook-signature. السر هو سر الـ webhook الخاص بك (من مفتاح API / لوحة التحكم).
import OrcaRail from '@orcarail/node'
const orcarail = new OrcaRail(apiKey, apiSecret)
const signature = req.headers['x-webhook-signature']
const rawBody = req.rawBody // must be raw string or Buffer, not parsed JSON
if (!orcarail.webhooks.verifySignature(rawBody, signature, webhookSecret)) {
return res.status(400).send('Invalid signature')
}
بناء الحدث (التحقق والتحليل)
تحقق وحلّل في خطوة واحدة؛ ويُرمى استثناء إذا كان التوقيع غير صالح:
const event = orcarail.webhooks.constructEvent(
rawBody,
req.headers['x-webhook-signature'],
webhookSecret
)
switch (event.type) {
case 'payment_intent.completed':
console.log('Payment succeeded:', event.data.object.id)
break
case 'payment_intent.processing':
console.log('Payment processing:', event.data.object.id)
break
case 'payment_intent.canceled':
console.log('Payment canceled:', event.data.object.id)
break
case 'payment_intent.requires_payment_method':
console.log('Payment needs method:', event.data.object.id)
break
default:
console.log('Unhandled event:', event.type)
}
مثال Express
const express = require('express')
const OrcaRail = require('@orcarail/node').default
const app = express()
const orcarail = new OrcaRail(
process.env.ORCARAIL_API_KEY,
process.env.ORCARAIL_API_SECRET
)
// Use raw body for signature verification
app.post(
'/webhooks/orcarail',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-webhook-signature']
const rawBody = req.body // Buffer
try {
const event = orcarail.webhooks.constructEvent(
rawBody,
signature,
process.env.ORCARAIL_WEBHOOK_SECRET
)
console.log('Event:', event.type, event.data.object.id)
res.status(200).json({ received: true })
} catch (err) {
res.status(400).send('Invalid signature')
}
}
)
مثال Next.js (App Router)
في Route Handler، اقرأ الجسم الخام وتحقق منه:
import { NextRequest, NextResponse } from 'next/server'
import OrcaRail from '@orcarail/node'
const orcarail = new OrcaRail(
process.env.ORCARAIL_API_KEY!,
process.env.ORCARAIL_API_SECRET!
)
export async function POST(request: NextRequest) {
const rawBody = await request.text()
const signature = request.headers.get('x-webhook-signature') ?? ''
try {
const event = orcarail.webhooks.constructEvent(
rawBody,
signature,
process.env.ORCARAIL_WEBHOOK_SECRET!
)
// Handle event.type and event.data.object
return NextResponse.json({ received: true })
} catch {
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 })
}
}
معالجة الأخطاء
ترمي الـ SDK أخطاء مصنّفة الأنواع يمكنك معالجتها:
import OrcaRail, {
OrcaRailError,
OrcaRailAPIError,
OrcaRailAuthenticationError,
OrcaRailSignatureVerificationError,
} from '@orcarail/node';
try {
const intent = await orcarail.paymentIntents.create({ ... });
} catch (err) {
if (err instanceof OrcaRailAuthenticationError) {
console.error('Invalid API key or secret');
} else if (err instanceof OrcaRailAPIError) {
console.error('API error:', err.statusCode, err.message);
} else if (err instanceof OrcaRailSignatureVerificationError) {
console.error('Webhook signature invalid');
} else if (err instanceof OrcaRailError) {
console.error('OrcaRail error:', err.message);
}
}
التطبيق التوضيحي
لمثال تكامل كامل (إنشاء intent، والتوجيه إلى الدفع، وصفحة النجاح، والإكمال، والـ webhooks)، راجع العرض التوضيحي مفتوح المصدر:
- المستودع: https://github.com/OrcaRail/demo
- التقنيات: Next.js، وNode.js SDK من OrcaRail، والدفع المستضاف، ونقطة نهاية webhook
انظر أيضًا
- مرجع API لـ Node SDK — كل دوال الـ SDK وأنواعها
- API الـ Payment Intents — مرجع REST
- الـ webhooks — الأحداث والإعداد
- البدء — الحساب ومفاتيح API