-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexpress-integration.ts
More file actions
196 lines (166 loc) · 5.87 KB
/
Copy pathexpress-integration.ts
File metadata and controls
196 lines (166 loc) · 5.87 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/**
* Express.js integration example for satim-node-sdk.
*
* Install deps: npm install express dotenv satim-node-sdk
*/
import express from 'express';
import {
Satim,
SatimApiError,
SatimNetworkError,
DZDToCentimes,
OrderStatus,
getLocalizedMessage,
} from '../src/index';
// Optional: npm install dotenv
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('dotenv').config();
} catch {
// dotenv is optional for this example
}
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// ─── Initialise SATIM client ──────────────────────────────────────────────────
const satim = new Satim({
username: process.env.SATIM_USERNAME ?? '',
password: process.env.SATIM_PASSWORD ?? '',
terminalId: process.env.SATIM_TERMINAL_ID ?? '',
baseUrl: process.env.SATIM_API_URL,
allowInsecureHttp: process.env.SATIM_ALLOW_INSECURE_HTTP === 'true',
sandbox: process.env.NODE_ENV !== 'production',
logger: {
info: (msg, meta) => {
// Application-owned logging — never log payloads/credentials from the SDK.
// eslint-disable-next-line no-console
console.info('[satim]', msg, meta);
},
},
});
// ─── Routes ───────────────────────────────────────────────────────────────────
/**
* POST /checkout
*
* Body: { orderId: string, amountDZD: number }
*
* Registers the order with SATIM and returns the payment URL.
*/
app.post('/checkout', async (req, res) => {
try {
const { orderId, amountDZD } = req.body as { orderId: string; amountDZD: number };
const { formUrl, orderId: satimOrderId } = await satim.registerOrder({
orderNumber: orderId,
amount: DZDToCentimes(amountDZD), // convert 5000 DZD → 500000 centimes
returnUrl: `${process.env.APP_URL}/payment/success`,
failUrl: `${process.env.APP_URL}/payment/fail`,
description: `Order ${orderId}`,
});
// Persist satimOrderId in your DB, then redirect the customer
res.json({ satimOrderId, formUrl });
} catch (err) {
handlePaymentError(err, res);
}
});
/**
* GET /payment/success?orderId=<satim-order-id>
*
* SATIM redirects here after payment. We verify the status server-side.
*/
app.get('/payment/success', async (req, res) => {
const { orderId } = req.query as { orderId: string };
if (!orderId) {
return res.status(400).json({ error: 'Missing orderId' });
}
try {
let status = await satim.getOrderStatus({ orderId });
// SATIM Sandbox Fix: Sometimes the redirect happens faster than the DB update.
// If the status is 0 (REGISTERED), wait 2 seconds and try one more time.
if (status.orderStatus === 0) {
await new Promise((resolve) => setTimeout(resolve, 2000));
status = await satim.getOrderStatus({ orderId });
}
if (satim.isPaymentSuccessful(status)) {
// ✅ Mark the order as paid in your database
return res.json({
success: true,
orderStatus: status.orderStatus,
orderNumber: status.orderNumber,
amount: status.amount,
});
}
const lang = (req.query.lang as string) || 'fr';
// Payment not successful (pending / declined)
return res.json({
success: false,
orderStatus: status.orderStatus,
message: getLocalizedMessage(status.actionCode, lang),
actionCode: status.actionCode,
reason: status.actionCodeDescription,
raw: status.raw,
});
} catch (err) {
handlePaymentError(err, res);
}
});
/**
* GET /payment/fail?orderId=<satim-order-id>
*/
app.get('/payment/fail', async (req, res) => {
const { orderId } = req.query as { orderId: string };
if (!orderId) {
return res.json({ success: false, message: 'Payment cancelled before starting' });
}
const lang = (req.query.lang as string) || 'fr';
try {
const status = await satim.getOrderStatus({ orderId });
res.json({
success: false,
message: getLocalizedMessage(status.actionCode, lang),
actionCode: status.actionCode,
reason: status.actionCodeDescription,
orderStatus: status.orderStatus,
orderId,
raw: status.raw,
});
} catch (err) {
handlePaymentError(err, res);
}
});
/**
* POST /refund
*
* Body: { orderId: string, amountDZD: number }
*/
app.post('/refund', async (req, res) => {
try {
const { orderId, amountDZD } = req.body as { orderId: string; amountDZD: number };
const result = await satim.refundOrder({
orderId,
amount: DZDToCentimes(amountDZD),
});
res.json(result);
} catch (err) {
handlePaymentError(err, res);
}
});
// ─── Error handler ────────────────────────────────────────────────────────────
function handlePaymentError(err: unknown, res: express.Response): void {
const lang = (res.req.query.lang as string) || 'fr';
if (err instanceof SatimApiError) {
res.status(422).json({
error: err.errorMessage,
message: getLocalizedMessage(err.errorCode, lang),
code: err.errorCode,
raw: err.raw,
});
} else if (err instanceof SatimNetworkError) {
res.status(502).json({ error: 'Payment gateway unreachable', details: err.message });
} else {
res.status(500).json({ error: 'Internal server error', err });
}
}
// ─── Start ────────────────────────────────────────────────────────────────────
const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
export default app;