@yosle/tropipayjs
Advanced tools
Comparing version 0.1.9 to 0.1.10
@@ -0,0 +0,0 @@ # Tropipayjs |
@@ -0,0 +0,0 @@ type LoginResponse = { |
177
index.d.ts
import { Axios } from 'axios'; | ||
type ServerMode$1 = "Development" | "Production"; | ||
type AccountBalance = { | ||
balance: number; | ||
pendingIn: number; | ||
pendingOut: number; | ||
}; | ||
interface TropipayConfig { | ||
clientId: string; | ||
clientSecret: string; | ||
serverMode?: ServerMode$1; | ||
} | ||
type TropipayCredentials = { | ||
clientId: string; | ||
clientSecret: string; | ||
}; | ||
type HookEventType = "transaction_completed" | "transaction_charged" | "transaction_guarded"; | ||
type HookTargetType = "web" | "email"; | ||
interface UserHook { | ||
event: HookEventType; | ||
target: string; | ||
value: string; | ||
} | ||
interface UserHook { | ||
event: HookEventType; | ||
target: string; | ||
value: string; | ||
} | ||
interface UserHookSubscribed extends UserHook { | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
interface UserHookSubscribed extends UserHook { | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
interface PaymentLinkPayload { | ||
@@ -39,6 +75,2 @@ reference: string; | ||
} | ||
/** | ||
* | ||
*/ | ||
interface mediationPaymentCardConfig { | ||
@@ -63,3 +95,88 @@ amount: number; | ||
} | ||
type LoginResponse = { | ||
access_token: string; | ||
refresh_token: string; | ||
token_type: "Bearer"; | ||
expires_in: number; | ||
scope: string; | ||
}; | ||
type LoginError = { | ||
error: string; | ||
}; | ||
type Country = { | ||
id: number; | ||
name: string; | ||
sepaZone: boolean; | ||
state: number; | ||
slug: string; | ||
slugn: number; | ||
callingCode: number; | ||
isDestination: boolean; | ||
isRisky: boolean; | ||
currentCurrency: string | null; | ||
createdAt: string; | ||
updatedAt: string; | ||
isFavorite: boolean; | ||
position: any; | ||
}; | ||
type Deposit = { | ||
id: number; | ||
accountNumber: string; | ||
alias: string; | ||
swift: string; | ||
type: number; | ||
country: number | null; | ||
firstName: string; | ||
default: null; | ||
state: number; | ||
userId: string; | ||
countryDestinationId: number; | ||
lastName: string; | ||
documentNumber: number; | ||
userRelationTypeId: number; | ||
city: string; | ||
postalCode: string; | ||
address: string; | ||
phone: string; | ||
checked: boolean; | ||
province: string; | ||
beneficiaryType: number; | ||
relatedUserId: null | string; | ||
currency: string; | ||
correspondent?: any; | ||
location: any; | ||
office: any; | ||
officeValue: any; | ||
paymentType: number; | ||
paymentEntityBeneficiaryId: number; | ||
paymentEntityAccountId: number; | ||
verified: any; | ||
paymentEntityInfo: any; | ||
documentTypeId: any; | ||
documentExpirationDate: Date; | ||
createdAt: Date; | ||
updatedAt: Date; | ||
countryDestination: Country; | ||
}; | ||
type AccountDeposits = { | ||
count: number; | ||
rows: Deposit[]; | ||
}; | ||
declare class TropipayHooks { | ||
private tropipay; | ||
constructor(tropipayInstance: Tropipay); | ||
static subscribeHook(eventType: HookEventType, target: string, value: string): Promise<void>; | ||
/** | ||
* Get hook the sucbcribed hook info by his eventType. | ||
* If no eventType is passed it will return | ||
* all subscribed hooks or empty Array if none hooks exist. | ||
* @param eventType or no params for retrieving all hooks | ||
* @returns | ||
*/ | ||
getSubscribedHook(eventType?: HookEventType): Promise<UserHookSubscribed[]>; | ||
updateSubscribedHook(eventType?: string): Promise<void>; | ||
deleteSubscribedHook(eventType?: string): Promise<void>; | ||
} | ||
/** | ||
@@ -72,20 +189,12 @@ * Tropipayjs is a Typescript/Javascript library for the Tropipay API. | ||
type ServerMode = 'Development' | 'Production'; | ||
interface TropipayConfig { | ||
clientId: string; | ||
clientSecret: string; | ||
serverMode?: ServerMode; | ||
} | ||
type AccountBalance = { | ||
balance: number; | ||
pendingIn: number; | ||
pendingOut: number; | ||
}; | ||
type ServerMode = "Development" | "Production"; | ||
declare class Tropipay { | ||
protected clientId: string; | ||
protected clientSecret: string; | ||
protected request: Axios; | ||
protected static accessToken: string | undefined; | ||
protected static refreshToken: string | undefined; | ||
protected serverMode: ServerMode; | ||
readonly clientId: string; | ||
readonly clientSecret: string; | ||
request: Axios; | ||
static accessToken: string | undefined; | ||
static refreshToken: string | undefined; | ||
serverMode: ServerMode; | ||
hooks: TropipayHooks; | ||
constructor(config: TropipayConfig); | ||
@@ -114,3 +223,3 @@ login(): Promise<LoginResponse>; | ||
* Get user balance | ||
* @returns balance object | ||
* @returns balance Object { balance: number, pendingIn: number, pendingOut: number } | ||
*/ | ||
@@ -163,3 +272,25 @@ getBalance(): Promise<AccountBalance>; | ||
} | ||
declare class ClientSideUtils { | ||
constructor(tropipayInstance: Tropipay); | ||
} | ||
export { Tropipay }; | ||
declare class ServerSideUtils { | ||
private tropipay; | ||
constructor(tropipayInstance: Tropipay); | ||
/** | ||
* 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: { | ||
clientId: string; | ||
clientSecret: string; | ||
} | Tropipay, originalCurrencyAmount: string, bankOrderCode: string, signature: string): boolean; | ||
} | ||
declare const SERVER_MODE: ServerMode$1; | ||
export { AccountBalance, AccountDeposits, ClientSideUtils, Country, Deposit, HookEventType, HookTargetType, LoginError, LoginResponse, PaymentLink, PaymentLinkPayload, SERVER_MODE, ServerMode$1 as ServerMode, ServerSideUtils, Tropipay, TropipayConfig, TropipayCredentials, TropipayHooks, UserHook, UserHookSubscribed, mediationPaymentCardConfig }; |
198
index.js
@@ -6,7 +6,69 @@ 'use strict'; | ||
var axios = require('axios'); | ||
var crypto = require('crypto'); | ||
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); | ||
class TropipayHooks { | ||
tropipay; | ||
// ... hook-related functionality ... | ||
constructor(tropipayInstance) { | ||
this.tropipay = tropipayInstance; | ||
} | ||
static async subscribeHook(eventType, target, value) { } | ||
/** | ||
* Get hook the sucbcribed hook info by his eventType. | ||
* If no eventType is passed it will return | ||
* all subscribed hooks or empty Array if none hooks exist. | ||
* @param eventType or no params for retrieving all hooks | ||
* @returns | ||
*/ | ||
async getSubscribedHook(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 new Error(`Could not get subscribed hooks ${error}`); | ||
} | ||
} | ||
async updateSubscribedHook(eventType) { | ||
//TODO | ||
throw new Error("Not implementet yet"); | ||
} | ||
async deleteSubscribedHook(eventType) { | ||
//TODO | ||
throw new Error("Not implementet yet"); | ||
} | ||
} | ||
/** | ||
@@ -25,29 +87,31 @@ * Tropipayjs is a Typescript/Javascript library for the Tropipay API. | ||
serverMode; | ||
hooks; | ||
constructor(config) { | ||
this.clientId = config.clientId; | ||
this.clientSecret = config.clientSecret; | ||
this.serverMode = config.serverMode || 'Development'; | ||
this.serverMode = config.serverMode || "Development"; | ||
this.request = axios__default["default"].create({ | ||
baseURL: this.serverMode === 'Production' | ||
? 'https://www.tropipay.com' | ||
: 'https://tropipay-dev.herokuapp.com', | ||
baseURL: this.serverMode === "Production" | ||
? "https://www.tropipay.com" | ||
: "https://tropipay-dev.herokuapp.com", | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Accept: 'application/json', | ||
"Content-Type": "application/json", | ||
Accept: "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
} | ||
}, | ||
}); | ||
this.hooks = new TropipayHooks(this); | ||
} | ||
async login() { | ||
try { | ||
const { data } = await this.request.post('/api/v2/access/token', { | ||
const { data } = await this.request.post("/api/v2/access/token", { | ||
client_id: this.clientId, | ||
client_secret: this.clientSecret, | ||
grant_type: "client_credentials", | ||
scope: "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" | ||
scope: "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', | ||
} | ||
"Content-Type": "application/json", | ||
Accept: "application/json", | ||
}, | ||
}); | ||
@@ -76,8 +140,8 @@ Tropipay.accessToken = data.access_token; | ||
try { | ||
const paylink = await this.request.post('/api/v2/paymentcards', payload, { | ||
const paylink = await this.request.post("/api/v2/paymentcards", payload, { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
Accept: "application/json", | ||
}, | ||
}); | ||
@@ -100,8 +164,8 @@ return paylink.data; | ||
try { | ||
const deposits = await this.request.get('/api/v2/deposit_accounts', { | ||
const deposits = await this.request.get("/api/v2/deposit_accounts", { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
Accept: "application/json", | ||
}, | ||
}); | ||
@@ -121,7 +185,7 @@ return deposits.data; | ||
try { | ||
const countries = await this.request.get('/api/v2/countries'); | ||
const countries = await this.request.get("/api/v2/countries"); | ||
return countries.data; | ||
} | ||
catch (error) { | ||
throw new Error(`TropipayJS Error - Could not retrieve the countries list`); | ||
throw new Error(`Could not retrieve the countries list`); | ||
} | ||
@@ -131,3 +195,3 @@ } | ||
* Get user balance | ||
* @returns balance object | ||
* @returns balance Object { balance: number, pendingIn: number, pendingOut: number } | ||
*/ | ||
@@ -139,8 +203,8 @@ async getBalance() { | ||
try { | ||
const balance = await this.request.get('/api/v2/users/balance', { | ||
const balance = await this.request.get("/api/v2/users/balance", { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
Accept: "application/json", | ||
}, | ||
}); | ||
@@ -150,3 +214,2 @@ return balance.data; | ||
catch (error) { | ||
console.log("el error es ", error); | ||
throw new Error(`TropipayJS Error - Could not retrieve the user's balance`); | ||
@@ -165,3 +228,3 @@ } | ||
try { | ||
const countries = await this.request.get('/api/v2/countries/destinations'); | ||
const countries = await this.request.get("/api/v2/countries/destinations"); | ||
return countries.data; | ||
@@ -182,8 +245,8 @@ } | ||
try { | ||
const favoritesList = await this.request.get('/api/v2/paymentcards/favorites', { | ||
const favoritesList = await this.request.get("/api/v2/paymentcards/favorites", { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
Accept: "application/json", | ||
}, | ||
}); | ||
@@ -205,9 +268,9 @@ return favoritesList?.data?.rows; | ||
try { | ||
const movements = await this.request.get('/api/v2/movements', { | ||
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}` | ||
} | ||
"Content-Type": "application/json", | ||
Accept: "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
}, | ||
}); | ||
@@ -228,3 +291,3 @@ return movements.data; | ||
try { | ||
const profile = await this.request.get('/api/users/profile'); | ||
const profile = await this.request.get("/api/users/profile"); | ||
return profile.data; | ||
@@ -244,3 +307,3 @@ } | ||
*/ | ||
async rates(originCurrency, targetCurrency = 'EUR') { | ||
async rates(originCurrency, targetCurrency = "EUR") { | ||
if (!Tropipay.accessToken) { | ||
@@ -250,11 +313,11 @@ await this.login(); | ||
try { | ||
const rates = await this.request.post('/api/v2/movements/get_rate', { | ||
const rates = await this.request.post("/api/v2/movements/get_rate", { | ||
currencyFrom: originCurrency, | ||
currencyTo: targetCurrency | ||
currencyTo: targetCurrency, | ||
}, { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Accept: 'application/json', | ||
"Content-Type": "application/json", | ||
Accept: "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
} | ||
}, | ||
}); | ||
@@ -280,8 +343,8 @@ return rates.data.rate; | ||
try { | ||
const mediation = await this.request.post('/api/v2/paymentcards/mediation', config, { | ||
const mediation = await this.request.post("/api/v2/paymentcards/mediation", config, { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
Accept: "application/json", | ||
}, | ||
}); | ||
@@ -295,4 +358,41 @@ return mediation.data; | ||
} | ||
class ClientSideUtils { | ||
constructor(tropipayInstance) { } | ||
} | ||
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 + | ||
crypto__namespace | ||
.createHash("sha1") | ||
.update(credentials.clientSecret) | ||
.digest("hex") + | ||
originalCurrencyAmount) | ||
.digest("hex"); | ||
return localSignature === signature; | ||
} | ||
} | ||
const SERVER_MODE = "Development"; // Move the constant here | ||
exports.ClientSideUtils = ClientSideUtils; | ||
exports.SERVER_MODE = SERVER_MODE; | ||
exports.ServerSideUtils = ServerSideUtils; | ||
exports.Tropipay = Tropipay; | ||
exports.TropipayHooks = TropipayHooks; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,159 @@ | ||
import * as countries from './countries'; | ||
export { countries }; | ||
import { ServerMode } from "../constants/TropipayConstants"; | ||
export type AccountBalance = { | ||
balance: number; | ||
pendingIn: number; | ||
pendingOut: number; | ||
}; | ||
export interface TropipayConfig { | ||
clientId: string; | ||
clientSecret: string; | ||
serverMode?: ServerMode; | ||
} | ||
export type TropipayCredentials = { | ||
clientId: string; | ||
clientSecret: string; | ||
}; | ||
export type HookEventType = "transaction_completed" | "transaction_charged" | "transaction_guarded"; | ||
export type HookTargetType = "web" | "email"; | ||
export interface UserHook { | ||
event: HookEventType; | ||
target: string; | ||
value: string; | ||
} | ||
export interface UserHookSubscribed extends UserHook { | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
export interface UserHook { | ||
event: HookEventType; | ||
target: string; | ||
value: string; | ||
} | ||
export interface UserHookSubscribed extends UserHook { | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
export interface PaymentLinkPayload { | ||
reference: string; | ||
concept: string; | ||
favorite: boolean; | ||
amount: number; | ||
currency: string; | ||
description: string; | ||
singleUse: boolean; | ||
reasonId: number; | ||
expirationDays: number; | ||
lang: string; | ||
urlSuccess: string; | ||
urlFailed: string; | ||
urlNotification: string; | ||
serviceDate: string; | ||
client: { | ||
name: string; | ||
lastName: string; | ||
address: string; | ||
phone: string; | ||
email: string; | ||
countryId: number; | ||
termsAndConditions: boolean; | ||
}; | ||
directPayment: boolean; | ||
paymentMethods?: string[]; | ||
} | ||
export interface PaymentLink extends PaymentLinkPayload { | ||
expirationDate: string; | ||
hasClient: boolean; | ||
updatedAt: string; | ||
createdAt: string; | ||
qrImage: string; | ||
shortUrl: string; | ||
paymentUrl: string; | ||
} | ||
export interface mediationPaymentCardConfig { | ||
amount: number; | ||
currency: "EUR" | "USD"; | ||
concept: string; | ||
description: string; | ||
reference: string; | ||
singleUse: boolean; | ||
lang: string; | ||
productUrl?: string; | ||
buyer: null | any; | ||
seller: { | ||
sellerId?: number; | ||
type?: number; | ||
email?: string; | ||
}; | ||
feePercent?: number; | ||
feeFixed?: number; | ||
sendMail: boolean; | ||
} | ||
export type LoginResponse = { | ||
access_token: string; | ||
refresh_token: string; | ||
token_type: "Bearer"; | ||
expires_in: number; | ||
scope: string; | ||
}; | ||
export type LoginError = { | ||
error: string; | ||
}; | ||
export type Country = { | ||
id: number; | ||
name: string; | ||
sepaZone: boolean; | ||
state: number; | ||
slug: string; | ||
slugn: number; | ||
callingCode: number; | ||
isDestination: boolean; | ||
isRisky: boolean; | ||
currentCurrency: string | null; | ||
createdAt: string; | ||
updatedAt: string; | ||
isFavorite: boolean; | ||
position: any; | ||
}; | ||
export type Deposit = { | ||
id: number; | ||
accountNumber: string; | ||
alias: string; | ||
swift: string; | ||
type: number; | ||
country: number | null; | ||
firstName: string; | ||
default: null; | ||
state: number; | ||
userId: string; | ||
countryDestinationId: number; | ||
lastName: string; | ||
documentNumber: number; | ||
userRelationTypeId: number; | ||
city: string; | ||
postalCode: string; | ||
address: string; | ||
phone: string; | ||
checked: boolean; | ||
province: string; | ||
beneficiaryType: number; | ||
relatedUserId: null | string; | ||
currency: string; | ||
correspondent?: any; | ||
location: any; | ||
office: any; | ||
officeValue: any; | ||
paymentType: number; | ||
paymentEntityBeneficiaryId: number; | ||
paymentEntityAccountId: number; | ||
verified: any; | ||
paymentEntityInfo: any; | ||
documentTypeId: any; | ||
documentExpirationDate: Date; | ||
createdAt: Date; | ||
updatedAt: Date; | ||
countryDestination: Country; | ||
}; | ||
export type AccountDeposits = { | ||
count: number; | ||
rows: Deposit[]; | ||
}; |
{ | ||
"name": "@yosle/tropipayjs", | ||
"version": "0.1.9", | ||
"version": "0.1.10", | ||
"description": "Javascript / Typescript SDK for the Tropipay API", | ||
@@ -43,2 +43,2 @@ "main": "index.js", | ||
} | ||
} | ||
} |
TropipayJS - Typescript/Javascript SDK for Tropipay Payments API | ||
=========== | ||
![NodeJS](https://img.shields.io/badge/node.js-6DA55F?style=for-the-badge&logo=node.js&logoColor=white) | ||
@@ -13,2 +14,3 @@ ![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white) | ||
# Table of Contents | ||
- [TropipayJS - Typescript/Javascript SDK for Tropipay Payments API](#tropipayjs---typescriptjavascript-sdk-for-tropipay-payments-api) | ||
@@ -28,2 +30,3 @@ - [Table of Contents](#table-of-contents) | ||
## About the project | ||
This library is a community effort. Tropipay may make some changes on the API specification. Use the [test environment](https://tropipay-dev.herokuapp.com) to make sure everything is working as expected. | ||
@@ -34,3 +37,5 @@ | ||
The library is intended to simplify the integration process with Tropipay's services, but it is essential to consult the official documentation to ensure that you are using the API correctly and taking into account any recent changes or updates made by Tropipay. | ||
# Getting started | ||
You can use npm or yarn to install this package: | ||
@@ -52,13 +57,19 @@ | ||
## Usage | ||
The Tropipay instance, allows you to access all the method available in the API. This Object is meant to be used *only in server side*. Do not use the Tropipay object on the client side (browser). This would expose your app credentials (the client secret of your account). You can create an endpoint at your back-end using express and consume it in your front-end, or use SSR if you're using NextJS. | ||
### CommonJS | ||
```javascript | ||
const { Tropipay } = require('@yosle/tropipayjs') | ||
``` | ||
### ES6 | ||
```javascript | ||
import { Tropipay } from '@yosle/tropipayjs' | ||
``` | ||
### Initialize the Tropipay class | ||
You can instantiate the Tropipay class passing the client Id ,client secret and optionally the serverMode parameter, if no serverMode is provided, `Development` will be used as default. Make sure you use the [test environment](https://tropipay-dev.herokuapp.com) credentials when serverMode is on `Development`. | ||
@@ -87,3 +98,5 @@ | ||
``` | ||
### Generating a Payment Link | ||
```javascript | ||
@@ -127,2 +140,3 @@ /* | ||
# Contributing | ||
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again! | ||
@@ -139,3 +153,5 @@ | ||
You can also make a small [donation to the author](https://tppay.me/l94qaa3h) of the library. | ||
# License | ||
Distributed under the MIT License. See `LICENSE.txt` for more information. | ||
@@ -142,0 +158,0 @@ |
// Contents of the file /rollup.config.js | ||
import typescript from '@rollup/plugin-typescript'; | ||
import typescript from "@rollup/plugin-typescript"; | ||
import dts from "rollup-plugin-dts"; | ||
const config = [ | ||
{ | ||
input: 'dist/index.js', | ||
output: { | ||
file: 'index.js', | ||
format: 'cjs', | ||
sourcemap: true, | ||
}, | ||
external: ['axios'], | ||
plugins: [typescript()] | ||
}, { | ||
input: 'dist/index.d.ts', | ||
output: { | ||
file: 'index.d.ts', | ||
format: 'es' | ||
}, | ||
plugins: [dts()] | ||
} | ||
{ | ||
input: "dist/index.js", | ||
output: { | ||
file: "index.js", | ||
format: "cjs", | ||
sourcemap: true, | ||
}, | ||
external: ["axios", "crypto"], | ||
plugins: [typescript()], | ||
}, | ||
{ | ||
input: "dist/index.d.ts", | ||
output: { | ||
file: "index.d.ts", | ||
format: "es", | ||
}, | ||
plugins: [dts()], | ||
}, | ||
]; | ||
export default config; | ||
export default config; |
304
src/index.ts
/** | ||
* Tropipayjs is a Typescript/Javascript library for the Tropipay API. | ||
* | ||
* | ||
* @author Yosleivy Baez Acosta | ||
* | ||
* | ||
*/ | ||
import axios, { Axios } from "axios"; | ||
import { PaymentLink, PaymentLinkPayload } from './interfaces/paymentlink' | ||
import { mediationPaymentCardConfig } from "./interfaces/mediation"; | ||
type ServerMode = 'Development' | 'Production' | ||
interface TropipayConfig { | ||
clientId: string; | ||
clientSecret: string; | ||
serverMode?: ServerMode; | ||
} | ||
type AccountBalance = { | ||
balance: number, | ||
pendingIn: number, | ||
pendingOut: number | ||
} | ||
export class Tropipay { | ||
protected clientId: string; | ||
protected clientSecret: string; | ||
protected request: Axios; | ||
protected static accessToken: string | undefined; | ||
protected static refreshToken: string | undefined; | ||
protected serverMode: ServerMode; | ||
constructor(config: TropipayConfig) { | ||
this.clientId = config.clientId; | ||
this.clientSecret = config.clientSecret; | ||
this.serverMode = config.serverMode || 'Development'; | ||
this.request = axios.create({ | ||
baseURL: this.serverMode === 'Production' | ||
? 'https://www.tropipay.com' | ||
: 'https://tropipay-dev.herokuapp.com', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Accept: 'application/json', | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
} | ||
}); | ||
} | ||
async login() { | ||
try { | ||
const { data } = await this.request.post<LoginResponse>('/api/v2/access/token', { | ||
client_id: this.clientId, | ||
client_secret: this.clientSecret, | ||
grant_type: "client_credentials", | ||
scope: "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 | ||
return data | ||
} catch (error) { | ||
if (axios.isAxiosError(error)) { | ||
throw new Error(`Could not obtain the access token from credentials ${error}`); | ||
} | ||
throw new Error(`Could not obtain the access token from credentials ${error}`); | ||
} | ||
} | ||
/** | ||
* 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 createPaymentCard(payload: PaymentLinkPayload): Promise<PaymentLink> { | ||
if (!Tropipay.accessToken) { | ||
await this.login() | ||
} | ||
try { | ||
const paylink = await this.request.post('/api/v2/paymentcards', payload, { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
}) | ||
return paylink.data as PaymentLink | ||
} catch (error) { | ||
throw new Error(`Could not obtain the access token with the given credentials.`); | ||
} | ||
} | ||
/** | ||
* Get all deposits in this account. | ||
* @returns A Promise of an Array of AccountDeposits or throws an Exception | ||
* @see https://tpp.stoplight.io/docs/tropipay-api-doc/b3A6OTgyOTQ1Mg-get-deposit-accounts-list | ||
*/ | ||
async getDepositAccounts(): Promise<AccountDeposits[] | Error> { | ||
if (!Tropipay.accessToken) { | ||
await this.login() | ||
} | ||
try { | ||
const deposits = await this.request.get('/api/v2/deposit_accounts', { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Authorization: `Bearer ${Tropipay.accessToken}`, | ||
Accept: 'application/json' | ||
} | ||
}) | ||
return deposits.data | ||
} catch (error) { | ||
throw new Error(`Could not retrieve the account deposits ${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(): Promise<Country[]> { | ||
try { | ||
const countries = await this.request.get('/api/v2/countries') | ||
return countries.data | ||
} catch (error) { | ||
throw new Error(`TropipayJS Error - Could not retrieve the countries list`); | ||
} | ||
} | ||
/** | ||
* Get user balance | ||
* @returns balance Object { balance: number, pendingIn: number, pendingOut: number } | ||
*/ | ||
async getBalance(): Promise<AccountBalance> { | ||
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 new Error(`TropipayJS Error - Could not retrieve the user's balance`); | ||
} | ||
} | ||
/** | ||
* 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(): Promise<Country[]> { | ||
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 new Error(`Could not retrieve favorites list ${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 new Error(`Could not retrieve movements list ${error}`); | ||
} | ||
} | ||
/** | ||
* Return profile data for this account. | ||
* @returns | ||
*/ | ||
async profile() { | ||
if (!Tropipay.accessToken) await this.login(); | ||
try { | ||
const profile = await this.request.get('/api/users/profile') | ||
return profile.data | ||
} catch (error) { | ||
throw new Error(`Could not retrieve movements list ${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: string, targetCurrency: string = 'EUR'): Promise<number | Error> { | ||
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 new Error(`Could not retrieve rates ${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: mediationPaymentCardConfig): Promise<PaymentLink> { | ||
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 as PaymentLink; | ||
} catch (error) { | ||
throw new Error(`Could not generate mediation paymentCard ${error}`); | ||
} | ||
} | ||
} | ||
export { Tropipay } from "./api/TropipayAPI"; | ||
export { ClientSideUtils } from "./api/TropipayAPI"; | ||
export { ServerSideUtils } from "./utils/TropipayUtils"; | ||
export { TropipayHooks } from "./hooks/TropipayHooks"; | ||
export * from "./interfaces/index"; | ||
export { SERVER_MODE } from "./config/TropipayConfig"; | ||
export * from "./constants/TropipayConstants"; |
"use strict"; | ||
//# sourceMappingURL=index.js.map |
@@ -1,4 +0,172 @@ | ||
import * as countries from './countries' | ||
import { ServerMode } from "../constants/TropipayConstants"; | ||
export type AccountBalance = { | ||
balance: number; | ||
pendingIn: number; | ||
pendingOut: number; | ||
}; | ||
export {countries} | ||
export interface TropipayConfig { | ||
clientId: string; | ||
clientSecret: string; | ||
serverMode?: ServerMode; | ||
} | ||
export type TropipayCredentials = { clientId: string; clientSecret: string }; | ||
export type HookEventType = | ||
| "transaction_completed" | ||
| "transaction_charged" | ||
| "transaction_guarded"; | ||
export type HookTargetType = "web" | "email"; | ||
export interface UserHook { | ||
event: HookEventType; | ||
target: string; | ||
value: string; | ||
} | ||
export interface UserHookSubscribed extends UserHook { | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
export interface UserHook { | ||
event: HookEventType; | ||
target: string; | ||
value: string; | ||
} | ||
export interface UserHookSubscribed extends UserHook { | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
export interface PaymentLinkPayload { | ||
reference: string; | ||
concept: string; | ||
favorite: boolean; | ||
amount: number; | ||
currency: string; | ||
description: string; | ||
singleUse: boolean; | ||
reasonId: number; | ||
expirationDays: number; | ||
lang: string; | ||
urlSuccess: string; | ||
urlFailed: string; | ||
urlNotification: string; | ||
serviceDate: string; | ||
client: { | ||
name: string; | ||
lastName: string; | ||
address: string; | ||
phone: string; | ||
email: string; | ||
countryId: number; | ||
termsAndConditions: boolean; | ||
}; | ||
directPayment: boolean; | ||
paymentMethods?: string[]; | ||
} | ||
export interface PaymentLink extends PaymentLinkPayload { | ||
expirationDate: string; | ||
hasClient: boolean; | ||
updatedAt: string; | ||
createdAt: string; | ||
qrImage: string; | ||
shortUrl: string; | ||
paymentUrl: string; | ||
} | ||
export interface mediationPaymentCardConfig { | ||
amount: number; | ||
currency: "EUR" | "USD"; | ||
concept: string; | ||
description: string; | ||
reference: string; | ||
singleUse: boolean; | ||
lang: string; | ||
productUrl?: string; | ||
buyer: null | any; | ||
seller: { | ||
sellerId?: number; | ||
type?: number; | ||
email?: string; | ||
}; | ||
feePercent?: number; | ||
feeFixed?: number; | ||
sendMail: boolean; | ||
} | ||
export type LoginResponse = { | ||
access_token: string; | ||
refresh_token: string; | ||
token_type: "Bearer"; | ||
expires_in: number; | ||
scope: string; | ||
}; | ||
export type LoginError = { | ||
error: string; | ||
}; | ||
export type Country = { | ||
id: number; | ||
name: string; | ||
sepaZone: boolean; | ||
state: number; | ||
slug: string; | ||
slugn: number; | ||
callingCode: number; | ||
isDestination: boolean; | ||
isRisky: boolean; | ||
currentCurrency: string | null; | ||
createdAt: string; | ||
updatedAt: string; | ||
isFavorite: boolean; | ||
position: any; | ||
}; | ||
export type Deposit = { | ||
id: number; | ||
accountNumber: string; | ||
alias: string; | ||
swift: string; | ||
type: number; | ||
country: number | null; | ||
firstName: string; | ||
default: null; | ||
state: number; | ||
userId: string; | ||
countryDestinationId: number; | ||
lastName: string; | ||
documentNumber: number; | ||
userRelationTypeId: number; | ||
city: string; | ||
postalCode: string; | ||
address: string; | ||
phone: string; | ||
checked: boolean; | ||
province: string; | ||
beneficiaryType: number; | ||
relatedUserId: null | string; | ||
currency: string; | ||
correspondent?: any; | ||
location: any; | ||
office: any; | ||
officeValue: any; | ||
paymentType: number; | ||
paymentEntityBeneficiaryId: number; | ||
paymentEntityAccountId: number; | ||
verified: any; | ||
paymentEntityInfo: any; | ||
documentTypeId: any; | ||
documentExpirationDate: Date; | ||
createdAt: Date; | ||
updatedAt: Date; | ||
countryDestination: Country; | ||
}; | ||
export type AccountDeposits = { | ||
count: number; | ||
rows: Deposit[]; | ||
}; |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ export interface PaymentLinkPayload { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
//# sourceMappingURL=index.js.map |
@@ -0,0 +0,0 @@ |
@@ -12,3 +12,3 @@ { | ||
/* Language and Environment */ | ||
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ | ||
"target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, | ||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ | ||
@@ -26,5 +26,5 @@ // "jsx": "preserve", /* Specify what JSX code is generated. */ | ||
/* Modules */ | ||
"module": "esnext", /* Specify what module code is generated. */ | ||
"rootDir": "./src", /* Specify the root folder within your source files. */ | ||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ | ||
"module": "esnext" /* Specify what module code is generated. */, | ||
"rootDir": "./src" /* Specify the root folder within your source files. */, | ||
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, | ||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ | ||
@@ -44,9 +44,9 @@ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ | ||
/* Emit */ | ||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ | ||
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, | ||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */ | ||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ | ||
"sourceMap": true, /* Create source map files for emitted JavaScript files. */ | ||
"sourceMap": true /* Create source map files for emitted JavaScript files. */, | ||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ | ||
"outDir": "./dist", /* Specify an output folder for all emitted files. */ | ||
"removeComments": false, /* Disable emitting comments. */ | ||
"outDir": "./dist" /* Specify an output folder for all emitted files. */, | ||
"removeComments": false /* Disable emitting comments. */, | ||
// "noEmit": true, /* Disable emitting files from a compilation. */ | ||
@@ -71,7 +71,7 @@ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ | ||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ | ||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ | ||
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, | ||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ | ||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ | ||
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, | ||
/* Type Checking */ | ||
"strict": true, /* Enable all strict type-checking options. */ | ||
"strict": true /* Enable all strict type-checking options. */, | ||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ | ||
@@ -94,3 +94,3 @@ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ | ||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ | ||
"allowUnreachableCode": false, /* Disable error reporting for unreachable code. */ | ||
"allowUnreachableCode": false /* Disable error reporting for unreachable code. */, | ||
/* Completeness */ | ||
@@ -100,2 +100,2 @@ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ | ||
} | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
226682
34
1857
155
1