-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
164 lines (152 loc) · 8.5 KB
/
Copy pathserver.js
File metadata and controls
164 lines (152 loc) · 8.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Advanta Quickstart — reference implementation in ~150 lines.
//
// Run: cp .env.example .env → paste your sandbox key → npm install → npm start
// Open: http://localhost:3000
//
// What this demonstrates:
// 1. POST /api/connect → creates a Connect session, returns connect_url
// 2. POST /api/webhooks/advanta → receives connection.completed webhook (signature verified)
// 3. GET /api/score/:nif → calls Advanta Score, returns formatted result
// 4. GET /api/erp/:cid/invoices → pulls invoices via the connection
//
// Storage is in-memory (Map). Replace with your DB in production.
import express from 'express';
import crypto from 'node:crypto';
import 'dotenv/config';
const app = express();
const PORT = process.env.PORT || 3000;
const ADVANTA_KEY = process.env.ADVANTA_API_KEY;
const ADVANTA_BASE = process.env.ADVANTA_BASE || 'https://sandbox.advanta.pt/v1';
const WEBHOOK_SECRET = process.env.ADVANTA_WEBHOOK_SECRET;
if (!ADVANTA_KEY) { console.error('Missing ADVANTA_API_KEY'); process.exit(1); }
// In-memory store: NIF → { connection_id, erp_provider, last_score, ... }
const customers = new Map();
// ──────────────────────────────────────────────
// Body parser — capture raw body for webhook signature verification
// ──────────────────────────────────────────────
app.use((req, res, next) => {
if (req.path === '/api/webhooks/advanta') {
let raw = '';
req.on('data', (c) => raw += c);
req.on('end', () => { req.rawBody = raw; req.body = raw ? JSON.parse(raw) : {}; next(); });
} else express.json()(req, res, next);
});
// ──────────────────────────────────────────────
// 1. Create a Connect session for an SME
// ──────────────────────────────────────────────
app.post('/api/connect', async (req, res) => {
const { nif, name, email } = req.body;
try {
const r = await fetch(`${ADVANTA_BASE}/connect/sessions`, {
method: 'POST',
headers: { Authorization: `Bearer ${ADVANTA_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
customer: { nif, name, email },
branding: 'co-branded',
scopes: ['invoices:read', 'receivables:read', 'saft:read'],
redirect_url: `http://localhost:${PORT}/connect/done`,
metadata: { bank_customer_id: `BANCO-${nif}` },
}),
});
if (!r.ok) throw new Error(`Advanta returned ${r.status}: ${await r.text()}`);
const session = await r.json();
res.json({ connect_url: session.connect_url, session_id: session.session_id });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// ──────────────────────────────────────────────
// 2. Webhook endpoint — receives connection.completed et al
// ──────────────────────────────────────────────
function verifySignature(payload, header, secret) {
if (!header || !secret) return false;
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
const t = parts.t, v1 = parts.v1;
if (!t || !v1) return false;
if (Date.now() / 1000 - parseInt(t, 10) > 300) return false; // 5-min replay tolerance
const expected = crypto.createHmac('sha256', secret).update(`${t}.${payload}`).digest('hex');
try { return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1)); }
catch { return false; }
}
app.post('/api/webhooks/advanta', (req, res) => {
const sig = req.headers['advanta-signature'];
if (!verifySignature(req.rawBody, sig, WEBHOOK_SECRET)) {
return res.status(400).json({ error: 'invalid_signature' });
}
const event = req.body;
console.log(`[webhook] ${event.type} — ${event.id}`);
switch (event.type) {
case 'connection.completed': {
const { nif, connection_id, erp_provider, company_name } = event.data;
customers.set(nif, { ...(customers.get(nif) || {}), nif, name: company_name, connection_id, erp_provider, connected_at: new Date() });
console.log(` ✓ ${company_name} (NIF ${nif}) connected via ${erp_provider}`);
break;
}
case 'invoice.created': {
const cid = event.data.connection_id;
const customer = [...customers.values()].find((c) => c.connection_id === cid);
if (customer) console.log(` • ${customer.name} issued FT ${event.data.invoice.external_id} for €${event.data.invoice.amount}`);
break;
}
case 'score.deteriorating': {
console.warn(` ⚠ score drop for NIF ${event.data.nif}: now ${event.data.score}`);
break;
}
default:
console.log(' (unhandled event type)');
}
res.sendStatus(200); // ack within 10s — process async if you need more time
});
// ──────────────────────────────────────────────
// 3. Get a score for an SME
// ──────────────────────────────────────────────
app.get('/api/score/:nif', async (req, res) => {
try {
const r = await fetch(`${ADVANTA_BASE}/score`, {
method: 'POST',
headers: { Authorization: `Bearer ${ADVANTA_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ nif: req.params.nif, product: 'factoring', horizon_days: 90 }),
});
const score = await r.json();
if (!r.ok) return res.status(r.status).json(score);
customers.set(req.params.nif, { ...(customers.get(req.params.nif) || {}), last_score: score });
res.json(score);
} catch (e) { res.status(500).json({ error: e.message }); }
});
// ──────────────────────────────────────────────
// 4. List invoices for a connected ERP
// ──────────────────────────────────────────────
app.get('/api/erp/:connectionId/invoices', async (req, res) => {
try {
const url = new URL(`${ADVANTA_BASE}/erp/${req.params.connectionId}/invoices`);
url.searchParams.set('status', req.query.status || 'open');
url.searchParams.set('limit', req.query.limit || '50');
const r = await fetch(url, { headers: { Authorization: `Bearer ${ADVANTA_KEY}` } });
res.status(r.status).json(await r.json());
} catch (e) { res.status(500).json({ error: e.message }); }
});
// ──────────────────────────────────────────────
// Bonus: a tiny dashboard so you can see the moving parts
// ──────────────────────────────────────────────
app.get('/', (_req, res) => {
const list = [...customers.values()].map((c) => `
<li><b>${c.name || c.nif}</b> · NIF ${c.nif} ·
${c.connection_id ? `connected via ${c.erp_provider}` : '<i>not connected</i>'} ·
${c.last_score ? `score ${c.last_score.score} (${c.last_score.tier})` : '<i>no score yet</i>'}
</li>`).join('') || '<i>no customers yet — POST /api/connect to create one</i>';
res.type('html').send(`<!doctype html>
<title>Advanta Quickstart</title>
<style>body{font-family:system-ui;max-width:780px;margin:40px auto;padding:0 20px;color:#0f172a}
code{background:#f1f5f9;padding:2px 6px;border-radius:4px;font-size:13px}
li{padding:8px 0;border-bottom:1px solid #e2e8f0}
.tier-A{color:#059669}.tier-B{color:#d97706}.tier-C{color:#dc2626}</style>
<h1>Advanta Quickstart</h1>
<p>Reference implementation. POST <code>/api/connect</code> with <code>{nif, name, email}</code> to start. Webhooks land at <code>/api/webhooks/advanta</code>.</p>
<h2>Customers</h2><ul>${list}</ul>
<h2>Try it (curl)</h2>
<pre>curl -X POST localhost:${PORT}/api/connect -H 'Content-Type: application/json' \\
-d '{"nif":"509123456","name":"Construções Ibéricas","email":"joao@construcoes.pt"}'</pre>
<p>Then: <code>GET /api/score/509123456</code> · <code>GET /api/erp/{connection_id}/invoices</code></p>
`);
});
app.listen(PORT, () => console.log(`✨ Advanta Quickstart on http://localhost:${PORT}`));