Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import eslintPluginPrettierRecommended from "eslint-plugin-prettier/recommended";

export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.recommended,
{
ignores: ["dist", "node_modules"],
},
eslintPluginPrettierRecommended,
);
eslint.configs.recommended,
tseslint.configs.recommended,
{
ignores: ["dist", "node_modules"],
},
eslintPluginPrettierRecommended,
);
9 changes: 4 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@eslint/js": "^9.19.0",
"@types/node": "^22.13.1",
"@vitest/coverage-v8": "^3.0.6",
"dotenv": "^16.4.7",
"dotenv": "^16.5.0",
"eslint": "^9.19.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.3",
Expand Down
3 changes: 2 additions & 1 deletion src/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export enum PaymentMethod {
}

export enum SimpleStatus {
ACCEPTED = "ACCEPTED",
AUTHORIZED = "AUTHORIZED",
PENDING = "PENDING",
CAPTURE = "CAPTURE",
REJECTED = "REJECTED",
}
27 changes: 20 additions & 7 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,17 @@ export function getSimpleStatus(
if (
paymentMethodStatuses[
paymentStatus.selectedPaymentMethod
]?.accepted.includes(plainStatus)
]?.authorized.includes(plainStatus)
) {
return SimpleStatus.ACCEPTED;
return SimpleStatus.AUTHORIZED;
}

if (
paymentMethodStatuses[
paymentStatus.selectedPaymentMethod
]?.capture.includes(plainStatus)
) {
return SimpleStatus.CAPTURE;
}

