Guides
Code prêt à copier
Client minimal et webhook complet en Node.js, PHP et Python.
Pas de bibliothèque à installer : l’API est du HTTP + JSON. Ces exemples complets suffisent. Adaptez seulement les fonctions de votre base de données (findOrder, markPaid…).
Ce qu’il faut ajouter à vos commandes
| Champ | Type | Contenu |
|---|---|---|
nangu_payment_id | texte | pay_… renvoyé à la création |
amount_due | entier | montant exact à faire payer |
payment_status | texte | pending · paid · expired · canceled |
paid_at | date | date de confirmation |
Et une table des événements déjà traités (event_id unique, received_at).
Client et création du paiement
// nangu.js : client minimal (Node 18+, sans dépendance)
const API = process.env.NANGU_API_URL;
const KEY = process.env.NANGU_SECRET_KEY;
export async function nangu(method, path, body, idempotencyKey) {
const headers = { Authorization: `Bearer ${KEY}`, Accept: "application/json" };
if (body) headers["Content-Type"] = "application/json";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
for (let attempt = 0; ; attempt++) {
const res = await fetch(API + path, { method, headers, body: body && JSON.stringify(body), signal: AbortSignal.timeout(30000) })
.catch((e) => ({ networkError: e }));
const retry = res.networkError || res.status >= 500 || res.status === 429;
if (retry && attempt < 2) { await new Promise((r) => setTimeout(r, 500 * 2 ** attempt)); continue; }
if (res.networkError) throw res.networkError;
const data = await res.json();
if (!res.ok) throw Object.assign(new Error(data.error?.message), { status: res.status, ...data.error });
return data;
}
}
// Créer le paiement d'une commande, puis envoyer le client sur la page de paiement
app.post("/orders/:id/pay", express.json(), async (req, res) => {
const order = await findOrder(req.params.id);
if (order.payment_status === "paid") return res.redirect(`/orders/${order.id}`);
const payment = await nangu("POST", "/v1/payments", {
amount: order.total,
reference: `CMD-${order.id}`,
customer_phone: order.customerPhone || undefined,
expires_in: 3600,
metadata: { order_id: String(order.id) },
}, `commande-${order.id}`);
await saveOrder(order.id, { nangu_payment_id: payment.id, amount_due: payment.amount_due, payment_status: "pending" });
res.redirect(payment.checkout_url);
});Réception du webhook
La fonction de vérification de signature :
import crypto from "node:crypto";
/** Vérifie X-Signature sur le corps BRUT (Buffer) et renvoie l'événement, ou lève une erreur. */
export function constructEvent(rawBody, header, secret, toleranceSec = 300) {
const t = /(?:^|,)t=(\d+)/.exec(header ?? "")?.[1];
const v1 = /(?:^|,)v1=([0-9a-f]{64})/.exec(header ?? "")?.[1];
if (!t || !v1) throw new Error("X-Signature absent ou mal formé");
if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) throw new Error("Horodatage trop ancien");
const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody.toString("utf8")}`).digest();
if (!crypto.timingSafeEqual(expected, Buffer.from(v1, "hex"))) throw new Error("Signature invalide");
return JSON.parse(rawBody.toString("utf8"));
}La route qui la reçoit :
// Corps BRUT obligatoire (express.raw), avant tout express.json()
app.post("/webhooks/nangu", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = constructEvent(req.body, req.get("X-Signature"), process.env.NANGU_WEBHOOK_SECRET);
} catch {
return res.sendStatus(400);
}
if (await eventAlreadyProcessed(event.id)) return res.sendStatus(200);
const p = event.data.payment;
const orderId = p?.metadata?.order_id;
if (orderId) {
if (event.type === "payment.succeeded") await markPaid(orderId, p.id, p.succeeded_at); // sans effet si déjà payée
if (event.type === "payment.expired") await markIfPending(orderId, "expired");
if (event.type === "payment.canceled") await markIfPending(orderId, "canceled");
}
await saveProcessedEvent(event.id);
res.sendStatus(200);
});Applications mobiles
Une application Flutter, Android ou iOS ne crée jamais le paiement elle-même : elle demande à votre serveur, qui détient la clé secrète, puis ouvrecheckout_url, pay_url ou affiche le QR code.