forked from Twint-AG/sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdev-server.js
More file actions
238 lines (209 loc) Β· 8.03 KB
/
Copy pathdev-server.js
File metadata and controls
238 lines (209 loc) Β· 8.03 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import winston from 'winston';
import { TwintClient } from './src/index.js';
// Load environment variables
dotenv.config();
const app = express();
const PORT = process.env.DEV_SERVER_PORT || 9000;
// Configure logger
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.printf(({ level, message, timestamp, ...meta }) => {
// For SOAP messages, show them clearly
if (meta.soap && process.env.SOAP_DEBUG === 'true') {
return message;
}
return winston.format.simple().transform({ level, message, timestamp, ...meta })[Symbol.for('message')];
})
),
}),
new winston.transports.File({
filename: 'dev-server.log',
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
}),
],
});
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Request logging middleware
app.use((req, _res, next) => {
logger.info(`${req.method} ${req.path}`, {
ip: req.ip,
userAgent: req.get('user-agent'),
});
next();
});
// Initialize TWINT client and server
let server;
let twintClient;
async function startServer() {
try {
// Initialize TWINT client from environment - handles everything internally
twintClient = await TwintClient.fromEnvironment({ logger });
// Add enhanced callback logging by listening to client events
twintClient.on('success', (order) => {
logger.info('π Payment callback: SUCCESS', {
event: 'payment_success',
orderId: order.id.toString(),
amount: order.amount,
reference: order.merchantTransactionReference?.toString(),
status: order.status.toString(),
transactionStatus: order.transactionStatus,
timestamp: new Date().toISOString()
});
});
twintClient.on('cancel', (order) => {
logger.warn('β Payment callback: CANCELLED', {
event: 'payment_cancelled',
orderId: order.id.toString(),
status: order.status.toString(),
reason: order.transactionStatus,
timestamp: new Date().toISOString()
});
});
twintClient.on('error', (error, order) => {
logger.error('β οΈ Payment callback: ERROR', {
event: 'payment_error',
orderId: order?.id?.toString() || 'unknown',
error: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
});
});
twintClient.on('statusChange', (order) => {
logger.info('π Payment callback: STATUS_CHANGE', {
event: 'status_change',
orderId: order.id.toString(),
status: order.status.toString(),
transactionStatus: order.transactionStatus,
timestamp: new Date().toISOString()
});
});
// Create enhanced middleware wrapper with callback logging
const enhancedMiddleware = (req, res, next) => {
// Log incoming requests
logger.info('π₯ TWINT API request', {
method: req.method,
path: req.path,
body: req.body,
query: req.query,
timestamp: new Date().toISOString()
});
// Wrap res.json to log responses
const originalJson = res.json;
res.json = function(data) {
logger.info('π€ TWINT API response', {
method: req.method,
path: req.path,
statusCode: res.statusCode,
success: data?.success,
data: data?.data ? {
orderId: data.data.id,
status: data.data.status,
amount: data.data.amount
} : null,
error: data?.error,
timestamp: new Date().toISOString()
});
return originalJson.call(this, data);
};
// Call the original TWINT middleware
return twintClient.middleware(req, res, next);
};
// Use enhanced middleware for all TWINT routes
app.use('/twint', enhancedMiddleware);
// Start server
server = app.listen(PORT, () => {
logger.info('TWINT API Server started', {
port: PORT,
environment: process.env.TWINT_ENVIRONMENT || 'INTEGRATION',
twintClient: 'CONNECTED',
});
const cashRegisterId = process.env.TWINT_CASH_REGISTER_ID;
const cashRegisterStatus = cashRegisterId
? `β (${cashRegisterId.substring(0, 8)}...)`
: 'NOT ENROLLED';
console.log(`
ββββββββββββββββββββββββββββββββββββββββββββββββββ
β TWINT Development Server β
β βββββββββββββββββββββββββββββββββββββββββββββββββ£
β API Server: http://localhost:${PORT} β
β Environment: ${process.env.TWINT_ENVIRONMENT || 'INTEGRATION'}${' '.repeat(32 - (process.env.TWINT_ENVIRONMENT || 'INTEGRATION').length)}β
β TWINT Client: CONNECTED β β
β Cash Register: ${cashRegisterStatus}${' '.repeat(30 - cashRegisterStatus.length)}β
β Logs: dev-server.log β
β SOAP Debug: ${process.env.SOAP_DEBUG === 'true' ? 'ENABLED π' : 'DISABLED'}${' '.repeat(22 - (process.env.SOAP_DEBUG === 'true' ? 'ENABLED π' : 'DISABLED').length)}β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
API Endpoints (Real TWINT):
- POST /twint/orders/start Start new order (auto-monitors)
- GET /twint/orders/:orderId Get order status
- POST /twint/orders/:orderId/stop-monitoring Stop monitoring
- POST /twint/orders/:orderId/confirm Confirm order
- POST /twint/orders/:orderId/cancel Cancel order
- GET /twint/health Health check
${process.env.SOAP_DEBUG === 'true' ? 'π SOAP debugging enabled - XML requests/responses will be shown in console' : 'π‘ Tip: Set SOAP_DEBUG=true in .env to see formatted XML requests/responses'}
`);
});
} catch (error) {
logger.error('Failed to initialize TWINT client:', error.message);
logger.error('Please check your .env configuration:');
logger.error('- TWINT_CERTIFICATE_PATH: Path to your TWINT certificate');
logger.error('- TWINT_CERTIFICATE_PASSWORD: Certificate password (if required)');
logger.error('- TWINT_STORE_UUID: Your TWINT store UUID');
logger.error('- TWINT_ENVIRONMENT: PRODUCTION, INTEGRATION, or STAGING');
logger.error('- TWINT_CASH_REGISTER_ID: Cash register ID');
process.exit(1);
}
}
// Handle shutdown gracefully
process.on('SIGTERM', async () => {
logger.info('SIGTERM received, shutting down gracefully...');
// Stop all monitoring before shutdown
if (twintClient) {
logger.info('Stopping all order monitoring...');
twintClient.stopAllMonitoring();
}
if (server) {
await new Promise((resolve) => {
server.close(resolve);
});
}
process.exit(0);
});
process.on('SIGINT', async () => {
logger.info('SIGINT received, shutting down gracefully...');
// Stop all monitoring before shutdown
if (twintClient) {
logger.info('Stopping all order monitoring...');
twintClient.stopAllMonitoring();
}
if (server) {
await new Promise((resolve) => {
server.close(resolve);
});
}
process.exit(0);
});
// Handle uncaught errors
process.on('uncaughtException', (error) => {
logger.error('Uncaught exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled rejection at:', promise, 'reason:', reason);
process.exit(1);
});
// Start the server
startServer().catch((error) => {
logger.error('Failed to start server:', error);
process.exit(1);
});