@payware/mcp-server 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/.env.example +4 -0
  2. package/README.md +18 -0
  3. package/package.json +7 -9
  4. package/src/auth/rsa-keys.js +12 -6
  5. package/src/auth/sandbox-setup.js +2 -0
  6. package/src/config/toolsets.js +104 -0
  7. package/src/core/auth/jwt-factory.js +4 -1
  8. package/src/core/auth/jwt-token.js +4 -0
  9. package/src/index.js +10 -6
  10. package/src/isv/data/index.js +15 -14
  11. package/src/isv/deep-links/delete-product-link.js +3 -2
  12. package/src/isv/deep-links/delete-transaction-link.js +3 -2
  13. package/src/isv/deep-links/get-product-link.js +8 -6
  14. package/src/isv/deep-links/get-transaction-link.js +8 -6
  15. package/src/isv/index.js +6 -0
  16. package/src/isv/invitations/index.js +5 -0
  17. package/src/isv/oauth2/get-token-info.js +10 -5
  18. package/src/isv/oauth2/obtain-token.js +9 -4
  19. package/src/isv/oauth2/token-helper.js +28 -26
  20. package/src/isv/poi/cancel-price.js +9 -2
  21. package/src/isv/poi/get-poi.js +4 -3
  22. package/src/isv/poi/get-qrcode.js +40 -9
  23. package/src/isv/poi/get-status.js +196 -168
  24. package/src/isv/poi/list-pois.js +6 -6
  25. package/src/isv/poi/set-price.js +40 -53
  26. package/src/isv/products/audios.js +8 -2
  27. package/src/isv/products/create-product.js +2 -0
  28. package/src/isv/products/delete-product.js +2 -0
  29. package/src/isv/products/get-product-image.js +2 -0
  30. package/src/isv/products/get-product.js +2 -0
  31. package/src/isv/products/list-products.js +2 -0
  32. package/src/isv/products/schedules.js +6 -0
  33. package/src/isv/products/update-product.js +2 -0
  34. package/src/isv/reference/index.js +2 -0
  35. package/src/isv/transactions/cancel-transaction.js +2 -0
  36. package/src/isv/transactions/create-transaction.js +2 -0
  37. package/src/isv/transactions/get-status.js +3 -1
  38. package/src/isv/transactions/process-transaction.js +2 -0
  39. package/src/isv/transactions/simulate-callback.js +21 -10
  40. package/src/isv/transactions/transaction-history.js +2 -0
  41. package/src/merchant/data/export-report.js +2 -0
  42. package/src/merchant/data/generate-report.js +2 -0
  43. package/src/merchant/data/get-export-list.js +2 -0
  44. package/src/merchant/data/get-report-requests.js +2 -0
  45. package/src/merchant/data/get-report-status.js +2 -0
  46. package/src/merchant/data/index.js +15 -10
  47. package/src/merchant/data/list-reports.js +2 -0
  48. package/src/merchant/deep-links/delete-product-link.js +3 -2
  49. package/src/merchant/deep-links/delete-transaction-link.js +3 -2
  50. package/src/merchant/deep-links/get-product-link.js +8 -6
  51. package/src/merchant/deep-links/get-transaction-link.js +8 -6
  52. package/src/merchant/index.js +7 -1
  53. package/src/merchant/logs/index.js +4 -0
  54. package/src/merchant/products/audios.js +15 -14
  55. package/src/merchant/products/create-product.js +3 -2
  56. package/src/merchant/products/delete-product.js +3 -2
  57. package/src/merchant/products/get-product-image.js +3 -2
  58. package/src/merchant/products/get-product.js +3 -2
  59. package/src/merchant/products/list-products.js +3 -2
  60. package/src/merchant/products/schedules.js +11 -10
  61. package/src/merchant/products/update-product.js +3 -2
  62. package/src/merchant/transactions/cancel-transaction.js +3 -2
  63. package/src/merchant/transactions/create-transaction.js +3 -1
  64. package/src/merchant/transactions/get-status.js +4 -3
  65. package/src/merchant/transactions/process-transaction.js +5 -4
  66. package/src/merchant/transactions/simulate-callback.js +325 -313
  67. package/src/merchant/transactions/transaction-history.js +7 -6
  68. package/src/payment-institution/data/index.js +15 -14
  69. package/src/payment-institution/deep-links/delete-transaction-link.js +3 -2
  70. package/src/payment-institution/deep-links/get-transaction-link.js +8 -6
  71. package/src/payment-institution/transactions/create-pi-transaction.js +4 -3
  72. package/src/payment-institution/transactions/finalize-transaction.js +6 -3
  73. package/src/payment-institution/transactions/get-transaction-history.js +8 -5
  74. package/src/payment-institution/transactions/get-transaction-status.js +16 -13
  75. package/src/payment-institution/transactions/process-pi-transaction.js +7 -6
  76. package/src/payment-institution/transactions/simulate-pi-callback.js +388 -375
  77. package/src/payment-institution/transactions/soundbite-transaction.js +6 -5
  78. package/src/proxy-server.js +25 -0
  79. package/src/shared/placements/api.js +51 -0
  80. package/src/shared/placements/tools.js +519 -0
  81. package/src/shared/poi/poi-create-api.js +4 -1
  82. package/src/shared/products/products-api.js +36 -25
  83. package/src/shared/shops/shops-api.js +2 -0
  84. package/src/shared/tool-annotations.js +53 -0
  85. package/src/tools/advanced-code-generator.js +17 -265
  86. package/src/utils/code-examples/common/auth-examples.js +1 -1
  87. package/src/utils/code-examples/isv/products.js +1 -1
  88. package/src/utils/code-examples/isv/transactions.js +1 -1
  89. package/src/utils/code-examples/merchant/transactions.js +1 -1
  90. package/src/utils/format-request.js +2 -0
  91. package/src/utils/json-formatter.js +2 -0
  92. package/src/utils/server-info.js +2 -0
  93. package/src/utils/code-examples.js +0 -646
