Skip to content

Node.js and Express: integrate Senfenico

Collect Orange Money and Moov Money with Node.js 18+, Express and the built-in fetch, with no SDK, from the checkout to the signed webhook and the reconciliation script.

Install the dependencies with npm install express better-sqlite3, add "type": "module" to package.json, then set your environment variables:

Fenêtre de terminal
export SENFENICO_SECRET_KEY=sk_test_...
export SENFENICO_WEBHOOK_SECRET=your_webhook_secret_key
export APP_URL=https://shop.example

SENFENICO_WEBHOOK_SECRET is the Signing secret shown on the dashboard’s Developer › Webhooks page. The secret key stays on the server and is never sent to the browser.

db.js
import Database from 'better-sqlite3';
export const db = new Database('shop.sqlite');
db.exec(`
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY,
amount INTEGER NOT NULL, -- XOF, integer
status TEXT NOT NULL DEFAULT 'pending',
senfenico_reference TEXT UNIQUE, -- opaque string
checkout_url TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS webhook_deliveries (
id TEXT PRIMARY KEY, -- X-Senfenico-Delivery
received_at TEXT DEFAULT CURRENT_TIMESTAMP
);
`);
senfenico.js
import { db } from './db.js';
const BASE = 'https://api.senfenico.com/v1/payment';
export class SenfenicoError extends Error {
constructor(message, { http = 0, code, errors } = {}) {
super(message);
this.http = http; // 0 = no HTTP response
this.code = code; // API error_code
this.errors = errors; // validation errors
}
}
export async function senfenico(method, path, body) {
const res = await fetch(BASE + path, {
method,
headers: {
'X-API-KEY': process.env.SENFENICO_SECRET_KEY,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
// a create call may wait for the operator's answer
signal: AbortSignal.timeout(method === 'GET' ? 20_000 : 90_000),
});
const json = await res.json().catch(() => ({})); // e.g. HTML 500
// Success = HTTP 2xx AND status strictly true
if (res.ok && json.status === true) return json;
throw new SenfenicoError(json.message ?? `HTTP ${res.status}`, {
http: res.status,
code: json.error_code,
errors: json.errors,
});
}
const ref = (r) => encodeURIComponent(r);
/** Verifies the payment with the API, marks the order paid. */
export async function confirmOrder(order) {
if (order.status === 'paid') return true;
const { data: chk } = await senfenico(
'GET', `/checkouts/${ref(order.senfenico_reference)}/`,
);
// The checkout can stay "pending" while its charge
// succeeded: check the charge too.
let paid = chk.status === 'success';
if (!paid && chk.charge_reference) {
const { data: charge } = await senfenico(
'GET', `/charges/${ref(chk.charge_reference)}/`,
);
paid = charge.status === 'success';
}
if (!paid) return false;
if (chk.amount !== order.amount) {
console.error('Senfenico: amount mismatch', order.id);
return false;
}
// Conditional update: the order can only be fulfilled once
const result = db.prepare(
`UPDATE orders SET status = 'paid'
WHERE id = ? AND status IN ('pending', 'expired')`,
).run(order.id);
if (result.changes === 1) await fulfillOrder(order);
return true;
}
async function fulfillOrder(order) {
// send the email, unlock the product, etc.
}
export function findOrderByReference(reference) {
return db.prepare(
'SELECT * FROM orders WHERE senfenico_reference = ?',
).get(String(reference ?? ''));
}

The client tests res.ok and json.status === true, because an invalid key returns "status": "False" as a string (see Missing or invalid key).

A timeout throws a DOMException named TimeoutError, and a network failure throws a TypeError. A read (GET) can be retried safely. For a create call, first check whether the object exists (see error handling).

The webhook route uses express.raw() and must be declared before app.use(express.json()), otherwise the raw body is consumed and the signature no longer matches.

server.js
import crypto from 'node:crypto';
import express from 'express';
import { db } from './db.js';
import {
senfenico, confirmOrder, findOrderByReference, SenfenicoError,
} from './senfenico.js';
const app = express();
const SECRET = process.env.SENFENICO_WEBHOOK_SECRET;
const APP_URL = process.env.APP_URL;
// ---- 1. Webhook (raw body) -----------------------------------
function verifySenfenico(rawBody, timestamp, signature, secret,
toleranceSec = 300) {
if (!timestamp || !signature || !signature.startsWith('v1=')) {
return false;
}
const ts = Number(timestamp);
if (!Number.isInteger(ts)
|| Math.abs(Date.now() / 1000 - ts) > toleranceSec) return false;
const expected = crypto.createHmac('sha256', secret)
.update(`${timestamp}.`).update(rawBody).digest('hex');
const a = Buffer.from(expected);
const b = Buffer.from(signature.slice(3));
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
app.post('/webhooks/senfenico',
express.raw({ type: 'application/json' }),
(req, res) => {
const ok = verifySenfenico(
req.body,
req.get('X-Senfenico-Timestamp'),
req.get('X-Senfenico-Signature'),
SECRET,
);
if (!ok) return res.sendStatus(400);
// Same X-Senfenico-Delivery on every retry: duplicate?
const delivery = req.get('X-Senfenico-Delivery') ?? '';
if (delivery) {
const { changes } = db.prepare(
'INSERT OR IGNORE INTO webhook_deliveries (id) VALUES (?)',
).run(delivery);
if (changes === 0) return res.sendStatus(200);
}
const event = JSON.parse(req.body);
const data = typeof event.data === 'string' // JSON string
? JSON.parse(event.data)
: event.data;
res.sendStatus(200); // answer within 5 s
handleEvent(event.event, data).catch((err) => {
// the reconciliation script will catch the order
console.error('Senfenico webhook', err);
});
});
async function handleEvent(name, data) {
let checkoutRef = null;
if (name === 'checkout.success') {
checkoutRef = data.reference;
} else if (name === 'charge.success') {
// was the charge created by a checkout?
const q = new URLSearchParams({ charge_reference: data.reference });
const list = await senfenico('GET', `/checkouts/?${q}`);
checkoutRef = list.data[0]?.reference ?? null;
}
if (!checkoutRef) return; // other events ignored
const order = findOrderByReference(checkoutRef);
if (order) await confirmOrder(order);
}
// ---- 2. Regular routes ---------------------------------------
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post('/orders/:id/pay', async (req, res, next) => {
try {
// also check that the order belongs to the customer
const order = db.prepare(
"SELECT * FROM orders WHERE id = ? AND status = 'pending'",
).get(Number(req.params.id));
if (!order) return res.status(404).send('Order not found.');
// A checkout already exists: reuse it
if (order.checkout_url) return res.redirect(303, order.checkout_url);
const { data } = await senfenico('POST', '/checkouts/initialize/', {
amount: order.amount, // integer, min. 100
// No "?": Senfenico appends ?reference=...
success_url: `${APP_URL}/checkout/return`,
cancel_url: `${APP_URL}/checkout/cancel`,
});
db.prepare(
`UPDATE orders SET senfenico_reference = ?, checkout_url = ?
WHERE id = ?`,
).run(data.reference, data.authorization_url, order.id);
res.redirect(303, data.authorization_url);
} catch (err) {
next(err);
}
});
app.get('/checkout/return', async (req, res, next) => {
// ?reference= finds the order; it does not prove payment,
// so we verify with the API.
const order = findOrderByReference(req.query.reference);
if (!order) return res.status(404).send('Order not found.');
try {
const paid = await confirmOrder(order);
res.send(paid
? 'Thank you! Your payment is confirmed.'
: 'Payment being verified.');
} catch (err) {
next(err);
}
});
app.get('/checkout/cancel', (req, res) => {
const order = findOrderByReference(req.query.reference);
if (!order) return res.status(404).send('Order not found.');
res.redirect(`/orders/${order.id}`); // offer to try again
});
app.use((err, req, res, next) => {
console.error(err);
const msg = err instanceof SenfenicoError
? 'Payment unavailable, please try again shortly.'
: 'Internal error.';
res.status(502).send(msg);
});
app.listen(3000, () => console.log('http://localhost:3000'));

POST /v1/payment/checkouts/initialize/ (HTTP 201):

{
"status": true,
"message": "Checkout initialized",
"data": {
"reference": "CHK261126-101431--3f9a0c1d2e",
"authorization_url": "https://api.senfenico.com/v1/checkout_payment/payment_page/CHK261126-101431--3f9a0c1d2e/",
"live_mode": false
}
}

GET /v1/payment/checkouts/{reference}/ after payment:

{
"status": true,
"message": "Checkout details retrieved",
"data": {
"email": null,
"reference": "CHK261126-101431--3f9a0c1d2e",
"charge_reference": "CH261126-101502-ORANGE_BF-8b41079ee8",
"amount": 1000,
"success_url": "https://shop.example/checkout/return",
"cancel_url": "https://shop.example/checkout/cancel",
"phone": "76000000",
"provider": "orange_bf",
"live_mode": false,
"created_at": "2026-11-26T10:14:31.512345Z",
"updated_at": "2026-11-26T10:15:02.104512Z",
"status": "success"
}
}

Checkout accepts neither ext_id nor metadata, so store its reference on the order. Treat references as opaque strings, without testing their format.

On the dashboard Developer › Webhooks page, add https://shop.example/webhooks/senfenico for checkout.success and charge.success, in test mode then live mode. Confirm the payment server-side explains why checkout.success alone is not enough. Locally, expose port 3000 with a tunnel (ngrok, Cloudflare Tunnel), because private URLs are rejected.

// reconcile.js — crontab: */15 * * * * node /app/reconcile.js
import { db } from './db.js';
import { confirmOrder } from './senfenico.js';
const orders = db.prepare(`
SELECT * FROM orders
WHERE status = 'pending' AND senfenico_reference IS NOT NULL
AND created_at < datetime('now', '-10 minutes')
AND created_at > datetime('now', '-2 days')
`).all();
for (const order of orders) {
try {
await confirmOrder(order);
} catch (err) {
console.error(`Reconcile ${order.id}:`, err.message);
}
}

Webhooks are only retried for about an hour. This script catches orders whose webhook was lost.

With an sk_test_ key, create an order for the amount paired with a test number, pay on the page, then check the order moves to paid: