@yosle/tropipayjs 0.1.24 → 0.1.27

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.
package/index.js CHANGED
@@ -1,910 +1,909 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var axios = require('axios');
6
- var crypto = require('crypto');
7
- var fs = require('fs/promises');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- function _interopNamespace(e) {
12
- if (e && e.__esModule) return e;
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () { return e[k]; }
21
- });
22
- }
23
- });
24
- }
25
- n["default"] = e;
26
- return Object.freeze(n);
27
- }
28
-
29
- var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
30
- var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
31
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
32
-
33
- function handleExceptions(error) {
34
- if (error instanceof axios.AxiosError) {
35
- if (error.response) {
36
- const axiosResponse = error.response;
37
- const errorMessage = axiosResponse.data?.error?.message || "An error occurred";
38
- switch (axiosResponse.status) {
39
- case 400:
40
- case 401:
41
- case 403:
42
- case 404:
43
- return new TropipayJSException(errorMessage, axiosResponse.status, axiosResponse.data.error);
44
- case 429:
45
- return new TropipayJSException(`${errorMessage} Too many request or rate limited`, axiosResponse.status, axiosResponse.data.error);
46
- default:
47
- return new TropipayJSException(errorMessage, axiosResponse.status, axiosResponse.data.error);
48
- }
49
- }
50
- else if (error.request) {
51
- // Axios request was made but no response received (e.g., network error)
52
- return new TropipayJSException("Request failed: No response received", 500, null);
53
- }
54
- else {
55
- // Something else went wrong
56
- return new TropipayJSException("An error occurred", 500, null);
57
- }
58
- }
59
- else {
60
- return new TropipayJSException("An Unknown error occurred", 500, null);
61
- }
62
- }
63
- class TropipayJSException extends Error {
64
- code; // Status code
65
- error;
66
- message;
67
- constructor(message, code, data) {
68
- super(message);
69
- // Set the prototype explicitly.
70
- Object.setPrototypeOf(this, TropipayJSException.prototype);
71
- this.code = code;
72
- this.error = data;
73
- this.message = message;
74
- }
75
- }
76
-
77
- class TropipayHooks {
78
- tropipay;
79
- // ... hook-related functionality ...
80
- constructor(tropipayInstance) {
81
- this.tropipay = tropipayInstance;
82
- }
83
- /**
84
- * Subscribe a new hook
85
- * @param event String that represents the name of the event,
86
- * you must select from the list of available events, otherwise
87
- * it will not produce an error but it will not be executed.
88
- * For get full list of available events see endpoint
89
- * GET /api/v2/hook/events.
90
- * @param target String representing the type of event supported.
91
- * It is currently available: 'web' (allows to receive information in a url),
92
- * 'email' (allows to receive information in an email address).
93
- * @param value if the selected 'target' is email the value would be an
94
- * email address, likewise if the selected 'target' is 'web' the expected
95
- * value corresponds to a url that receives information through the
96
- * HTTP POST method.
97
- * @returns
98
- */
99
- async subscribe({ eventType, target, value, }) {
100
- if (!Tropipay.accessToken) {
101
- await this.tropipay.login();
102
- }
103
- try {
104
- const hooks = await this.tropipay.request.post(`/api/v2/hooks`, {
105
- event: eventType,
106
- target: target,
107
- value: value,
108
- }, {
109
- headers: {
110
- "Content-Type": "application/json",
111
- Authorization: `Bearer ${Tropipay.accessToken}`,
112
- Accept: "application/json",
113
- },
114
- });
115
- return hooks.data;
116
- }
117
- catch (error) {
118
- throw handleExceptions(error);
119
- }
120
- }
121
- /**
122
- * Get the subscribed hook info by his event type.
123
- * If no event type is passed, it will return
124
- * all subscribed hooks or empty Array if none exist.
125
- * @param eventType or no params for retrieving all hooks
126
- * @returns All subscribed hooks or empty Array if none exist.
127
- */
128
- async list(eventType) {
129
- if (!Tropipay.accessToken) {
130
- await this.tropipay.login();
131
- }
132
- try {
133
- const hooks = await this.tropipay.request.get(`/api/v2/hooks/${eventType || ""}`, {
134
- headers: {
135
- "Content-Type": "application/json",
136
- Authorization: `Bearer ${Tropipay.accessToken}`,
137
- Accept: "application/json",
138
- },
139
- });
140
- return hooks.data;
141
- }
142
- catch (error) {
143
- throw handleExceptions(error);
144
- }
145
- }
146
- async update(eventType, target, value) {
147
- if (!Tropipay.accessToken) {
148
- await this.tropipay.login();
149
- }
150
- try {
151
- const hooks = await this.tropipay.request.put(`/api/v2/hooks`, {
152
- event: eventType,
153
- target: target,
154
- value: value,
155
- }, {
156
- headers: {
157
- "Content-Type": "application/json",
158
- Authorization: `Bearer ${Tropipay.accessToken}`,
159
- Accept: "application/json",
160
- },
161
- });
162
- return hooks.data;
163
- }
164
- catch (error) {
165
- throw handleExceptions(error);
166
- }
167
- }
168
- async delete(eventType, target) {
169
- if (!Tropipay.accessToken) {
170
- await this.tropipay.login();
171
- }
172
- try {
173
- const hooks = await this.tropipay.request.delete(`/api/v2/hooks/${eventType}/${target}`, {
174
- headers: {
175
- "Content-Type": "application/json",
176
- Authorization: `Bearer ${Tropipay.accessToken}`,
177
- Accept: "application/json",
178
- },
179
- });
180
- return hooks.data;
181
- }
182
- catch (error) {
183
- console.trace(error);
184
- throw handleExceptions(error);
185
- }
186
- }
187
- async events() {
188
- if (!Tropipay.accessToken) {
189
- await this.tropipay.login();
190
- }
191
- try {
192
- const hooks = await this.tropipay.request.get(`/api/v2/hooks/events`, {
193
- headers: {
194
- "Content-Type": "application/json",
195
- Authorization: `Bearer ${Tropipay.accessToken}`,
196
- Accept: "application/json",
197
- },
198
- });
199
- return hooks.data;
200
- }
201
- catch (error) {
202
- throw handleExceptions(error);
203
- }
204
- }
205
- }
206
-
207
- class PaymentCard {
208
- tropipay;
209
- constructor(tropipayInstance) {
210
- this.tropipay = tropipayInstance;
211
- }
212
- /**
213
- * Create a paymentLink with the specified options.
214
- * @param payload PaymentLinkPayload Object.
215
- * @returns Promise<PaymentLink> or throws an Exception.
216
- * @see https://tpp.stoplight.io/docs/tropipay-api-doc/b3A6ODgyNTM3OQ-create-a-new-pay-link-charge
217
- */
218
- async create(payload) {
219
- if (!Tropipay.accessToken) {
220
- await this.tropipay.login();
221
- }
222
- try {
223
- const paylink = await this.tropipay.request.post("/api/v2/paymentcards", payload, {
224
- headers: {
225
- "Content-Type": "application/json",
226
- Authorization: `Bearer ${Tropipay.accessToken}`,
227
- Accept: "application/json",
228
- },
229
- });
230
- return paylink.data;
231
- }
232
- catch (error) {
233
- throw handleExceptions(error);
234
- }
235
- }
236
- /**
237
- * Shows a list of stored paymentcards created by user.
238
- * This list includes active and closed paylinks
239
- * @returns Array of paymentlinks
240
- */
241
- async list() {
242
- if (!Tropipay.accessToken) {
243
- await this.tropipay.login();
244
- }
245
- try {
246
- const paymentcards = await this.tropipay.request.get(`/api/v2/paymentcards`, {
247
- headers: {
248
- "Content-Type": "application/json",
249
- Authorization: `Bearer ${Tropipay.accessToken}`,
250
- Accept: "application/json",
251
- },
252
- });
253
- return paymentcards.data;
254
- }
255
- catch (error) {
256
- throw new Error(`Could not retrieve PaymenCards list`);
257
- }
258
- }
259
- /**
260
- * Retrieves a payment card with the specified ID.
261
- *
262
- * @param {string} id - The ID of the payment card to retrieve.
263
- * @return {Promise<any>} A Promise that resolves to the payment card data.
264
- * @throws {Error} If an error occurs while retrieving the payment card.
265
- */
266
- async get(id) {
267
- if (!Tropipay.accessToken) {
268
- await this.tropipay.login();
269
- }
270
- try {
271
- const paymentcard = await this.tropipay.request.get(`/api/v2/paymentcards/${id}`, {
272
- headers: {
273
- "Content-Type": "application/json",
274
- Authorization: `Bearer ${Tropipay.accessToken}`,
275
- Accept: "application/json",
276
- },
277
- });
278
- return paymentcard.data;
279
- }
280
- catch (error) {
281
- throw handleExceptions(error);
282
- }
283
- }
284
- /**
285
- * Deletes a payment card with the specified ID. Its a LOGIC delete
286
- * so this will delete the paymentcard from paymentcard list and
287
- * disable shortUrl but not paymentUrl
288
- * @param {string} id - The ID of the payment card to delete.
289
- * @return {Promise<any>} A Promise that resolves to the deleted payment card data.
290
- * @throws {Error} If an error occurs while deleting the payment card.
291
- */
292
- async delete(id) {
293
- if (!Tropipay.accessToken) {
294
- await this.tropipay.login();
295
- }
296
- try {
297
- const paymentcard = await this.tropipay.request.delete(`/api/v2/paymentcards/`, {
298
- headers: {
299
- "Content-Type": "application/json",
300
- Authorization: `Bearer ${Tropipay.accessToken}`,
301
- Accept: "application/json",
302
- },
303
- data: {
304
- cardId: id,
305
- },
306
- });
307
- return paymentcard.data;
308
- }
309
- catch (error) {
310
- throw handleExceptions(error);
311
- }
312
- }
313
- }
314
-
315
- class MediationPaymentCard {
316
- tropipay;
317
- constructor(tropipayInstance) {
318
- this.tropipay = tropipayInstance;
319
- }
320
- /**
321
- * (ONLY FOR BUSINESS ACCOUNTS) Create a mediation paymentcard (an escrow payment link) with the specified options.
322
- * This allows a payment to be made to persons belonging or not to the TropiPay platform with the
323
- * particularity that the payment will be held in custody or retained until it is released with
324
- * the approval of the payer.
325
- * @param payload PaymentLinkPayload Object.
326
- * @returns Promise<PaymentLink> or throws an Exception.
327
- * @see https://tpp.stoplight.io/docs/tropipay-api-doc/12a128ff971e4-creating-a-mediation-payment-card
328
- */
329
- async create(payload) {
330
- if (!Tropipay.accessToken) {
331
- await this.tropipay.login();
332
- }
333
- try {
334
- const paylink = await this.tropipay.request.post("/api/v2/paymentcards/mediation", payload, {
335
- headers: {
336
- "Content-Type": "application/json",
337
- Authorization: `Bearer ${Tropipay.accessToken}`,
338
- Accept: "application/json",
339
- },
340
- });
341
- return paylink.data;
342
- }
343
- catch (error) {
344
- throw handleExceptions(error);
345
- }
346
- }
347
- }
348
-
349
- class DepositAccounts {
350
- tropipay;
351
- constructor(tropipayInstance) {
352
- this.tropipay = tropipayInstance;
353
- }
354
- /**
355
- * List od all beneficiaries of this account
356
- * @returns Array of DepositAccounts
357
- */
358
- async list() {
359
- if (!Tropipay.accessToken) {
360
- await this.tropipay.login();
361
- }
362
- try {
363
- const deposit = await this.tropipay.request.get(`/api/v2/deposit_accounts`, {
364
- headers: {
365
- "Content-Type": "application/json",
366
- Authorization: `Bearer ${Tropipay.accessToken}`,
367
- Accept: "application/json",
368
- },
369
- });
370
- return deposit.data;
371
- }
372
- catch (error) {
373
- return handleExceptions(error);
374
- }
375
- }
376
- /**
377
- * Adds a new beneficiary to the user account.
378
- * @param payload
379
- * @returns
380
- */
381
- async create(depositAccountObj) {
382
- if (!Tropipay.accessToken) {
383
- await this.tropipay.login();
384
- }
385
- try {
386
- const deposit = await this.tropipay.request.post("/api/v2/deposit_accounts", depositAccountObj, {
387
- headers: {
388
- "Content-Type": "application/json",
389
- Authorization: `Bearer ${Tropipay.accessToken}`,
390
- Accept: "application/json",
391
- },
392
- });
393
- return deposit.data;
394
- }
395
- catch (error) {
396
- return handleExceptions(error);
397
- }
398
- }
399
- /**
400
- * This returns details of a specific
401
- * Deposit Account (beneficiary) specified by its ID
402
- * @param id
403
- * @returns
404
- */
405
- async get(id) {
406
- if (!Tropipay.accessToken) {
407
- await this.tropipay.login();
408
- }
409
- try {
410
- const deposit = await this.tropipay.request.get(`/api/v2/deposit_accounts/${id}`, {
411
- headers: {
412
- "Content-Type": "application/json",
413
- Authorization: `Bearer ${Tropipay.accessToken}`,
414
- Accept: "application/json",
415
- },
416
- });
417
- return deposit.data;
418
- }
419
- catch (error) {
420
- return handleExceptions(error);
421
- }
422
- }
423
- /**
424
- * Updates certain beneficiary data.
425
- * @param depositAccountObj
426
- * @returns
427
- */
428
- async update(depositAccountObj) {
429
- if (!Tropipay.accessToken) {
430
- await this.tropipay.login();
431
- }
432
- try {
433
- const deposit = await this.tropipay.request.put(`/api/v2/deposit_accounts/`, {
434
- headers: {
435
- "Content-Type": "application/json",
436
- Authorization: `Bearer ${Tropipay.accessToken}`,
437
- Accept: "application/json",
438
- },
439
- });
440
- return deposit.data;
441
- }
442
- catch (error) {
443
- return handleExceptions(error);
444
- }
445
- }
446
- /**
447
- * (UNTESTED) Deletes the beneficiary indicated by id
448
- * @param id
449
- * @returns
450
- */
451
- async delete(id) {
452
- if (!Tropipay.accessToken) {
453
- await this.tropipay.login();
454
- }
455
- try {
456
- const deposit = await this.tropipay.request.delete(`/api/v2/deposit_accounts/${id}`, {
457
- headers: {
458
- "Content-Type": "application/json",
459
- Authorization: `Bearer ${Tropipay.accessToken}`,
460
- Accept: "application/json",
461
- },
462
- });
463
- return deposit.data;
464
- }
465
- catch (error) {
466
- return handleExceptions(error);
467
- }
468
- }
469
- }
470
-
471
- /**
472
- * Tropipayjs is a Typescript/Javascript library for the Tropipay API.
473
- *
474
- * @author Yosleivy Baez Acosta
475
- *
476
- */
477
- class Tropipay {
478
- clientId;
479
- clientSecret;
480
- scopes;
481
- request;
482
- loginRequest;
483
- static accessToken;
484
- static refreshToken;
485
- static expiresIn;
486
- static expiresIn;
487
- serverMode;
488
- hooks;
489
- paymentCards;
490
- depositAccounts;
491
- mediationPaymentCard;
492
- /**
493
- * Initializes a new instance of the Tropipay class.
494
- *
495
- * @param {TropipayConfig} config - The configuration object.
496
- */
497
- constructor(config) {
498
- // use all scopes if none is passed
499
- if (!config?.scopes) {
500
- this.scopes = [
501
- "ALLOW_GET_PROFILE_DATA",
502
- "ALLOW_PAYMENT_IN",
503
- "ALLOW_EXTERNAL_CHARGE",
504
- "KYC3_FULL_ALLOW",
505
- "ALLOW_PAYMENT_OUT",
506
- "ALLOW_MARKET_PURCHASES",
507
- "ALLOW_GET_BALANCE",
508
- "ALLOW_GET_MOVEMENT_LIST",
509
- "ALLOW_GET_CREDENTIAL",
510
- ];
511
- }
512
- else {
513
- this.scopes = config.scopes;
514
- }
515
- if (!config.clientId || !config.clientSecret) {
516
- throw new TropipayJSException(`You must pass clientId and clientSecret in Tropipay constructor`, 400, null);
517
- }
518
- this.clientId = config.clientId;
519
- this.clientSecret = config.clientSecret;
520
- this.serverMode = config.serverMode || "Development";
521
- const tpp_env = this.serverMode === "Production"
522
- ? "https://www.tropipay.com"
523
- : "https://tropipay-dev.herokuapp.com";
524
- this.request = axios__default["default"].create({
525
- baseURL: config.customTropipayUrl || tpp_env,
526
- const tpp_env = this.serverMode === "Production"
527
- ? "https://www.tropipay.com"
528
- : "https://tropipay-dev.herokuapp.com";
529
- this.request = axios__default["default"].create({
530
- baseURL: config.customTropipayUrl || tpp_env,
531
- headers: {
532
- "Content-Type": "application/json",
533
- Accept: "application/json",
534
- Authorization: `Bearer ${Tropipay.accessToken}`,
535
- },
536
- });
537
- // Create a separate instance for login requests
538
- this.loginRequest = axios__default["default"].create({
539
- baseURL: tpp_env,
540
- headers: {
541
- "Content-Type": "application/json",
542
- Accept: "application/json",
543
- },
544
- });
545
- // Add request interceptor for Token expired
546
- this.request.interceptors.request.use(async (config) => {
547
- const currentTimestamp = Math.floor(Date.now() / 1000); // Current time in seconds
548
- if (Tropipay.expiresIn && Tropipay.expiresIn < currentTimestamp) {
549
- // Token has expired, attempt to refresh it
550
- try {
551
- await this.login();
552
- }
553
- catch (error) {
554
- // Handle token refresh error
555
- Tropipay.accessToken = null;
556
- Tropipay.refreshToken = null;
557
- throw handleExceptions(error);
558
- }
559
- }
560
- return config;
561
- }, (error) => {
562
- return Promise.reject(error);
563
- });
564
- this.hooks = new TropipayHooks(this);
565
- this.paymentCards = new PaymentCard(this);
566
- this.mediationPaymentCard = new MediationPaymentCard(this);
567
- this.depositAccounts = new DepositAccounts(this);
568
- }
569
- async login() {
570
- try {
571
- if (Tropipay.refreshToken) {
572
- const { data } = await this.loginRequest.post("/api/v2/access/token", {
573
- client_id: this.clientId,
574
- client_secret: this.clientSecret,
575
- grant_type: "refresh_token",
576
- refresh_token: Tropipay.refreshToken,
577
- }, {
578
- headers: {
579
- "Content-Type": "application/json",
580
- Accept: "application/json",
581
- },
582
- });
583
- return data;
584
- }
585
- // normal credetials login
586
- const { data } = await this.loginRequest.post("/api/v2/access/token", {
587
- client_id: this.clientId,
588
- client_secret: this.clientSecret,
589
- grant_type: "client_credentials",
590
- scope: this.scopes.join(" "), // "ALLOW_GET_PROFILE_DATA ALLOW_PAYMENT_IN ALLOW_EXTERNAL_CHARGE KYC3_FULL_ALLOW ALLOW_PAYMENT_OUT ALLOW_MARKET_PURCHASES ALLOW_GET_BALANCE ALLOW_GET_MOVEMENT_LIST ALLOW_GET_CREDENTIAL",
591
- }, {
592
- headers: {
593
- "Content-Type": "application/json",
594
- Accept: "application/json",
595
- },
596
- });
597
- Tropipay.accessToken = data.access_token;
598
- Tropipay.refreshToken = data.refresh_token;
599
- Tropipay.expiresIn = data.expires_in;
600
- Tropipay.expiresIn = data.expires_in;
601
- return data;
602
- }
603
- catch (error) {
604
- Tropipay.accessToken = null;
605
- Tropipay.refreshToken = null;
606
- Tropipay.expiresIn = null;
607
- Tropipay.expiresIn = null;
608
- throw handleExceptions(error);
609
- }
610
- }
611
- /**
612
- * Get the list of all supported countries by Tropipay.
613
- * @returns Array of Countries Data
614
- * @see https://tpp.stoplight.io/docs/tropipay-api-doc/bfac21259e2ff-getting-users-countries-list
615
- */
616
- async countries() {
617
- try {
618
- const countries = await this.request.get("/api/v2/countries");
619
- return countries.data;
620
- }
621
- catch (error) {
622
- throw handleExceptions(error);
623
- }
624
- }
625
- /**
626
- * Get user balance
627
- * @returns balance Object { balance: number, pendingIn: number, pendingOut: number }
628
- */
629
- async getBalance() {
630
- if (!Tropipay.accessToken) {
631
- await this.login();
632
- }
633
- try {
634
- const balance = await this.request.get("/api/v2/users/balance", {
635
- headers: {
636
- "Content-Type": "application/json",
637
- Authorization: `Bearer ${Tropipay.accessToken}`,
638
- Accept: "application/json",
639
- },
640
- });
641
- return balance.data;
642
- }
643
- catch (error) {
644
- throw handleExceptions(error);
645
- }
646
- }
647
- /**
648
- * Get the list of all detination countries supported by Tropipay.
649
- * Obtaining the list of valid countries to send funds to. Useful
650
- * when adding new beneficiaries to some user.
651
- *
652
- * @returns Array of Country Objects
653
- * @see https://tpp.stoplight.io/docs/tropipay-api-doc/3cfe5504f0524-getting-list-of-beneficiary-countries
654
- */
655
- async destinations() {
656
- try {
657
- const countries = await this.request.get("/api/v2/countries/destinations");
658
- return countries.data;
659
- }
660
- catch (error) {
661
- throw new Error(`Could not retrieve the destination countries list`);
662
- }
663
- }
664
- /**
665
- * Get list of all the favorites payment links.
666
- * @returns Array of account Object or throws an error
667
- */
668
- async favorites() {
669
- if (!Tropipay.accessToken) {
670
- await this.login();
671
- }
672
- try {
673
- const favoritesList = await this.request.get("/api/v2/paymentcards/favorites", {
674
- headers: {
675
- "Content-Type": "application/json",
676
- Authorization: `Bearer ${Tropipay.accessToken}`,
677
- Accept: "application/json",
678
- },
679
- });
680
- return favoritesList?.data?.rows;
681
- }
682
- catch (error) {
683
- throw handleExceptions(error);
684
- }
685
- }
686
- /**
687
- * List all account movements. You can optionaly specify
688
- * offset and limit params for pagination.
689
- * @returns
690
- */
691
- async movements(offset = 0, limit = 10) {
692
- if (!Tropipay.accessToken)
693
- await this.login();
694
- try {
695
- const movements = await this.request.get("/api/v2/movements", {
696
- params: { limit: limit, offset: offset },
697
- headers: {
698
- "Content-Type": "application/json",
699
- Accept: "application/json",
700
- Authorization: `Bearer ${Tropipay.accessToken}`,
701
- },
702
- });
703
- return movements.data;
704
- }
705
- catch (error) {
706
- throw handleExceptions(error);
707
- }
708
- }
709
- /**
710
- * Return profile data for current Tropipay account.
711
- * @returns account object
712
- */
713
- async profile() {
714
- if (!Tropipay.accessToken)
715
- await this.login();
716
- try {
717
- const profile = await this.request.get("/api/users/profile");
718
- return profile.data;
719
- }
720
- catch (error) {
721
- throw handleExceptions(error);
722
- }
723
- }
724
- /**
725
- * Obtain current Tropipay conversion rate. For example USD to EUR
726
- * targetCurrency must be 'EUR'
727
- * @param originCurrency Target currency code supported by Tropipay.
728
- * @param targetCurrency Must be 'EUR'? (not documented by Tropipay)
729
- * @returns Conversion rate (number)
730
- * @see https://tpp.stoplight.io/docs/tropipay-api-doc/85163f6f28b23-get-rate
731
- */
732
- async rates(originCurrency, targetCurrency = "EUR") {
733
- if (!Tropipay.accessToken) {
734
- await this.login();
735
- }
736
- try {
737
- const rates = await this.request.post("/api/v2/movements/get_rate", {
738
- currencyFrom: originCurrency,
739
- currencyTo: targetCurrency,
740
- }, {
741
- headers: {
742
- "Content-Type": "application/json",
743
- Accept: "application/json",
744
- Authorization: `Bearer ${Tropipay.accessToken}`,
745
- },
746
- });
747
- return rates.data.rate;
748
- }
749
- catch (error) {
750
- throw handleExceptions(error);
751
- }
752
- }
753
- /**
754
- * (ONLY in Bussiness Accounts)
755
- * An escrow payment link. This allows a payment to be made to persons
756
- * belonging or not to the TropiPay platform with the particularity
757
- * that the payment will be held in custody or retained until it is
758
- * released with the approval of the payer.
759
- * @see https://tpp.stoplight.io/docs/tropipay-api-doc/12a128ff971e4-creating-a-mediation-payment-card
760
- * @param config Payload with the payment details
761
- */
762
- async createMediationPaymentCard(config) {
763
- if (!Tropipay.accessToken)
764
- await this.login();
765
- try {
766
- const mediation = await this.request.post("/api/v2/paymentcards/mediation", config, {
767
- headers: {
768
- "Content-Type": "application/json",
769
- Authorization: `Bearer ${Tropipay.accessToken}`,
770
- Accept: "application/json",
771
- },
772
- });
773
- return mediation.data;
774
- }
775
- catch (error) {
776
- throw handleExceptions(error);
777
- }
778
- }
779
- }
780
- class ClientSideUtils {
781
- constructor(tropipayInstance) {
782
- throw Error(`Not implemented yet`);
783
- }
784
- }
785
-
786
- const MAX_IMAGE_SIZE_MB = 1;
787
-
788
- class ServerSideUtils {
789
- tropipay;
790
- constructor(tropipayInstance) {
791
- this.tropipay = tropipayInstance;
792
- }
793
- /**
794
- * Verify Topipay's signature on webhooks.
795
- * @param credentials Credential object or Tropipay instance
796
- * @param {String} originalCurrencyAmount
797
- * @param bankOrderCode
798
- * @param signature
799
- * @returns {Boolean}
800
- */
801
- static verifySignature(credentials, originalCurrencyAmount, bankOrderCode, signature) {
802
- const localSignature = crypto__namespace
803
- .createHash("sha256")
804
- .update(bankOrderCode +
805
- credentials.clientId +
806
- credentials.clientSecret +
807
- originalCurrencyAmount)
808
- .digest("hex");
809
- return localSignature === signature;
810
- }
811
- /**
812
- * Checks if the provided base64 string represents a square image.
813
- *
814
- * @param {string} base64String - The base64 string of the image
815
- * @return {Promise<boolean>} A Promise that resolves to a boolean indicating whether the image is square
816
- */
817
- static async isBase64ImageSquare(base64String) {
818
- return new Promise((resolve, reject) => {
819
- const img = new Image();
820
- img.onload = () => {
821
- // Check if the image has a 1:1 aspect ratio
822
- const isSquare = img.width === img.height;
823
- resolve(isSquare);
824
- };
825
- img.onerror = (error) => {
826
- reject(error);
827
- };
828
- img.src = base64String;
829
- });
830
- }
831
- /**
832
- * Takes a local file path and returns a base64 representation of the file content.
833
- *
834
- * @param {string} filepath - the path of the file to be converted to base64
835
- * @return {Promise<string>} a Promise that resolves to the base64 representation of the file content
836
- */
837
- static async fileToBase64(filepath) {
838
- const contents = await fs__default["default"].readFile(filepath);
839
- let base64content = contents.toString("base64");
840
- const ext = filepath.split(".").pop();
841
- return `data:image/${ext};base64,` + base64content;
842
- }
843
- /**
844
- * Get the base64 representation of a remote file from the given URL.
845
- *
846
- * @param {string} url - the URL of the file
847
- * @return {Promise<string>} the base64 representation of the file
848
- */
849
- static async getBase64FromFileUrl(url) {
850
- const response = await axios__default["default"].get(url, {
851
- responseType: "arraybuffer",
852
- maxRedirects: 5,
853
- });
854
- return Buffer.from(response.data, "binary").toString("base64");
855
- }
856
- /**
857
- * Check if the base64 string represents a valid image and has a valid size
858
- *
859
- * @param {string} base64Image - the base64 image to be validated
860
- * @return {Promise<string>} the valid base64 image
861
- */
862
- static isValidImage(base64Image) {
863
- // Check if the base64 string represents a valid image and has a valid size
864
- try {
865
- const isBase64Image = base64Image.startsWith("data:image/");
866
- if (!isBase64Image) {
867
- console.error("Not a valid base64 image");
868
- throw new Error("Not a valid base64 image");
869
- }
870
- // TODO: use constants intead of magic numbers here
871
- const isSizeLessThan2MB = base64Image.length * 0.75 <= MAX_IMAGE_SIZE_MB * 1024 * 1024;
872
- if (!isSizeLessThan2MB) {
873
- console.error(`The image should be less than 2mb`);
874
- throw new Error(`The image should be less than 2mb`);
875
- }
876
- // all is fine
877
- return true;
878
- }
879
- catch (error) {
880
- console.error("Error checking base64 image:", error);
881
- throw new Error(`Error checking base64 image`);
882
- }
883
- }
884
- }
885
-
886
- const SERVER_MODE = "Development"; // Move the constant here
887
-
888
- /**
889
- * TropipayJS is a powerful TypeScript/JavaScript library designed to provide seamless interaction
890
- * with the Tropipay API. It simplifies the process of integrating Tropipay's functionality into
891
- * your applications.
892
- *
893
- * Developed by Yosleivy Baez Acosta
894
- * GitHub: https://github.com/yosle/tropipayjs
895
- *
896
- * @version 0.1.11
897
- * @license MIT
898
- */
899
- if (typeof window !== "undefined") {
900
- const err_msg = `⚠️ **Warning:** The Tropipay SDK should only be instantiated server-side for security reasons. Using it client-side may lead to unexpected behavior and security vulnerabilities. YOUR CREDENTIALS COULD BE EXPOSED. Check https://yosle.github.io/tropipayjs-docs/guides/installation/ for more details.`;
901
- console.error(err_msg);
902
- throw new Error(err_msg);
903
- }
904
-
905
- exports.ClientSideUtils = ClientSideUtils;
906
- exports.MAX_IMAGE_SIZE_MB = MAX_IMAGE_SIZE_MB;
907
- exports.SERVER_MODE = SERVER_MODE;
908
- exports.ServerSideUtils = ServerSideUtils;
909
- exports.Tropipay = Tropipay;
910
- //# sourceMappingURL=index.js.map
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var axios = require('axios');
6
+ var crypto = require('crypto');
7
+ var fs = require('fs/promises');
8
+
9
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
+
11
+ function _interopNamespace(e) {
12
+ if (e && e.__esModule) return e;
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n["default"] = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
30
+ var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
31
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
32
+
33
+ function handleExceptions(error) {
34
+ if (error instanceof axios.AxiosError) {
35
+ if (error.response) {
36
+ const axiosResponse = error.response;
37
+ const errorMessage = axiosResponse.data?.error?.message || "An error occurred";
38
+ switch (axiosResponse.status) {
39
+ case 400:
40
+ case 401:
41
+ case 403:
42
+ case 404:
43
+ return new TropipayJSException(errorMessage, axiosResponse.status, axiosResponse.data.error);
44
+ case 429:
45
+ return new TropipayJSException(`${errorMessage} Too many request or rate limited`, axiosResponse.status, axiosResponse.data.error);
46
+ default:
47
+ return new TropipayJSException(errorMessage, axiosResponse.status, axiosResponse.data.error);
48
+ }
49
+ }
50
+ else if (error.request) {
51
+ // Axios request was made but no response received (e.g., network error)
52
+ return new TropipayJSException("Request failed: No response received", 500, null);
53
+ }
54
+ else {
55
+ // Something else went wrong
56
+ return new TropipayJSException("An error occurred", 500, null);
57
+ }
58
+ }
59
+ else {
60
+ return new TropipayJSException("An Unknown error occurred", 500, null);
61
+ }
62
+ }
63
+ class TropipayJSException extends Error {
64
+ code; // Status code
65
+ error;
66
+ message;
67
+ constructor(message, code, data) {
68
+ super(message);
69
+ // Set the prototype explicitly.
70
+ Object.setPrototypeOf(this, TropipayJSException.prototype);
71
+ this.code = code;
72
+ this.error = data;
73
+ this.message = message;
74
+ }
75
+ }
76
+
77
+ class TropipayHooks {
78
+ tropipay;
79
+ // ... hook-related functionality ...
80
+ constructor(tropipayInstance) {
81
+ this.tropipay = tropipayInstance;
82
+ }
83
+ /**
84
+ * Subscribe a new hook
85
+ * @param event String that represents the name of the event,
86
+ * you must select from the list of available events, otherwise
87
+ * it will not produce an error but it will not be executed.
88
+ * For get full list of available events see endpoint
89
+ * GET /api/v2/hook/events.
90
+ * @param target String representing the type of event supported.
91
+ * It is currently available: 'web' (allows to receive information in a url),
92
+ * 'email' (allows to receive information in an email address).
93
+ * @param value if the selected 'target' is email the value would be an
94
+ * email address, likewise if the selected 'target' is 'web' the expected
95
+ * value corresponds to a url that receives information through the
96
+ * HTTP POST method.
97
+ * @returns
98
+ */
99
+ async subscribe({ eventType, target, value, }) {
100
+ if (!Tropipay.accessToken) {
101
+ await this.tropipay.login();
102
+ }
103
+ try {
104
+ const hooks = await this.tropipay.request.post(`/api/v2/hooks`, {
105
+ event: eventType,
106
+ target: target,
107
+ value: value,
108
+ }, {
109
+ headers: {
110
+ "Content-Type": "application/json",
111
+ Authorization: `Bearer ${Tropipay.accessToken}`,
112
+ Accept: "application/json",
113
+ },
114
+ });
115
+ return hooks.data;
116
+ }
117
+ catch (error) {
118
+ throw handleExceptions(error);
119
+ }
120
+ }
121
+ /**
122
+ * Get the subscribed hook info by his event type.
123
+ * If no event type is passed, it will return
124
+ * all subscribed hooks or empty Array if none exist.
125
+ * @param eventType or no params for retrieving all hooks
126
+ * @returns All subscribed hooks or empty Array if none exist.
127
+ */
128
+ async list(eventType) {
129
+ if (!Tropipay.accessToken) {
130
+ await this.tropipay.login();
131
+ }
132
+ try {
133
+ const hooks = await this.tropipay.request.get(`/api/v2/hooks/${eventType || ""}`, {
134
+ headers: {
135
+ "Content-Type": "application/json",
136
+ Authorization: `Bearer ${Tropipay.accessToken}`,
137
+ Accept: "application/json",
138
+ },
139
+ });
140
+ return hooks.data;
141
+ }
142
+ catch (error) {
143
+ throw handleExceptions(error);
144
+ }
145
+ }
146
+ async update(eventType, target, value) {
147
+ if (!Tropipay.accessToken) {
148
+ await this.tropipay.login();
149
+ }
150
+ try {
151
+ const hooks = await this.tropipay.request.put(`/api/v2/hooks`, {
152
+ event: eventType,
153
+ target: target,
154
+ value: value,
155
+ }, {
156
+ headers: {
157
+ "Content-Type": "application/json",
158
+ Authorization: `Bearer ${Tropipay.accessToken}`,
159
+ Accept: "application/json",
160
+ },
161
+ });
162
+ return hooks.data;
163
+ }
164
+ catch (error) {
165
+ throw handleExceptions(error);
166
+ }
167
+ }
168
+ async delete(eventType, target) {
169
+ if (!Tropipay.accessToken) {
170
+ await this.tropipay.login();
171
+ }
172
+ try {
173
+ const hooks = await this.tropipay.request.delete(`/api/v2/hooks/${eventType}/${target}`, {
174
+ headers: {
175
+ "Content-Type": "application/json",
176
+ Authorization: `Bearer ${Tropipay.accessToken}`,
177
+ Accept: "application/json",
178
+ },
179
+ });
180
+ return hooks.data;
181
+ }
182
+ catch (error) {
183
+ console.trace(error);
184
+ throw handleExceptions(error);
185
+ }
186
+ }
187
+ async events() {
188
+ if (!Tropipay.accessToken) {
189
+ await this.tropipay.login();
190
+ }
191
+ try {
192
+ const hooks = await this.tropipay.request.get(`/api/v2/hooks/events`, {
193
+ headers: {
194
+ "Content-Type": "application/json",
195
+ Authorization: `Bearer ${Tropipay.accessToken}`,
196
+ Accept: "application/json",
197
+ },
198
+ });
199
+ return hooks.data;
200
+ }
201
+ catch (error) {
202
+ throw handleExceptions(error);
203
+ }
204
+ }
205
+ }
206
+
207
+ class PaymentCard {
208
+ tropipay;
209
+ constructor(tropipayInstance) {
210
+ this.tropipay = tropipayInstance;
211
+ }
212
+ /**
213
+ * Create a paymentLink with the specified options.
214
+ * @param payload PaymentLinkPayload Object.
215
+ * @returns Promise<PaymentLink> or throws an Exception.
216
+ * @see https://tpp.stoplight.io/docs/tropipay-api-doc/b3A6ODgyNTM3OQ-create-a-new-pay-link-charge
217
+ */
218
+ async create(payload) {
219
+ if (!Tropipay.accessToken) {
220
+ await this.tropipay.login();
221
+ }
222
+ try {
223
+ const paylink = await this.tropipay.request.post("/api/v2/paymentcards", payload, {
224
+ headers: {
225
+ "Content-Type": "application/json",
226
+ Authorization: `Bearer ${Tropipay.accessToken}`,
227
+ Accept: "application/json",
228
+ },
229
+ });
230
+ return paylink.data;
231
+ }
232
+ catch (error) {
233
+ throw handleExceptions(error);
234
+ }
235
+ }
236
+ /**
237
+ * Shows a list of stored paymentcards created by user.
238
+ * This list includes active and closed paylinks
239
+ * @returns Array of paymentlinks
240
+ */
241
+ async list() {
242
+ if (!Tropipay.accessToken) {
243
+ await this.tropipay.login();
244
+ }
245
+ try {
246
+ const paymentcards = await this.tropipay.request.get(`/api/v2/paymentcards`, {
247
+ headers: {
248
+ "Content-Type": "application/json",
249
+ Authorization: `Bearer ${Tropipay.accessToken}`,
250
+ Accept: "application/json",
251
+ },
252
+ });
253
+ return paymentcards.data;
254
+ }
255
+ catch (error) {
256
+ throw new Error(`Could not retrieve PaymenCards list`);
257
+ }
258
+ }
259
+ /**
260
+ * Retrieves a payment card with the specified ID.
261
+ *
262
+ * @param {string} id - The ID of the payment card to retrieve.
263
+ * @return {Promise<any>} A Promise that resolves to the payment card data.
264
+ * @throws {Error} If an error occurs while retrieving the payment card.
265
+ */
266
+ async get(id) {
267
+ if (!Tropipay.accessToken) {
268
+ await this.tropipay.login();
269
+ }
270
+ try {
271
+ const paymentcard = await this.tropipay.request.get(`/api/v2/paymentcards/${id}`, {
272
+ headers: {
273
+ "Content-Type": "application/json",
274
+ Authorization: `Bearer ${Tropipay.accessToken}`,
275
+ Accept: "application/json",
276
+ },
277
+ });
278
+ return paymentcard.data;
279
+ }
280
+ catch (error) {
281
+ throw handleExceptions(error);
282
+ }
283
+ }
284
+ /**
285
+ * Deletes a payment card with the specified ID. Its a LOGIC delete
286
+ * so this will delete the paymentcard from paymentcard list and
287
+ * disable shortUrl but not paymentUrl
288
+ * @param {string} id - The ID of the payment card to delete.
289
+ * @return {Promise<any>} A Promise that resolves to the deleted payment card data.
290
+ * @throws {Error} If an error occurs while deleting the payment card.
291
+ */
292
+ async delete(id) {
293
+ if (!Tropipay.accessToken) {
294
+ await this.tropipay.login();
295
+ }
296
+ try {
297
+ const paymentcard = await this.tropipay.request.delete(`/api/v2/paymentcards/`, {
298
+ headers: {
299
+ "Content-Type": "application/json",
300
+ Authorization: `Bearer ${Tropipay.accessToken}`,
301
+ Accept: "application/json",
302
+ },
303
+ data: {
304
+ cardId: id,
305
+ },
306
+ });
307
+ return paymentcard.data;
308
+ }
309
+ catch (error) {
310
+ throw handleExceptions(error);
311
+ }
312
+ }
313
+ }
314
+
315
+ class MediationPaymentCard {
316
+ tropipay;
317
+ constructor(tropipayInstance) {
318
+ this.tropipay = tropipayInstance;
319
+ }
320
+ /**
321
+ * (ONLY FOR BUSINESS ACCOUNTS) Create a mediation paymentcard (an escrow payment link) with the specified options.
322
+ * This allows a payment to be made to persons belonging or not to the TropiPay platform with the
323
+ * particularity that the payment will be held in custody or retained until it is released with
324
+ * the approval of the payer.
325
+ * @param payload PaymentLinkPayload Object.
326
+ * @returns Promise<PaymentLink> or throws an Exception.
327
+ * @see https://tpp.stoplight.io/docs/tropipay-api-doc/12a128ff971e4-creating-a-mediation-payment-card
328
+ */
329
+ async create(payload) {
330
+ if (!Tropipay.accessToken) {
331
+ await this.tropipay.login();
332
+ }
333
+ try {
334
+ const paylink = await this.tropipay.request.post("/api/v2/paymentcards/mediation", payload, {
335
+ headers: {
336
+ "Content-Type": "application/json",
337
+ Authorization: `Bearer ${Tropipay.accessToken}`,
338
+ Accept: "application/json",
339
+ },
340
+ });
341
+ return paylink.data;
342
+ }
343
+ catch (error) {
344
+ throw handleExceptions(error);
345
+ }
346
+ }
347
+ }
348
+
349
+ class DepositAccounts {
350
+ tropipay;
351
+ constructor(tropipayInstance) {
352
+ this.tropipay = tropipayInstance;
353
+ }
354
+ /**
355
+ * List od all beneficiaries of this account
356
+ * @returns Array of DepositAccounts
357
+ */
358
+ async list() {
359
+ if (!Tropipay.accessToken) {
360
+ await this.tropipay.login();
361
+ }
362
+ try {
363
+ const deposit = await this.tropipay.request.get(`/api/v2/deposit_accounts`, {
364
+ headers: {
365
+ "Content-Type": "application/json",
366
+ Authorization: `Bearer ${Tropipay.accessToken}`,
367
+ Accept: "application/json",
368
+ },
369
+ });
370
+ return deposit.data;
371
+ }
372
+ catch (error) {
373
+ return handleExceptions(error);
374
+ }
375
+ }
376
+ /**
377
+ * Adds a new beneficiary to the user account.
378
+ * @param payload
379
+ * @returns
380
+ */
381
+ async create(depositAccountObj) {
382
+ if (!Tropipay.accessToken) {
383
+ await this.tropipay.login();
384
+ }
385
+ try {
386
+ const deposit = await this.tropipay.request.post("/api/v2/deposit_accounts", depositAccountObj, {
387
+ headers: {
388
+ "Content-Type": "application/json",
389
+ Authorization: `Bearer ${Tropipay.accessToken}`,
390
+ Accept: "application/json",
391
+ },
392
+ });
393
+ return deposit.data;
394
+ }
395
+ catch (error) {
396
+ return handleExceptions(error);
397
+ }
398
+ }
399
+ /**
400
+ * This returns details of a specific
401
+ * Deposit Account (beneficiary) specified by its ID
402
+ * @param id
403
+ * @returns
404
+ */
405
+ async get(id) {
406
+ if (!Tropipay.accessToken) {
407
+ await this.tropipay.login();
408
+ }
409
+ try {
410
+ const deposit = await this.tropipay.request.get(`/api/v2/deposit_accounts/${id}`, {
411
+ headers: {
412
+ "Content-Type": "application/json",
413
+ Authorization: `Bearer ${Tropipay.accessToken}`,
414
+ Accept: "application/json",
415
+ },
416
+ });
417
+ return deposit.data;
418
+ }
419
+ catch (error) {
420
+ return handleExceptions(error);
421
+ }
422
+ }
423
+ /**
424
+ * Updates certain beneficiary data.
425
+ * @param depositAccountObj
426
+ * @returns
427
+ */
428
+ async update(depositAccountObj) {
429
+ if (!Tropipay.accessToken) {
430
+ await this.tropipay.login();
431
+ }
432
+ try {
433
+ const deposit = await this.tropipay.request.put(`/api/v2/deposit_accounts/`, {
434
+ headers: {
435
+ "Content-Type": "application/json",
436
+ Authorization: `Bearer ${Tropipay.accessToken}`,
437
+ Accept: "application/json",
438
+ },
439
+ });
440
+ return deposit.data;
441
+ }
442
+ catch (error) {
443
+ return handleExceptions(error);
444
+ }
445
+ }
446
+ /**
447
+ * (UNTESTED) Deletes the beneficiary indicated by id
448
+ * @param id
449
+ * @returns
450
+ */
451
+ async delete(id) {
452
+ if (!Tropipay.accessToken) {
453
+ await this.tropipay.login();
454
+ }
455
+ try {
456
+ const deposit = await this.tropipay.request.delete(`/api/v2/deposit_accounts/${id}`, {
457
+ headers: {
458
+ "Content-Type": "application/json",
459
+ Authorization: `Bearer ${Tropipay.accessToken}`,
460
+ Accept: "application/json",
461
+ },
462
+ });
463
+ return deposit.data;
464
+ }
465
+ catch (error) {
466
+ return handleExceptions(error);
467
+ }
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Tropipayjs is a Typescript/Javascript library for the Tropipay API.
473
+ *
474
+ * @author Yosleivy Baez Acosta
475
+ *
476
+ */
477
+ class Tropipay {
478
+ clientId;
479
+ clientSecret;
480
+ scopes;
481
+ request;
482
+ loginRequest;
483
+ static accessToken;
484
+ static refreshToken;
485
+ static expiresIn;
486
+ serverMode;
487
+ hooks;
488
+ paymentCards;
489
+ depositAccounts;
490
+ mediationPaymentCard;
491
+ /**
492
+ * Initializes a new instance of the Tropipay class.
493
+ *
494
+ * @param {TropipayConfig} config - The configuration object.
495
+ */
496
+ constructor(config) {
497
+ // use all scopes if none is passed
498
+ if (!config?.scopes) {
499
+ this.scopes = [
500
+ "ALLOW_GET_PROFILE_DATA",
501
+ "ALLOW_PAYMENT_IN",
502
+ "ALLOW_EXTERNAL_CHARGE",
503
+ "KYC3_FULL_ALLOW",
504
+ "ALLOW_PAYMENT_OUT",
505
+ "ALLOW_MARKET_PURCHASES",
506
+ "ALLOW_GET_BALANCE",
507
+ "ALLOW_GET_MOVEMENT_LIST",
508
+ "ALLOW_GET_CREDENTIAL",
509
+ ];
510
+ }
511
+ else {
512
+ this.scopes = config.scopes;
513
+ }
514
+ if (!config.clientId || !config.clientSecret) {
515
+ throw new TropipayJSException(`You must pass clientId and clientSecret in Tropipay constructor`, 400, null);
516
+ }
517
+ this.clientId = config.clientId;
518
+ this.clientSecret = config.clientSecret;
519
+ this.serverMode = config.serverMode || "Development";
520
+ const tpp_env = this.serverMode === "Production"
521
+ ? "https://www.tropipay.com"
522
+ : "https://tropipay-dev.herokuapp.com";
523
+ this.request = axios__default["default"].create({
524
+ baseURL: config.customTropipayUrl || tpp_env,
525
+ headers: {
526
+ "Content-Type": "application/json",
527
+ Accept: "application/json",
528
+ Authorization: `Bearer ${Tropipay.accessToken}`,
529
+ },
530
+ });
531
+ // Create a separate instance for login requests
532
+ this.loginRequest = axios__default["default"].create({
533
+ baseURL: config.customTropipayUrl || tpp_env,
534
+ headers: {
535
+ "Content-Type": "application/json",
536
+ Accept: "application/json",
537
+ Authorization: `Bearer ${Tropipay.accessToken}`,
538
+ },
539
+ });
540
+ // Add request interceptor for Token expired
541
+ this.request.interceptors.request.use(async (config) => {
542
+ const currentTimestamp = Math.floor(Date.now() / 1000); // Current time in seconds
543
+ if (Tropipay.expiresIn && Tropipay.expiresIn < currentTimestamp) {
544
+ // Token has expired, attempt to refresh it
545
+ try {
546
+ await this.login();
547
+ }
548
+ catch (error) {
549
+ // Handle token refresh error
550
+ Tropipay.accessToken = null;
551
+ Tropipay.refreshToken = null;
552
+ throw handleExceptions(error);
553
+ }
554
+ }
555
+ return config;
556
+ }, (error) => {
557
+ return Promise.reject(error);
558
+ });
559
+ this.hooks = new TropipayHooks(this);
560
+ this.paymentCards = new PaymentCard(this);
561
+ this.mediationPaymentCard = new MediationPaymentCard(this);
562
+ this.depositAccounts = new DepositAccounts(this);
563
+ }
564
+ async login() {
565
+ try {
566
+ // if (Tropipay.refreshToken) {
567
+ // const { data } = await this.loginRequest.post<LoginResponse>(
568
+ // "/api/v2/access/token",
569
+ // {
570
+ // client_id: this.clientId,
571
+ // client_secret: this.clientSecret,
572
+ // grant_type: "refresh_token",
573
+ // refresh_token: Tropipay.refreshToken,
574
+ // },
575
+ // {
576
+ // headers: {
577
+ // "Content-Type": "application/json",
578
+ // Accept: "application/json",
579
+ // },
580
+ // }
581
+ // );
582
+ // return data;
583
+ // }
584
+ // normal credetials login
585
+ const { data } = await this.loginRequest.post("/api/v2/access/token", {
586
+ client_id: this.clientId,
587
+ client_secret: this.clientSecret,
588
+ grant_type: "client_credentials",
589
+ scope: this.scopes.join(" "), // "ALLOW_GET_PROFILE_DATA ALLOW_PAYMENT_IN ALLOW_EXTERNAL_CHARGE KYC3_FULL_ALLOW ALLOW_PAYMENT_OUT ALLOW_MARKET_PURCHASES ALLOW_GET_BALANCE ALLOW_GET_MOVEMENT_LIST ALLOW_GET_CREDENTIAL",
590
+ }, {
591
+ headers: {
592
+ "Content-Type": "application/json",
593
+ Accept: "application/json",
594
+ },
595
+ });
596
+ Tropipay.accessToken = data.access_token;
597
+ Tropipay.refreshToken = data.refresh_token;
598
+ Tropipay.expiresIn = data.expires_in;
599
+ Tropipay.expiresIn = data.expires_in;
600
+ return data;
601
+ }
602
+ catch (error) {
603
+ Tropipay.accessToken = null;
604
+ Tropipay.refreshToken = null;
605
+ Tropipay.expiresIn = null;
606
+ Tropipay.expiresIn = null;
607
+ throw handleExceptions(error);
608
+ }
609
+ }
610
+ /**
611
+ * Get the list of all supported countries by Tropipay.
612
+ * @returns Array of Countries Data
613
+ * @see https://tpp.stoplight.io/docs/tropipay-api-doc/bfac21259e2ff-getting-users-countries-list
614
+ */
615
+ async countries() {
616
+ try {
617
+ const countries = await this.request.get("/api/v2/countries");
618
+ return countries.data;
619
+ }
620
+ catch (error) {
621
+ throw handleExceptions(error);
622
+ }
623
+ }
624
+ /**
625
+ * Get user balance
626
+ * @returns balance Object { balance: number, pendingIn: number, pendingOut: number }
627
+ */
628
+ async getBalance() {
629
+ if (!Tropipay.accessToken) {
630
+ await this.login();
631
+ }
632
+ try {
633
+ const balance = await this.request.get("/api/v2/users/balance", {
634
+ headers: {
635
+ "Content-Type": "application/json",
636
+ Authorization: `Bearer ${Tropipay.accessToken}`,
637
+ Accept: "application/json",
638
+ },
639
+ });
640
+ return balance.data;
641
+ }
642
+ catch (error) {
643
+ throw handleExceptions(error);
644
+ }
645
+ }
646
+ /**
647
+ * Get the list of all detination countries supported by Tropipay.
648
+ * Obtaining the list of valid countries to send funds to. Useful
649
+ * when adding new beneficiaries to some user.
650
+ *
651
+ * @returns Array of Country Objects
652
+ * @see https://tpp.stoplight.io/docs/tropipay-api-doc/3cfe5504f0524-getting-list-of-beneficiary-countries
653
+ */
654
+ async destinations() {
655
+ try {
656
+ const countries = await this.request.get("/api/v2/countries/destinations");
657
+ return countries.data;
658
+ }
659
+ catch (error) {
660
+ throw new Error(`Could not retrieve the destination countries list`);
661
+ }
662
+ }
663
+ /**
664
+ * Get list of all the favorites payment links.
665
+ * @returns Array of account Object or throws an error
666
+ */
667
+ async favorites() {
668
+ if (!Tropipay.accessToken) {
669
+ await this.login();
670
+ }
671
+ try {
672
+ const favoritesList = await this.request.get("/api/v2/paymentcards/favorites", {
673
+ headers: {
674
+ "Content-Type": "application/json",
675
+ Authorization: `Bearer ${Tropipay.accessToken}`,
676
+ Accept: "application/json",
677
+ },
678
+ });
679
+ return favoritesList?.data?.rows;
680
+ }
681
+ catch (error) {
682
+ throw handleExceptions(error);
683
+ }
684
+ }
685
+ /**
686
+ * List all account movements. You can optionaly specify
687
+ * offset and limit params for pagination.
688
+ * @returns
689
+ */
690
+ async movements(offset = 0, limit = 10) {
691
+ if (!Tropipay.accessToken)
692
+ await this.login();
693
+ try {
694
+ const movements = await this.request.get("/api/v2/movements", {
695
+ params: { limit: limit, offset: offset },
696
+ headers: {
697
+ "Content-Type": "application/json",
698
+ Accept: "application/json",
699
+ Authorization: `Bearer ${Tropipay.accessToken}`,
700
+ },
701
+ });
702
+ return movements.data;
703
+ }
704
+ catch (error) {
705
+ throw handleExceptions(error);
706
+ }
707
+ }
708
+ /**
709
+ * Return profile data for current Tropipay account.
710
+ * @returns account object
711
+ */
712
+ async profile() {
713
+ if (!Tropipay.accessToken)
714
+ await this.login();
715
+ try {
716
+ const profile = await this.request.get("/api/users/profile");
717
+ return profile.data;
718
+ }
719
+ catch (error) {
720
+ throw handleExceptions(error);
721
+ }
722
+ }
723
+ /**
724
+ * Obtain current Tropipay conversion rate. For example USD to EUR
725
+ * targetCurrency must be 'EUR'
726
+ * @param originCurrency Target currency code supported by Tropipay.
727
+ * @param targetCurrency Must be 'EUR'? (not documented by Tropipay)
728
+ * @returns Conversion rate (number)
729
+ * @see https://tpp.stoplight.io/docs/tropipay-api-doc/85163f6f28b23-get-rate
730
+ */
731
+ async rates(originCurrency, targetCurrency = "EUR") {
732
+ if (!Tropipay.accessToken) {
733
+ await this.login();
734
+ }
735
+ try {
736
+ const rates = await this.request.post("/api/v2/movements/get_rate", {
737
+ currencyFrom: originCurrency,
738
+ currencyTo: targetCurrency,
739
+ }, {
740
+ headers: {
741
+ "Content-Type": "application/json",
742
+ Accept: "application/json",
743
+ Authorization: `Bearer ${Tropipay.accessToken}`,
744
+ },
745
+ });
746
+ return rates.data.rate;
747
+ }
748
+ catch (error) {
749
+ throw handleExceptions(error);
750
+ }
751
+ }
752
+ /**
753
+ * (ONLY in Bussiness Accounts)
754
+ * An escrow payment link. This allows a payment to be made to persons
755
+ * belonging or not to the TropiPay platform with the particularity
756
+ * that the payment will be held in custody or retained until it is
757
+ * released with the approval of the payer.
758
+ * @see https://tpp.stoplight.io/docs/tropipay-api-doc/12a128ff971e4-creating-a-mediation-payment-card
759
+ * @param config Payload with the payment details
760
+ */
761
+ async createMediationPaymentCard(config) {
762
+ if (!Tropipay.accessToken)
763
+ await this.login();
764
+ try {
765
+ const mediation = await this.request.post("/api/v2/paymentcards/mediation", config, {
766
+ headers: {
767
+ "Content-Type": "application/json",
768
+ Authorization: `Bearer ${Tropipay.accessToken}`,
769
+ Accept: "application/json",
770
+ },
771
+ });
772
+ return mediation.data;
773
+ }
774
+ catch (error) {
775
+ throw handleExceptions(error);
776
+ }
777
+ }
778
+ }
779
+ class ClientSideUtils {
780
+ constructor(tropipayInstance) {
781
+ throw Error(`Not implemented yet`);
782
+ }
783
+ }
784
+
785
+ const MAX_IMAGE_SIZE_MB = 1;
786
+
787
+ class ServerSideUtils {
788
+ tropipay;
789
+ constructor(tropipayInstance) {
790
+ this.tropipay = tropipayInstance;
791
+ }
792
+ /**
793
+ * Verify Topipay's signature on webhooks.
794
+ * @param credentials Credential object or Tropipay instance
795
+ * @param {String} originalCurrencyAmount
796
+ * @param bankOrderCode
797
+ * @param signature
798
+ * @returns {Boolean}
799
+ */
800
+ static verifySignature(credentials, originalCurrencyAmount, bankOrderCode, signature) {
801
+ const localSignature = crypto__namespace
802
+ .createHash("sha256")
803
+ .update(bankOrderCode +
804
+ credentials.clientId +
805
+ credentials.clientSecret +
806
+ originalCurrencyAmount)
807
+ .digest("hex");
808
+ return localSignature === signature;
809
+ }
810
+ /**
811
+ * Checks if the provided base64 string represents a square image.
812
+ *
813
+ * @param {string} base64String - The base64 string of the image
814
+ * @return {Promise<boolean>} A Promise that resolves to a boolean indicating whether the image is square
815
+ */
816
+ static async isBase64ImageSquare(base64String) {
817
+ return new Promise((resolve, reject) => {
818
+ const img = new Image();
819
+ img.onload = () => {
820
+ // Check if the image has a 1:1 aspect ratio
821
+ const isSquare = img.width === img.height;
822
+ resolve(isSquare);
823
+ };
824
+ img.onerror = (error) => {
825
+ reject(error);
826
+ };
827
+ img.src = base64String;
828
+ });
829
+ }
830
+ /**
831
+ * Takes a local file path and returns a base64 representation of the file content.
832
+ *
833
+ * @param {string} filepath - the path of the file to be converted to base64
834
+ * @return {Promise<string>} a Promise that resolves to the base64 representation of the file content
835
+ */
836
+ static async fileToBase64(filepath) {
837
+ const contents = await fs__default["default"].readFile(filepath);
838
+ let base64content = contents.toString("base64");
839
+ const ext = filepath.split(".").pop();
840
+ return `data:image/${ext};base64,` + base64content;
841
+ }
842
+ /**
843
+ * Get the base64 representation of a remote file from the given URL.
844
+ *
845
+ * @param {string} url - the URL of the file
846
+ * @return {Promise<string>} the base64 representation of the file
847
+ */
848
+ static async getBase64FromFileUrl(url) {
849
+ const response = await axios__default["default"].get(url, {
850
+ responseType: "arraybuffer",
851
+ maxRedirects: 5,
852
+ });
853
+ return Buffer.from(response.data, "binary").toString("base64");
854
+ }
855
+ /**
856
+ * Check if the base64 string represents a valid image and has a valid size
857
+ *
858
+ * @param {string} base64Image - the base64 image to be validated
859
+ * @return {Promise<string>} the valid base64 image
860
+ */
861
+ static isValidImage(base64Image) {
862
+ // Check if the base64 string represents a valid image and has a valid size
863
+ try {
864
+ const isBase64Image = base64Image.startsWith("data:image/");
865
+ if (!isBase64Image) {
866
+ console.error("Not a valid base64 image");
867
+ throw new Error("Not a valid base64 image");
868
+ }
869
+ // TODO: use constants intead of magic numbers here
870
+ const isSizeLessThan2MB = base64Image.length * 0.75 <= MAX_IMAGE_SIZE_MB * 1024 * 1024;
871
+ if (!isSizeLessThan2MB) {
872
+ console.error(`The image should be less than 2mb`);
873
+ throw new Error(`The image should be less than 2mb`);
874
+ }
875
+ // all is fine
876
+ return true;
877
+ }
878
+ catch (error) {
879
+ console.error("Error checking base64 image:", error);
880
+ throw new Error(`Error checking base64 image`);
881
+ }
882
+ }
883
+ }
884
+
885
+ const SERVER_MODE = "Development"; // Move the constant here
886
+
887
+ /**
888
+ * TropipayJS is a powerful TypeScript/JavaScript library designed to provide seamless interaction
889
+ * with the Tropipay API. It simplifies the process of integrating Tropipay's functionality into
890
+ * your applications.
891
+ *
892
+ * Developed by Yosleivy Baez Acosta
893
+ * GitHub: https://github.com/yosle/tropipayjs
894
+ *
895
+ * @version 0.1.11
896
+ * @license MIT
897
+ */
898
+ if (typeof window !== "undefined") {
899
+ const err_msg = `⚠️ **Warning:** The Tropipay SDK should only be instantiated server-side for security reasons. Using it client-side may lead to unexpected behavior and security vulnerabilities. YOUR CREDENTIALS COULD BE EXPOSED. Check https://yosle.github.io/tropipayjs-docs/guides/installation/ for more details.`;
900
+ console.error(err_msg);
901
+ throw new Error(err_msg);
902
+ }
903
+
904
+ exports.ClientSideUtils = ClientSideUtils;
905
+ exports.MAX_IMAGE_SIZE_MB = MAX_IMAGE_SIZE_MB;
906
+ exports.SERVER_MODE = SERVER_MODE;
907
+ exports.ServerSideUtils = ServerSideUtils;
908
+ exports.Tropipay = Tropipay;
909
+ //# sourceMappingURL=index.js.map