if (
Expand Down Expand Up @@ -107,23 +115,28 @@ export function getSavedCardData(

export const paymentMethodStatuses: Record<PaymentMethod, PaymentStatuses> = {
[PaymentMethod.QR_PAY]: {
accepted: ["ACSC", "ACCC"],
capture: ["ACSC", "ACCC"],
rejected: ["CANC", "RJCT"],
authorized: [],
},
[PaymentMethod.BANK_TRANSFER]: {
accepted: ["ACSC", "ACCC"],
capture: ["ACSC", "ACCC"],
rejected: ["CANC", "RJCT"],
authorized: [],
},
[PaymentMethod.PAY_LATER]: {
accepted: ["LOAN_APPLICATION_FINISHED", "LOAN_DISBURSED"],
capture: ["LOAN_APPLICATION_FINISHED", "LOAN_DISBURSED"],
rejected: ["CANCEL", "EXPIRED"],
authorized: [],
},
[PaymentMethod.CARD_PAY]: {
accepted: ["OK", "CB"],
capture: ["OK", "CB"],
rejected: ["FAIL"],
authorized: ["PA"],
},
[PaymentMethod.DIRECT_API]: {
accepted: ["OK", "CB"],
capture: ["OK", "CB"],
rejected: ["FAIL"],
authorized: [],
},
};
25 changes: 16 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { GatewayMode, Scopes } from "./enums";
import { TBPlusLogger } from "./logger";
import createClient, { ClientOptions, Middleware } from "openapi-fetch";
import { operations, paths } from "./paths";
import { constants, publicEncrypt, randomUUID } from "node:crypto";
Expand All @@ -18,7 +19,6 @@ export * from "./enums";
export class TBPlusSDK {
private clientId: string;
private clientSecret: string;
private clientIp: string;
private mode: GatewayMode;
private originalRequest: Request | undefined;
private scopes: Scopes[];
Expand All @@ -29,16 +29,17 @@ export class TBPlusSDK {
public apiClient;
public accessToken: string | undefined = undefined;
UNPROTECTED_ROUTES = ["/auth/oauth/v2/token"];
private logger: TBPlusLogger | undefined = undefined;

constructor(
clientId: string,
clientSecret: string,
clientIp: string,
sdkOptions: {
mode?: GatewayMode;
scopes?: Scopes[];
createClientParams?: ClientOptions;
} = {},
logger: TBPlusLogger | undefined = undefined,
) {
this.mode = sdkOptions.mode ?? GatewayMode.SANDBOX;
if (this.mode == GatewayMode.PRODUCTION) {
Expand All @@ -51,12 +52,12 @@ export class TBPlusSDK {

this.clientId = clientId;
this.clientSecret = clientSecret;
this.clientIp = clientIp;
this.scopes = sdkOptions.scopes ?? [Scopes.TATRAPAYPLUS];
this.apiClient = createClient<paths>({
baseUrl: this.baseUrl,
...sdkOptions.createClientParams,
});
this.logger = logger;
this.apiClient.use(this.getAuthMiddleware());
this.apiClient.use(this.getRetryMiddleware());
}
Expand Down Expand Up @@ -88,6 +89,9 @@ export class TBPlusSDK {
return request.clone();
},
onResponse: async ({ response }) => {
if (this.originalRequest && this.logger && typeof this.logger.log === 'function') {
await this.logger.log(this.originalRequest, response);
}
if (
!this.retryStatues.includes(response.status) ||
!this.originalRequest
Expand Down Expand Up @@ -116,12 +120,8 @@ export class TBPlusSDK {
}

private getDefaultHeaders() {
const defaultHeaders: Record<
"X-Request-ID" | "IP-Address" | "User-Agent",
string
> = {
const defaultHeaders: Record<"X-Request-ID" | "User-Agent", string> = {
"X-Request-ID": randomUUID(),
"IP-Address": this.clientIp,
"User-Agent": `Tatrapayplus-plugin/${this.clientVersion}/Node.js`,
};
return defaultHeaders;
Expand Down Expand Up @@ -167,6 +167,7 @@ export class TBPlusSDK {
public async createPayment(
body: paths["/v1/payments"]["post"]["requestBody"]["content"]["application/json"],
redirectUri: string,
clientIp: string,
language: operations["initiatePayment"]["parameters"]["header"]["Accept-Language"] = undefined,
preferredMethod: operations["initiatePayment"]["parameters"]["header"]["Preferred-Method"] = undefined,
fetchOptions = {},
Expand All @@ -175,6 +176,7 @@ export class TBPlusSDK {
const headers: operations["initiatePayment"]["parameters"]["header"] = {
...this.getDefaultHeaders(),
"Redirect-URI": redirectUri,
"IP-Address": clientIp,
};
if (language) {
headers["Accept-Language"] = language;
Expand Down Expand Up @@ -304,10 +306,15 @@ export class TBPlusSDK {
public async createPaymentDirect(
body: paths["/v1/payments-direct"]["post"]["requestBody"]["content"]["application/json"],
redirectUri: string,
clientIp: string,
) {
return this.apiClient.POST("/v1/payments-direct", {
params: {
header: { ...this.getDefaultHeaders(), "Redirect-URI": redirectUri },
header: {
...this.getDefaultHeaders(),
"Redirect-URI": redirectUri,
"IP-Address": clientIp,
},
},
body: body,
});
Expand Down
97 changes: 97 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
type AnyObject = Record<string, unknown>;

export class TBPlusLogger {
private maskSensitiveData: boolean;
private maskBodyFields: string[] = [
"client_id",
"client_secret",
"access_token",
];
private maskHeaderFields: string[] = ["authorization"];

constructor(maskSensitiveData = true) {
this.maskSensitiveData = maskSensitiveData;
}

private maskValue(value: string, keep = 5): string {
if (value.length <= keep * 2) {
return "*".repeat(value.length);
}
return (
value.slice(0, keep) +
"*".repeat(value.length - 2 * keep) +
value.slice(-keep)
);
}
private isRecord(obj: unknown): obj is Record<string, unknown> {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
}

private maskBody(body: unknown): unknown {
if (!this.maskSensitiveData || !this.isRecord(body)) return body;

const masked: Record<string, unknown> = { ...body };

for (const key of this.maskBodyFields) {
if (key in masked && typeof masked[key] === "string") {
masked[key] = this.maskValue(masked[key]);
}
}

return masked;
}

private maskHeaders(headers: Headers | AnyObject): AnyObject {
const rawHeaders: AnyObject =
headers instanceof Headers
? Object.fromEntries(headers.entries())
: headers;
const masked: AnyObject = {};

for (const key in rawHeaders) {
masked[key] = this.maskHeaderFields.includes(key)
? this.maskValue(String(rawHeaders[key]))
: rawHeaders[key];
}

return masked;
}

public async log(request: Request, response: Response): Promise<void> {
const requestClone = request.clone();
const bodyText = await requestClone.text();
const parsedBody = (() => {
try {
return JSON.parse(bodyText);
} catch {
return bodyText;
}
})();

const maskedBody = this.maskBody(parsedBody);
const maskedHeaders = this.maskHeaders(request.headers);

this.writeLine(`Request: ${request.method} ${request.url}`);
this.writeLine(`Headers: ${JSON.stringify(maskedHeaders, null, 2)}`);
if (bodyText) {
this.writeLine(`Body: ${JSON.stringify(maskedBody, null, 2)}`);
}

const resText = await response.clone().text();
let resParsed;
try {
resParsed = JSON.parse(resText);
} catch {
resParsed = resText;
}

this.writeLine(`Response Status: ${response.status}`);
this.writeLine(
`Response: ${JSON.stringify(this.maskBody(resParsed), null, 2)}\n`,
);
}

protected writeLine(line: string): void {
console.log(line);
}
}
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type PaymentMethodsParams = {
};

export type PaymentStatuses = {
accepted: string[];
authorized: string[];
rejected: string[];
capture: string[];
};
18 changes: 15 additions & 3 deletions tests/live.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import { TBPlusSDK } from "../src";
import dotenv from "dotenv";
import { PaymentMethod, SimpleStatus } from "../src/enums";
import { getAvailable } from "../src/helpers";
import { TBPlusLogger } from "../src/logger";

dotenv.config();

const REDIRECT_URI = "https://tatrabanka.sk/";

export class TestLogger extends TBPlusLogger {
protected writeLine(line: string): void {
console.log("[TestLogger]", line);
}
}
describe("TBPlusSDK tests on live", () => {
it("retrieve all payment methods", async () => {
const sdk = new TBPlusSDK(
Expand All @@ -29,6 +34,8 @@ describe("TBPlusSDK tests on live", () => {
process.env.API_KEY as string,
process.env.API_SECRET as string,
"192.0.2.123",
{},
new TestLogger(),
);
const { data, error } = await sdk.createPayment(
{
Expand All @@ -42,6 +49,7 @@ describe("TBPlusSDK tests on live", () => {
},
},
REDIRECT_URI,
"127.0.0.1",
);
expect(error).toBeUndefined();
if (!data) {
Expand Down Expand Up @@ -106,6 +114,7 @@ describe("TBPlusSDK tests on live", () => {
},
},
REDIRECT_URI,
"127.0.0.1",
);
expect(error).toBeUndefined();
if (data) {
Expand Down Expand Up @@ -133,7 +142,6 @@ describe("TBPlusSDK tests on live", () => {
const sdk = new TBPlusSDK(
process.env.API_KEY as string,
process.env.API_SECRET as string,
"192.0.2.123",
{
createClientParams: {
fetch: mockFetch,
Expand Down Expand Up @@ -174,7 +182,11 @@ describe("TBPlusSDK tests on live", () => {
},
},
};
const { data, error } = await sdk.createPayment(body, REDIRECT_URI);
const { data, error } = await sdk.createPayment(
body,
REDIRECT_URI,
"127.0.0.1",
);
const requestBody = await requestHistory[1]?.json();

expect(error).toBeUndefined();
Expand Down
Loading