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