Guide
Guide JavaScript (Node.js) pour créer et payer une transaction YKNPG.
Guide JavaScript (Node.js) pour créer et payer une transaction YKNPG.
Pré-requis
- Node.js 18+, npm.
- Jeton bearer stocké dans
.envsousYKNPG_API_TOKEN.
- Initialiser le projet
mkdir -p demo_js && cd demo_jsnpm init -y
- Installer les dépendances
npm install axios dotenv
- Ajouter le fichier d'environnement
- Fichier :
.env
YKNPG_API_TOKEN=remplacez-par-votre-jeton
YKNPG_BASE_URL=https://yknpg.ngoul.com/api/v1
- Créer le script de transaction
- Fichier :
transaction.js
import axios from "axios";
import dotenv from "dotenv";
dotenv.config();
const API_TOKEN = process.env.YKNPG_API_TOKEN;
const BASE_URL = process.env.YKNPG_BASE_URL || "https://yknpg.ngoul.com/api/v1";
const client = axios.create({
baseURL: BASE_URL,
headers: { Authorization: `Bearer ${API_TOKEN}` },
timeout: 10000,
});
async function createTransaction(amount, phone) {
const payload = {
amount,
provider: "ORANGE_MONEY",
user_infos: { number: phone },
callback_url: "http://example.com",
callback_method: "POST",
your_message: "pay this",
your_order_ref: "demo-1",
provider_fees_on_customer: true,
};
const { data } = await client.post("/transactions/", payload);
return data;
}
async function payTransaction(uuid) {
const { data } = await client.post(`/transactions/${uuid}/pay/`);
return data;
}
async function pollStatus(uuid) {
let status = "new";
while (status === "new" || status === "paying") {
await new Promise((r) => setTimeout(r, 5000));
const { data } = await client.get(`/transactions/${uuid}/`);
status = data.status;
console.log("Current status:", status);
}
return status;
}
async function main() {
const phone = process.argv[2];
const amount = Number(process.argv[3]);
if (!phone || !amount) {
console.log("Usage: node transaction.js <phone> <amount>");
process.exit(1);
}
const trx = await createTransaction(amount, phone);
console.log("Gateway instructions:", trx.instructions);
const pay = await payTransaction(trx.uuid);
console.log("Post-pay instructions:", pay.instructions);
const finalStatus = await pollStatus(trx.uuid);
console.log("Final status:", finalStatus);
}
main().catch((err) => {
console.error(err.response?.data || err.message);
process.exit(1);
});
- Exécuter
node transaction.js <phone> <amount>
Remarques
- Gardez le jeton côté serveur ; pour le navigateur, appelez votre backend afin qu'il ajoute l'en-tête Authorization.