@@ -1,646 +0,0 @@
1
- /**
2
- * Generate code examples for different programming languages
3
- *
4
- * PAYWARE REQUIREMENT: All examples must demonstrate using the EXACT same
5
- * compact JSON string for both JWT contentSha256 calculation and HTTP body.
6
- *
7
- * Examples use deterministic serialization to guarantee this consistency.
8
- */
9
-
10
- /**
11
- * Generate Python code example
12
- */
13
- function generatePythonExample(type, params = {}) {
14
- const {
15
- partnerId = 'YOUR_PARTNER_ID',
16
- amount = '10.00',
17
- currency = 'EUR',
18
- transactionType = 'PLAIN',
19
- reasonL1 = 'Test transaction',
20
- reasonL2 = ''
21
- } = params;
22
-
23
- switch (type) {
24
- case 'complete_flow':
25
- return `import requests
26
- import jwt
27
- import json
28
- import hashlib
29
- import base64
30
- from datetime import datetime, timedelta
31
- from cryptography.hazmat.primitives import serialization
32
-
33
- # Configuration
34
- PARTNER_ID = "${partnerId}"
35
- SANDBOX_URL = "https://sandbox.payware.eu/api"
36
-
37
- # Load your private key (generated earlier)
38
- with open('private_key.pem', 'r') as f:
39
- PRIVATE_KEY = f.read()
40
-
41
- def create_deterministic_json(data):
42
- """Create consistent compact JSON for payware API
43
-
44
- REQUIREMENT: The exact same string must be used for JWT contentSha256 and HTTP body.
45
- SOLUTION: Sort keys to guarantee consistent output across all platforms.
46
- """
47
- # Sort keys recursively to ensure deterministic output
48
- def sort_dict(obj):
49
- if isinstance(obj, dict):
50
- return {k: sort_dict(v) for k, v in sorted(obj.items())}
51
- elif isinstance(obj, list):
52
- return [sort_dict(item) for item in obj]
53
- else:
54
- return obj
55
-
56
- sorted_data = sort_dict(data)
57
- return json.dumps(sorted_data, separators=(',', ':'))
58
-
59
- def create_jwt_token(request_body=None):
60
- """Create JWT token for authentication with payware API"""
61
- now = int(datetime.utcnow().timestamp())
62
-
63
- # JWT header
64
- header = {
65
- 'alg': 'RS256',
66
- 'typ': 'JWT'
67
- }
68
-
69
- # Add content SHA-256 for POST requests
70
- if request_body:
71
- body_string = create_deterministic_json(request_body)
72
- content_sha256 = base64.b64encode(hashlib.sha256(body_string.encode('utf-8')).digest()).decode('utf-8')
73
- header['contentSha256'] = content_sha256
74
-
75
- # JWT payload
76
- payload = {
77
- 'iss': PARTNER_ID,
78
- 'aud': 'https://payware.eu',
79
- 'iat': now
80
- }
81
-
82
- token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers=header)
83
- return token, body_string if request_body else None
84
-
85
- def create_transaction():
86
- """Create a new transaction"""
87
- # Build request body according to payware API structure
88
- data = {
89
- 'trData': {
90
- 'amount': '${amount}',
91
- 'currency': '${currency}',
92
- 'reasonL1': '${reasonL1}'${reasonL2 ? `,
93
- 'reasonL2': '${reasonL2}'` : ''}
94
- },
95
- 'trOptions': {
96
- 'type': '${transactionType}',
97
- 'timeToLive': 120
98
- }
99
- }
100
-
101
- token, deterministic_body = create_jwt_token(data)
102
-
103
- headers = {
104
- 'Authorization': f'Bearer {token}',
105
- 'Content-Type': 'application/json',
106
- 'Api-Version': '1'
107
- }
108
-
109
- # CRITICAL: Send the EXACT same string used for JWT contentSha256 calculation
110
- # This prevents ERR_INVALID_CONTENT_HASH authentication errors
111
- response = requests.post(f"{SANDBOX_URL}/transactions", data=deterministic_body, headers=headers)
112
- return response.json()
113
-
114
- def get_transaction_status(transaction_id):
115
- """Get transaction status"""
116
- token, _ = create_jwt_token() # No body for GET request
117
-
118
- headers = {
119
- 'Authorization': f'Bearer {token}',
120
- 'Content-Type': 'application/json',
121
- 'Api-Version': '1'
122
- }
123
-
124
- response = requests.get(f"{SANDBOX_URL}/transactions/{transaction_id}", headers=headers)
125
- return response.json()
126
-
127
- # Example usage
128
- if __name__ == "__main__":
129
- try:
130
- # Create transaction
131
- transaction = create_transaction()
132
- print("Created transaction:", json.dumps(transaction, indent=2))
133
-
134
- if 'transactionId' in transaction:
135
- # Check status
136
- status = get_transaction_status(transaction['transactionId'])
137
- print("Transaction status:", json.dumps(status, indent=2))
138
- except Exception as e:
139
- print(f"Error: {e}")`;
140
-
141
- case 'auth_only':
142
- return `import jwt
143
- import hashlib
144
- import base64
145
- import json
146
- from datetime import datetime
147
-
148
- PARTNER_ID = "${partnerId}"
149
-
150
- # Load your private key
151
- with open('private_key.pem', 'r') as f:
152
- PRIVATE_KEY = f.read()
153
-
154
- def create_jwt_token(request_body=None):
155
- """Create JWT token with proper payware format"""
156
- now = int(datetime.utcnow().timestamp())
157
-
158
- # JWT header
159
- header = {
160
- 'alg': 'RS256',
161
- 'typ': 'JWT'
162
- }
163
-
164
- # Add content SHA-256 for requests with body
165
- if request_body:
166
- # PAYWARE REQUIREMENT: Same string for JWT SHA-256 and HTTP body
167
- # SOLUTION: Use deterministic serialization (sorted keys)
168
- def sort_dict(obj):
169
- if isinstance(obj, dict):
170
- return {k: sort_dict(v) for k, v in sorted(obj.items())}
171
- elif isinstance(obj, list):
172
- return [sort_dict(item) for item in obj]
173
- else:
174
- return obj
175
-
176
- sorted_data = sort_dict(request_body)
177
- body_string = json.dumps(sorted_data, separators=(',', ':'))
178
- content_sha256 = base64.b64encode(hashlib.sha256(body_string.encode('utf-8')).digest()).decode('utf-8')
179
- header['contentSha256'] = content_sha256
180
-
181
- # JWT payload
182
- payload = {
183
- 'iss': PARTNER_ID,
184
- 'aud': 'https://payware.eu',
185
- 'iat': now
186
- }
187
-
188
- return jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers=header)
189
-
190
- # Usage examples
191
- print("JWT Token for GET request:")
192
- get_token = create_jwt_token()
193
- print(f"Token: {get_token}")
194
-
195
- print("\nJWT Token for POST request with body:")
196
- sample_body = {
197
- 'trData': {
198
- 'amount': '10.00',
199
- 'currency': 'EUR',
200
- 'reasonL1': 'Test transaction'
201
- },
202
- 'trOptions': {
203
- 'type': 'PLAIN',
204
- 'timeToLive': 120
205
- }
206
- }
207
- post_token = create_jwt_token(sample_body)
208
- print(f"Token: {post_token}")`;
209
-
210
- case 'transaction_only':
211
- return `import requests
212
- import json
213
-
214
- def create_transaction(jwt_token):
215
- """Create transaction using existing JWT token"""
216
- headers = {
217
- 'Authorization': f'Bearer {jwt_token}',
218
- 'Content-Type': 'application/json',
219
- 'Api-Version': '1'
220
- }
221
-
222
- # Build request according to payware API structure
223
- data = {
224
- 'trData': {
225
- 'amount': '${amount}',
226
- 'currency': '${currency}',
227
- 'reasonL1': '${reasonL1}'${reasonL2 ? `,
228
- 'reasonL2': '${reasonL2}'` : ''}
229
- },
230
- 'trOptions': {
231
- 'type': '${transactionType}',
232
- 'timeToLive': 120
233
- }
234
- }
235
-
236
- # PAYWARE REQUIREMENT: Same string for JWT SHA-256 and HTTP body
237
- # SOLUTION: Use deterministic serialization (sorted keys)
238
- def sort_dict(obj):
239
- if isinstance(obj, dict):
240
- return {k: sort_dict(v) for k, v in sorted(obj.items())}
241
- elif isinstance(obj, list):
242
- return [sort_dict(item) for item in obj]
243
- else:
244
- return obj
245
-
246
- sorted_data = sort_dict(data)
247
- deterministic_body = json.dumps(sorted_data, separators=(',', ':'))
248
-
249
- response = requests.post(
250
- "https://sandbox.payware.eu/api/transactions",
251
- data=deterministic_body,
252
- headers=headers
253
- )
254
-
255
- return response.json()
256
-
257
- # Note: JWT token must include contentSha256 hash for the request body
258
- # Use the auth_only example to create a proper token with body hash`;
259
-
260
- default:
261
- return 'Unknown example type';
262
- }
263
- }
264
-
265
- /**
266
- * Generate Node.js code example
267
- */
268
- function generateNodeJSExample(type, params = {}) {
269
- const {
270
- partnerId = 'YOUR_PARTNER_ID',
271
- amount = '10.00',
272
- currency = 'EUR',
273
- transactionType = 'PLAIN',
274
- reasonL1 = 'Test transaction',
275
- reasonL2 = ''
276
- } = params;
277
-
278
- switch (type) {
279
- case 'complete_flow':
280
- return `const axios = require('axios');
281
- const jwt = require('jsonwebtoken');
282
- const crypto = require('crypto');
283
- const fs = require('fs');
284
-
285
- // Configuration
286
- const PARTNER_ID = '${partnerId}';
287
- const SANDBOX_URL = 'https://sandbox.payware.eu/api';
288
-
289
- // Load your private key (generated earlier)
290
- const PRIVATE_KEY = fs.readFileSync('private_key.pem', 'utf8');
291
-
292
- function createDeterministicJSON(data) {
293
- // PAYWARE REQUIREMENT: Same compact JSON for JWT SHA-256 and HTTP body
294
- // SOLUTION: Sort keys to guarantee consistent output
295
- function sortObject(obj) {
296
- if (Array.isArray(obj)) {
297
- return obj.map(item => sortObject(item));
298
- } else if (obj !== null && typeof obj === 'object') {
299
- const sorted = {};
300
- Object.keys(obj).sort().forEach(key => {
301
- sorted[key] = sortObject(obj[key]);
302
- });
303
- return sorted;
304
- }
305
- return obj;
306
- }
307
-
308
- const sortedData = sortObject(data);
309
- return JSON.stringify(sortedData);
310
- }
311
-
312
- function createJWTToken(requestBody = null) {
313
- const now = Math.floor(Date.now() / 1000);
314
-
315
- // JWT header
316
- const header = {
317
- alg: 'RS256',
318
- typ: 'JWT'
319
- };
320
-
321
- // Add content SHA-256 for POST requests
322
- let deterministicBody = null;
323
- if (requestBody) {
324
- deterministicBody = createDeterministicJSON(requestBody);
325
- const contentSha256 = crypto.createHash('sha256').update(deterministicBody, 'utf8').digest('base64');
326
- header.contentSha256 = contentSha256;
327
- }
328
-
329
- // JWT payload
330
- const payload = {
331
- iss: PARTNER_ID,
332
- aud: 'https://payware.eu',
333
- iat: now
334
- };
335
-
336
- const token = jwt.sign(payload, PRIVATE_KEY, { algorithm: 'RS256', header });
337
- return { token, deterministicBody };
338
- }
339
-
340
- async function createTransaction() {
341
- // Build request body according to payware API structure
342
- const data = {
343
- trData: {
344
- amount: '${amount}',
345
- currency: '${currency}',
346
- reasonL1: '${reasonL1}'${reasonL2 ? `,
347
- reasonL2: '${reasonL2}'` : ''}
348
- },
349
- trOptions: {
350
- type: '${transactionType}',
351
- timeToLive: 120
352
- }
353
- };
354
-
355
- const { token, deterministicBody } = createJWTToken(data);
356
-
357
- const headers = {
358
- 'Authorization': \`Bearer \${token}\`,
359
- 'Content-Type': 'application/json',
360
- 'Api-Version': '1'
361
- };
362
-
363
- try {
364
- // CRITICAL: Send the EXACT same string used for JWT contentSha256 calculation
365
- // This prevents ERR_INVALID_CONTENT_HASH authentication errors
366
- const response = await axios.post(\`\${SANDBOX_URL}/transactions\`, deterministicBody, {
367
- headers,
368
- // Tell axios to send the string as-is, don't serialize it again
369
- transformRequest: [(data) => data]
370
- });
371
- return response.data;
372
- } catch (error) {
373
- console.error('Error creating transaction:', error.response?.data || error.message);
374
- throw error;
375
- }
376
- }
377
-
378
- async function getTransactionStatus(transactionId) {
379
- const { token } = createJWTToken(); // No body for GET request
380
-
381
- const headers = {
382
- 'Authorization': \`Bearer \${token}\`,
383
- 'Content-Type': 'application/json',
384
- 'Api-Version': '1'
385
- };
386
-
387
- try {
388
- const response = await axios.get(\`\${SANDBOX_URL}/transactions/\${transactionId}\`, { headers });
389
- return response.data;
390
- } catch (error) {
391
- console.error('Error getting transaction status:', error.response?.data || error.message);
392
- throw error;
393
- }
394
- }
395
-
396
- // Example usage
397
- async function main() {
398
- try {
399
- // Create transaction
400
- const transaction = await createTransaction();
401
- console.log('Created transaction:', JSON.stringify(transaction, null, 2));
402
-
403
- if (transaction.transactionId) {
404
- // Check status
405
- const status = await getTransactionStatus(transaction.transactionId);
406
- console.log('Transaction status:', JSON.stringify(status, null, 2));
407
- }
408
- } catch (error) {
409
- console.error('Error:', error);
410
- }
411
- }
412
-
413
- main();`;
414
-
415
- case 'auth_only':
416
- return `const jwt = require('jsonwebtoken');
417
- const crypto = require('crypto');
418
- const fs = require('fs');
419
-
420
- const PARTNER_ID = '${partnerId}';
421
- const PRIVATE_KEY = fs.readFileSync('private_key.pem', 'utf8');
422
-
423
- function createJWTToken(requestBody = null) {
424
- const now = Math.floor(Date.now() / 1000);
425
-
426
- // JWT header
427
- const header = {
428
- alg: 'RS256',
429
- typ: 'JWT'
430
- };
431
-
432
- // Add content SHA-256 for requests with body
433
- if (requestBody) {
434
- // PAYWARE REQUIREMENT: Same string for JWT SHA-256 and HTTP body
435
- // SOLUTION: Use deterministic serialization (sorted keys)
436
- function sortObject(obj) {
437
- if (Array.isArray(obj)) {
438
- return obj.map(item => sortObject(item));
439
- } else if (obj !== null && typeof obj === 'object') {
440
- const sorted = {};
441
- Object.keys(obj).sort().forEach(key => {
442
- sorted[key] = sortObject(obj[key]);
443
- });
444
- return sorted;
445
- }
446
- return obj;
447
- }
448
-
449
- const sortedData = sortObject(requestBody);
450
- const bodyString = JSON.stringify(sortedData);
451
- const contentSha256 = crypto.createHash('sha256').update(bodyString, 'utf8').digest('base64');
452
- header.contentSha256 = contentSha256;
453
- }
454
-
455
- // JWT payload
456
- const payload = {
457
- iss: PARTNER_ID,
458
- aud: 'https://payware.eu',
459
- iat: now
460
- };
461
-
462
- return jwt.sign(payload, PRIVATE_KEY, { algorithm: 'RS256', header });
463
- }
464
-
465
- // Usage examples
466
- console.log('JWT Token for GET request:');
467
- const getToken = createJWTToken();
468
- console.log('Token:', getToken);
469
-
470
- console.log('\\nJWT Token for POST request with body:');
471
- const sampleBody = {
472
- trData: {
473
- amount: '10.00',
474
- currency: 'EUR',
475
- reasonL1: 'Test transaction'
476
- },
477
- trOptions: {
478
- type: 'PLAIN',
479
- timeToLive: 120
480
- }
481
- };
482
- const postToken = createJWTToken(sampleBody);
483
- console.log('Token:', postToken);`;
484
-
485
- default:
486
- return 'Unknown example type';
487
- }
488
- }
489
-
490
- /**
491
- * Generate code examples tool implementation
492
- */
493
- export const generateCodeExampleTool = {
494
- name: "payware_utils_generate_code_example",
495
- description: "Generate code examples for different programming languages and scenarios",
496
- inputSchema: {
497
- type: "object",
498
- properties: {
499
- language: {
500
- type: "string",
501
- enum: ["python", "nodejs", "javascript"],
502
- description: "Programming language for the example",
503
- default: "python"
504
- },
505
- type: {
506
- type: "string",
507
- enum: ["complete_flow", "auth_only", "transaction_only"],
508
- description: "Type of code example to generate",
509
- default: "complete_flow"
510
- },
511
- partnerId: {
512
- type: "string",
513
- description: "Partner ID to use in example",
514
- default: "YOUR_PARTNER_ID"
515
- },
516
- amount: {
517
- type: "string",
518
- description: "Transaction amount as currency value (e.g., '10.00' for €10.00)",
519
- default: "10.00"
520
- },
521
- currency: {
522
- type: "string",
523
- enum: ["EUR", "USD", "GBP"],
524
- description: "Currency for transaction examples",
525
- default: "EUR"
526
- },
527
- transactionType: {
528
- type: "string",
529
- enum: ["PLAIN", "QR", "BARCODE"],
530
- description: "Transaction type for examples",
531
- default: "PLAIN"
532
- },
533
- reasonL1: {
534
- type: "string",
535
- description: "Transaction grounds description (required field in payware API)",
536
- default: "Test transaction"
537
- },
538
- reasonL2: {
539
- type: "string",
540
- description: "Transaction grounds description continuation (optional field)",
541
- default: ""
542
- }
543
- }
544
- },
545
-
546
- async handler(args) {
547
- const {
548
- language = 'python',
549
- type = 'complete_flow',
550
- partnerId = 'YOUR_PARTNER_ID',
551
- amount = '10.00',
552
- currency = 'EUR',
553
- transactionType = 'PLAIN',
554
- reasonL1 = 'Test transaction',
555
- reasonL2 = ''
556
- } = args;
557
-
558
- const params = { partnerId, amount, currency, transactionType, reasonL1, reasonL2 };
559
-
560
- let code = '';
561
- let languageName = '';
562
- let fileExtension = '';
563
- let dependencies = '';
564
-
565
- switch (language.toLowerCase()) {
566
- case 'python':
567
- code = generatePythonExample(type, params);
568
- languageName = 'Python';
569
- fileExtension = 'py';
570
- dependencies = `# Install dependencies:
571
- # pip install requests pyjwt cryptography`;
572
- break;
573
-
574
- case 'nodejs':
575
- case 'javascript':
576
- code = generateNodeJSExample(type, params);
577
- languageName = 'Node.js';
578
- fileExtension = 'js';
579
- dependencies = `// Install dependencies:
580
- // npm install axios jsonwebtoken`;
581
- break;
582
-
583
- default:
584
- throw new Error(`Unsupported language: ${language}`);
585
- }
586
-
587
- const typeDescriptions = {
588
- 'complete_flow': 'Complete authentication and transaction flow',
589
- 'auth_only': 'Authentication (JWT token creation) only',
590
- 'transaction_only': 'Transaction creation only (requires existing JWT token)'
591
- };
592
-
593
- return {
594
- content: [{
595
- type: "text",
596
- text: `💻 **${languageName} Code Example Generated**
597
-
598
- **Type:** ${typeDescriptions[type] || type}
599
- **Language:** ${languageName}
600
-
601
- ${dependencies}
602
-
603
- **Code Example:**
604
- \`\`\`${language === 'nodejs' ? 'javascript' : language}
605
- ${code}
606
- \`\`\`
607
-
608
- **Setup Instructions:**
609
- 1. Save this code to a file (e.g., \`payware_example.${fileExtension}\`)
610
- 2. Install the required dependencies (see above)
611
- 3. Replace \`${partnerId}\` with your actual partner ID
612
- 4. Ensure you have your \`private_key.pem\` file in the same directory
613
- 5. Run the code to test the integration
614
-
615
- **⚠️ Important API Changes:**
616
- - Uses correct API endpoint: \`/api/transactions\` (not \`/api/v1/transaction\`)
617
- - Includes required \`Api-Version: 1\` header
618
- - Uses proper request body structure with \`trData\` and \`trOptions\`
619
- - JWT includes \`aud: 'https://payware.eu'\` claim
620
- - POST requests include \`contentSha256\` hash in JWT header
621
- - Amount format uses decimal strings (e.g., '10.00')
622
- - Uses \`reasonL1\`/\`reasonL2\` instead of \`description\`
623
-
624
- **Configuration Notes:**
625
- - Amount: ${amount} ${currency}
626
- - Transaction Type: ${transactionType}
627
- - Reason L1: ${reasonL1}
628
- ${reasonL2 ? `- Reason L2: ${reasonL2}` : ''}
629
- - Environment: Sandbox only
630
-
631
- **Security Reminders:**
632
- - Never hardcode private keys in production code
633
- - Use environment variables for sensitive configuration
634
- - Implement proper error handling and logging
635
- - Validate all inputs and responses
636
-
637
- **Next Steps:**
638
- 1. Test the code in your development environment
639
- 2. Modify parameters as needed for your use case
640
- 3. Add proper error handling and logging
641
- 4. Implement callback handling if needed
642
- 5. Test different transaction scenarios`
643
- }]
644
- };
645
- }
646
- };