نمونهکد Node.js¶
نمونه با Express و fetchِ خودِ Node (نسخهٔ ۱۸ به بعد).
کلاینت¶
rabinhood.js
const BASE_URL = 'https://pay.rabinhood.co/api/v2/pay/merchant';
async function request(method, path, body) {
const res = await fetch(BASE_URL + path, {
method,
headers: {
Authorization: `Bearer ${process.env.RABINHOOD_API_KEY}`,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(15000),
});
const text = await res.text();
let data;
try { data = JSON.parse(text); } catch { data = { message: text }; }
return { status: res.status, data };
}
module.exports = {
createPayment: (p) => request('POST', '/payments', {
order_id: p.orderId,
amount_toman: String(p.amountToman),
description: p.description,
callback_url: p.callbackUrl,
return_url: p.returnUrl,
}),
getPayment: (id) => request('GET', `/payments/${encodeURIComponent(id)}`),
verifyPayment: (id) => request('POST', `/payments/${encodeURIComponent(id)}/verify`),
};
سرور¶
server.js
const express = require('express');
const rabinhood = require('./rabinhood');
const app = express();
// 1. Create the payment and redirect the buyer
app.post('/checkout/:orderId', async (req, res) => {
const order = await loadOrder(req.params.orderId);
const { status, data } = await rabinhood.createPayment({
orderId: order.id,
amountToman: order.totalToman,
description: `Order ${order.id}`,
callbackUrl: 'https://shop.example/rabinhood/callback',
returnUrl: 'https://shop.example/rabinhood/return',
});
if (status !== 200) return res.status(502).send(`Payment gateway error: ${data.message}`);
await saveOrderPayment(order.id, data.payment_id);
if (data.existing && !data.pay_url) return res.send('A payment already exists for this order.');
res.redirect(data.pay_url);
});
// 2. Return page
app.get('/rabinhood/return', async (req, res) => {
const paymentId = req.query.payment_id;
if (!paymentId) return res.send('Payment not found.');
const { status, data } = await rabinhood.verifyPayment(paymentId);
if (status === 200 && data.status === 'SUCCESSFUL') {
const order = await findOrderByPayment(paymentId);
if (order && Number(data.amount_toman) === order.totalToman) {
await markOrderPaid(order.id, data); // once only
return res.send(`Payment successful. Tracking code: ${data.tracking_code ?? '-'}`);
}
}
res.send('Payment was not completed.');
});
// 3. Callback: only a notice; verify is what settles the order
app.post('/rabinhood/callback', express.json(), async (req, res) => {
const paymentId = req.body && req.body.payment_id;
if (!paymentId) return res.sendStatus(400);
res.sendStatus(200);
const { status, data } = await rabinhood.verifyPayment(paymentId);
if (status === 200 && data.status === 'SUCCESSFUL') await markOrderPaid(data.order_id, data);
});
app.listen(3000);