'use strict'; const http = require('node:http'); const GATEWAY_URL = process.env.GATEWAY_URL || 'https://www.vaurapay.com'; const API_KEY = process.env.GATEWAY_KEY || 'API_KEY'; async function buatPembayaran({ amount, orderId, description }) { const idempotencyKey = 'order-' + String(orderId).replace(/[^A-Za-z0-9_.-]/g, ''); const res = await fetch(GATEWAY_URL + '/api/v1/create-payment', { method: 'POST', headers: { 'X-Api-Key': API_KEY, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify({ amount, description: description || 'Pesanan ' + orderId, fee_bearer: 'merchant', }), }); const result = await res.json(); if (!res.ok || !result.success) { throw new Error(result.message || 'Gagal membuat pembayaran (HTTP ' + res.status + ')'); } return result.data; } const server = http.createServer(async (req, res) => { const url = new URL(req.url, 'http://localhost'); if (url.pathname !== '/checkout') { res.writeHead(404).end('Buka /checkout?amount=100000&order_id=481'); return; } // Di toko, ambil nominal dari pesanan yang tersimpan. const amount = Number(url.searchParams.get('amount') || 0); const orderId = url.searchParams.get('order_id') || 'order-' + Date.now(); if (!Number.isInteger(amount) || amount <= 0) { res.writeHead(400).end('Nominal tidak valid.'); return; } try { const payment = await buatPembayaran({ amount, orderId }); // Simpan trx_id dan total_paid pada pesanan sebelum redirect. console.log('Pesanan %s -> trx_id %s', orderId, payment.trx_id); res.writeHead(302, { Location: payment.payment_url }).end(); } catch (err) { console.error(err); res.writeHead(502).end('Pembayaran gagal dibuat: ' + err.message); } }); server.listen(3000, () => console.log('Contoh checkout: http://localhost:3000/checkout?amount=100000&order_id=481'));