Merge branch 'develop' into PW-7518

This commit is contained in:
jillingk
2023-01-13 09:54:14 +01:00
committed by GitHub
25 changed files with 428 additions and 670 deletions

View File

@@ -47,18 +47,18 @@
"jest-ts-auto-mock": "^2.0.0",
"kind-of": "^6.0.3",
"minimist": ">=1.2.3",
"nock": "13.2.9",
"nock": "13.3.0",
"release-it": "15.5.0",
"ts-auto-mock": "^3.3.5",
"ts-jest": "^27.0.4",
"ts-loader": "9.4.2",
"ttypescript": "^1.5.10",
"typescript": "4.9.3"
"typescript": "4.9.4"
},
"dependencies": {
"https-proxy-agent": "5.0.1"
},
"optionalDependencies": {
"@types/node": "14.0.9"
"@types/node": "14.18.36"
}
}

View File

@@ -2,13 +2,13 @@ import nock from "nock";
import Client from "../client";
import { createClient } from "../__mocks__/base";
import BalancePlatform from "../services/balancePlatform";
import * as models from "../typings/balancePlatform/models";
import { balancePlatform } from "../typings";
import { AccountHolderUpdate } from "../services/balancePlaftform/accountHolders";
import { SweepConfigurationV2Create, SweepConfigurationV2Update } from "../services/balancePlaftform/balanceAccounts";
import { TransactionRuleInfoUpdate } from "../services/balancePlaftform/transactionRules";
let client: Client;
let balancePlatform: BalancePlatform;
let balancePlatformService: BalancePlatform;
let scope: nock.Scope;
beforeEach((): void => {
@@ -17,7 +17,7 @@ beforeEach((): void => {
}
client = createClient();
scope = nock(`${client.config.balancePlatformEndpoint}/${Client.BALANCE_PLATFORM_API_VERSION}`);
balancePlatform = new BalancePlatform(client);
balancePlatformService = new BalancePlatform(client);
});
afterEach(() => {
@@ -55,7 +55,7 @@ describe("Balance Platform", (): void => {
"id": "AH3227C223222B5CMD2SXFKGT",
"status": "active"
});
const request: models.AccountHolderInfo = {
const request: balancePlatform.AccountHolderInfo = {
"balancePlatform": "YOUR_BALANCE_PLATFORM",
"description": "S.Hopper - Staff 123",
"legalEntityId": "LE322KT223222D5FJ7THR293F",
@@ -63,7 +63,7 @@ describe("Balance Platform", (): void => {
"email": "s.hopper@example.com",
"phone": {
"number": "+315551231234",
"type": models.Phone.TypeEnum.Mobile
"type": balancePlatform.Phone.TypeEnum.Mobile
},
"address": {
"city": "Amsterdam",
@@ -75,7 +75,7 @@ describe("Balance Platform", (): void => {
}
};
const response: models.AccountHolder = await balancePlatform.AccountHolders.create(request);
const response: balancePlatform.AccountHolder = await balancePlatformService.AccountHolders.create(request);
expect(response.id).toBe("AH3227C223222B5CMD2SXFKGT");
expect(response.legalEntityId).toBe("LE322KT223222D5FJ7THR293F");
@@ -104,7 +104,7 @@ describe("Balance Platform", (): void => {
"status": "Active"
});
const response: models.AccountHolder = await balancePlatform.AccountHolders.retrieve("AH32272223222B5CM4MWJ892H");
const response: balancePlatform.AccountHolder = await balancePlatformService.AccountHolders.retrieve("AH32272223222B5CM4MWJ892H");
expect(response.id).toBe("AH32272223222B5CM4MWJ892H");
expect(response.balancePlatform).toBe("YOUR_BALANCE_PLATFORM");
@@ -133,11 +133,11 @@ describe("Balance Platform", (): void => {
"status": "Suspended"
});
const request: AccountHolderUpdate = {
status: models.AccountHolder.StatusEnum.Suspended,
status: balancePlatform.AccountHolder.StatusEnum.Suspended,
legalEntityId: "LE322KT223222D5FJ7THR293F",
};
const response: models.AccountHolder = await balancePlatform.AccountHolders.update("AH32272223222B5CM4MWJ892H", request);
const response: balancePlatform.AccountHolder = await balancePlatformService.AccountHolders.update("AH32272223222B5CM4MWJ892H", request);
expect(response.status).toBe("Suspended");
});
@@ -169,7 +169,7 @@ describe("Balance Platform", (): void => {
"hasPrevious": false
});
const response: models.PaginatedBalanceAccountsResponse = await balancePlatform.AccountHolders.listBalanceAccounts("AH32272223222B5CM4MWJ892H", {
const response: balancePlatform.PaginatedBalanceAccountsResponse = await balancePlatformService.AccountHolders.listBalanceAccounts("AH32272223222B5CM4MWJ892H", {
params: {
"limit": "5",
"offset": "10"
@@ -198,12 +198,12 @@ describe("Balance Platform", (): void => {
"id": balanceAccountId,
"status": "active"
});
const request: models.BalanceAccountInfo = {
const request: balancePlatform.BalanceAccountInfo = {
"accountHolderId": "AH32272223222B59K6ZKBBFNQ",
"description": "S.Hopper - Main balance account"
};
const response: models.BalanceAccount = await balancePlatform.BalanceAccounts.create(request);
const response: balancePlatform.BalanceAccount = await balancePlatformService.BalanceAccounts.create(request);
expect(response.id).toBe(balanceAccountId);
});
@@ -237,7 +237,7 @@ describe("Balance Platform", (): void => {
]
});
const response: models.BalanceSweepConfigurationsResponse = await balancePlatform.BalanceAccounts.listSweeps(balanceAccountId, {
const response: balancePlatform.BalanceSweepConfigurationsResponse = await balancePlatformService.BalanceAccounts.listSweeps(balanceAccountId, {
params: {
"limit": "5",
"offset": "10"
@@ -276,13 +276,13 @@ describe("Balance Platform", (): void => {
},
"currency": "EUR",
"schedule": {
"type": models.SweepSchedule.TypeEnum.Balance
"type": balancePlatform.SweepSchedule.TypeEnum.Balance
},
"type": models.SweepConfigurationV2.TypeEnum.Pull,
"status": models.SweepConfigurationV2.StatusEnum.Active
"type": balancePlatform.SweepConfigurationV2.TypeEnum.Pull,
"status": balancePlatform.SweepConfigurationV2.StatusEnum.Active
};
const response: models.SweepConfigurationV2 = await balancePlatform.BalanceAccounts.createSweep(balanceAccountId, request);
const response: balancePlatform.SweepConfigurationV2 = await balancePlatformService.BalanceAccounts.createSweep(balanceAccountId, request);
expect(response.id).toBe(sweepId);
expect(response.triggerAmount!.value).toBe(50000);
@@ -291,7 +291,7 @@ describe("Balance Platform", (): void => {
it("should support DELETE /balanceAccounts/{balanceAccountId}/sweeps/{sweepId}", async (): Promise<void> => {
scope.delete(`/balanceAccounts/${balanceAccountId}/sweeps/${sweepId}`).reply(204);
await balancePlatform.BalanceAccounts.deleteSweep(balanceAccountId, sweepId);
await balancePlatformService.BalanceAccounts.deleteSweep(balanceAccountId, sweepId);
});
it("should support GET /balanceAccounts/{balanceAccountId}/sweeps/{sweepId}", async (): Promise<void> => {
@@ -317,7 +317,7 @@ describe("Balance Platform", (): void => {
"currency": "EUR"
});
const response: models.SweepConfigurationV2 = await balancePlatform.BalanceAccounts.retrieveSweep(balanceAccountId, sweepId);
const response: balancePlatform.SweepConfigurationV2 = await balancePlatformService.BalanceAccounts.retrieveSweep(balanceAccountId, sweepId);
expect(response.id).toBe(sweepId);
expect(response.status).toBe("active");
@@ -342,10 +342,10 @@ describe("Balance Platform", (): void => {
"status": "inactive"
});
const request: SweepConfigurationV2Update = {
"status": models.SweepConfigurationV2.StatusEnum.Inactive
"status": balancePlatform.SweepConfigurationV2.StatusEnum.Inactive
};
const response: models.SweepConfigurationV2 = await balancePlatform.BalanceAccounts.updateSweep(balanceAccountId, sweepId, request);
const response: balancePlatform.SweepConfigurationV2 = await balancePlatformService.BalanceAccounts.updateSweep(balanceAccountId, sweepId, request);
expect(response.status).toBe("inactive");
});
@@ -367,7 +367,7 @@ describe("Balance Platform", (): void => {
"status": "Active"
});
const response: models.BalanceAccount = await balancePlatform.BalanceAccounts.retrieve(balanceAccountId);
const response: balancePlatform.BalanceAccount = await balancePlatformService.BalanceAccounts.retrieve(balanceAccountId);
expect(response.id).toBe(balanceAccountId);
expect(response.status).toBe("Active");
@@ -392,13 +392,13 @@ describe("Balance Platform", (): void => {
"status": "active",
"timeZone": "Europe/Amsterdam"
});
const request: models.BalanceAccountUpdateRequest = {
const request: balancePlatform.BalanceAccountUpdateRequest = {
"description": "Testing",
"status": models.BalanceAccountUpdateRequest.StatusEnum.Active,
"status": balancePlatform.BalanceAccountUpdateRequest.StatusEnum.Active,
"timeZone": "Europe/Amsterdam"
};
const response: models.BalanceAccount = await balancePlatform.BalanceAccounts.update(balanceAccountId, request);
const response: balancePlatform.BalanceAccount = await balancePlatformService.BalanceAccounts.update(balanceAccountId, request);
expect(response.status).toBe("active");
expect(response.timeZone).toBe("Europe/Amsterdam");
@@ -451,7 +451,7 @@ describe("Balance Platform", (): void => {
]
});
const response: models.PaginatedPaymentInstrumentsResponse = await balancePlatform.BalanceAccounts.listPaymentInstruments(balanceAccountId, {
const response: balancePlatform.PaginatedPaymentInstrumentsResponse = await balancePlatformService.BalanceAccounts.listPaymentInstruments(balanceAccountId, {
params: {
limit: "3",
offset: "6",
@@ -471,7 +471,7 @@ describe("Balance Platform", (): void => {
"status": "Active"
});
const response: models.BalancePlatform = await balancePlatform.General.retrieve(balanceAccountId);
const response: balancePlatform.BalancePlatform = await balancePlatformService.General.retrieve(balanceAccountId);
expect(response.id).toBe(balanceAccountId);
expect(response.status).toBe("Active");
@@ -514,7 +514,7 @@ describe("Balance Platform", (): void => {
"hasPrevious": "false"
});
const response: models.PaginatedAccountHoldersResponse = await balancePlatform.General.listAccountHolders(balanceAccountId);
const response: balancePlatform.PaginatedAccountHoldersResponse = await balancePlatformService.General.listAccountHolders(balanceAccountId);
expect(response.accountHolders.length).toBe(2);
expect(response.accountHolders[0].id).toBe("AH32272223222B59DDWSCCMP7");
@@ -545,13 +545,13 @@ describe("Balance Platform", (): void => {
},
"id": paymentInstrumentId
});
const request: models.PaymentInstrumentInfo = {
"type": models.PaymentInstrumentInfo.TypeEnum.Card,
const request: balancePlatform.PaymentInstrumentInfo = {
"type": balancePlatform.PaymentInstrumentInfo.TypeEnum.Card,
"issuingCountryCode": "NL",
"balanceAccountId": balanceAccountId,
"status": models.PaymentInstrumentInfo.StatusEnum.Inactive,
"status": balancePlatform.PaymentInstrumentInfo.StatusEnum.Inactive,
"card": {
"formFactor": models.CardInfo.FormFactorEnum.Physical,
"formFactor": balancePlatform.CardInfo.FormFactorEnum.Physical,
"brand": "mc",
"brandVariant": "mcdebit",
"cardholderName": "Sam Hopper",
@@ -576,7 +576,7 @@ describe("Balance Platform", (): void => {
"description": "S.Hopper - Main card"
};
const response: models.PaymentInstrument = await balancePlatform.PaymentInstruments.create(request);
const response: balancePlatform.PaymentInstrument = await balancePlatformService.PaymentInstruments.create(request);
expect(response.id).toBe(paymentInstrumentId);
expect(response.balanceAccountId).toBe(balanceAccountId);
@@ -606,7 +606,7 @@ describe("Balance Platform", (): void => {
"id": paymentInstrumentId
});
const response: models.PaymentInstrument = await balancePlatform.PaymentInstruments.retrieve(paymentInstrumentId);
const response: balancePlatform.PaymentInstrument = await balancePlatformService.PaymentInstruments.retrieve(paymentInstrumentId);
expect(response.id).toBe(paymentInstrumentId);
expect(response.status).toBe("active");
@@ -635,11 +635,11 @@ describe("Balance Platform", (): void => {
},
"id": paymentInstrumentId
});
const request: models.PaymentInstrumentUpdateRequest = {
const request: balancePlatform.PaymentInstrumentUpdateRequest = {
"balanceAccountId": "BA32272223222B5CM82WL892M"
};
const response: models.PaymentInstrument = await balancePlatform.PaymentInstruments.update(paymentInstrumentId, request);
const response: balancePlatform.PaymentInstrument = await balancePlatformService.PaymentInstruments.update(paymentInstrumentId, request);
expect(response.id).toBe(paymentInstrumentId);
expect(response.balanceAccountId).toBe("BA32272223222B5CM82WL892M");
@@ -681,7 +681,7 @@ describe("Balance Platform", (): void => {
]
});
const response: models.TransactionRulesResponse = await balancePlatform.PaymentInstruments.listTransactionRules(paymentInstrumentId);
const response: balancePlatform.TransactionRulesResponse = await balancePlatformService.PaymentInstruments.listTransactionRules(paymentInstrumentId);
expect(response.transactionRules!.length).toBe(2);
expect(response.transactionRules![0].id).toBe("TR32272223222B5CMDGMC9F4F");
@@ -696,12 +696,12 @@ describe("Balance Platform", (): void => {
"txVariant": "mc",
"id": paymentInstrumentGroupId
});
const request: models.PaymentInstrumentGroupInfo = {
const request: balancePlatform.PaymentInstrumentGroupInfo = {
"balancePlatform": "YOUR_BALANCE_PLATFORM",
"txVariant": "mc"
};
const response: models.PaymentInstrumentGroup = await balancePlatform.PaymentInstrumentGroups.create(request);
const response: balancePlatform.PaymentInstrumentGroup = await balancePlatformService.PaymentInstrumentGroups.create(request);
expect(response.id).toBe(paymentInstrumentGroupId);
expect(response.txVariant).toBe("mc");
@@ -715,7 +715,7 @@ describe("Balance Platform", (): void => {
"id": paymentInstrumentGroupId
});
const response: models.PaymentInstrumentGroup = await balancePlatform.PaymentInstrumentGroups.retrieve(paymentInstrumentGroupId);
const response: balancePlatform.PaymentInstrumentGroup = await balancePlatformService.PaymentInstrumentGroups.retrieve(paymentInstrumentGroupId);
expect(response.id).toBe(paymentInstrumentGroupId);
expect(response.txVariant).toBe("mc");
@@ -757,7 +757,7 @@ describe("Balance Platform", (): void => {
]
});
const response: models.TransactionRulesResponse = await balancePlatform.PaymentInstrumentGroups.listTransactionRules(paymentInstrumentGroupId);
const response: balancePlatform.TransactionRulesResponse = await balancePlatformService.PaymentInstrumentGroups.listTransactionRules(paymentInstrumentGroupId);
expect(response.transactionRules!.length).toBe(2);
expect(response.transactionRules![0].id).toBe("TR32272223222B5CMDGMC9F4F");
@@ -793,29 +793,29 @@ describe("Balance Platform", (): void => {
"type": "blockList",
"id": transactionRuleId
});
const request: models.TransactionRuleInfo = {
const request: balancePlatform.TransactionRuleInfo = {
"description": "Allow only point-of-sale transactions",
"reference": "YOUR_REFERENCE_4F7346",
"entityKey": {
"entityType": "paymentInstrument",
"entityReference": "PI3227C223222B5BPCMFXD2XG"
},
"status": models.TransactionRuleInfo.StatusEnum.Active,
"status": balancePlatform.TransactionRuleInfo.StatusEnum.Active,
"interval": {
"type": models.TransactionRuleInterval.TypeEnum.PerTransaction
"type": balancePlatform.TransactionRuleInterval.TypeEnum.PerTransaction
},
"ruleRestrictions": {
"processingTypes": {
"operation": "noneMatch",
"value": [
models.ProcessingTypesRestriction.ValueEnum.Pos
balancePlatform.ProcessingTypesRestriction.ValueEnum.Pos
]
}
},
"type": models.TransactionRuleInfo.TypeEnum.BlockList
"type": balancePlatform.TransactionRuleInfo.TypeEnum.BlockList
};
const response: models.TransactionRule = await balancePlatform.TransactionRules.create(request);
const response: balancePlatform.TransactionRule = await balancePlatformService.TransactionRules.create(request);
expect(response.id).toBe(transactionRuleId);
expect(response.status).toBe("active");
@@ -839,7 +839,7 @@ describe("Balance Platform", (): void => {
}
});
const response: models.TransactionRuleResponse = await balancePlatform.TransactionRules.retrieve(transactionRuleId);
const response: balancePlatform.TransactionRuleResponse = await balancePlatformService.TransactionRules.retrieve(transactionRuleId);
expect(response.transactionRule!.id).toBe(transactionRuleId);
expect(response.transactionRule!.type).toBe("velocity");
@@ -859,10 +859,10 @@ describe("Balance Platform", (): void => {
"id": transactionRuleId
});
const request: TransactionRuleInfoUpdate = {
"status": models.TransactionRuleInfo.StatusEnum.Inactive
"status": balancePlatform.TransactionRuleInfo.StatusEnum.Inactive
};
const response: models.TransactionRule = await balancePlatform.TransactionRules.update(transactionRuleId, request);
const response: balancePlatform.TransactionRule = await balancePlatformService.TransactionRules.update(transactionRuleId, request);
expect(response.status).toBe("inactive");
expect(response.reference).toBe("myRule12345");
@@ -886,7 +886,7 @@ describe("Balance Platform", (): void => {
"id": transactionRuleId
});
const response: models.TransactionRule = await balancePlatform.TransactionRules.delete(transactionRuleId);
const response: balancePlatform.TransactionRule = await balancePlatformService.TransactionRules.delete(transactionRuleId);
expect(response.id).toBe(transactionRuleId);
});

View File

@@ -3,11 +3,7 @@ import { createClient } from "../__mocks__/base";
import BinLookup from "../services/binLookup";
import Client from "../client";
import HttpClientException from "../httpClient/httpClientException";
import {
ThreeDSAvailabilityRequest,
ThreeDSAvailabilityResponse,
CostEstimateRequest,
} from "../typings/binlookup/models";
import { binlookup } from "../typings";
const threeDSAvailabilitySuccess = {
binDetails: {
@@ -19,7 +15,7 @@ const threeDSAvailabilitySuccess = {
};
let client: Client;
let binLookup: BinLookup;
let binLookupService: BinLookup;
let scope: nock.Scope;
beforeEach((): void => {
@@ -27,7 +23,7 @@ beforeEach((): void => {
nock.activate();
}
client = createClient();
binLookup = new BinLookup(client);
binLookupService = new BinLookup(client);
scope = nock(`${client.config.endpoint}${Client.BIN_LOOKUP_PAL_SUFFIX}${Client.BIN_LOOKUP_API_VERSION}`);
});
@@ -37,7 +33,7 @@ afterEach((): void => {
describe("Bin Lookup", function (): void {
test("should succeed on get 3ds availability", async function (): Promise<void> {
const threeDSAvailabilityRequest: ThreeDSAvailabilityRequest = {
const threeDSAvailabilityRequest: binlookup.ThreeDSAvailabilityRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
brands: ["randomBrand"],
cardNumber: "4111111111111111"
@@ -46,13 +42,12 @@ describe("Bin Lookup", function (): void {
scope.post("/get3dsAvailability")
.reply(200, threeDSAvailabilitySuccess);
const response = await binLookup.get3dsAvailability(threeDSAvailabilityRequest);
const response = await binLookupService.get3dsAvailability(threeDSAvailabilityRequest);
expect(response).toEqual<ThreeDSAvailabilityResponse>(threeDSAvailabilitySuccess);
expect(response).toEqual< binlookup.ThreeDSAvailabilityResponse>(threeDSAvailabilitySuccess);
});
test.each([false, true])("should fail with invalid merchant. isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
test("should fail with invalid merchant", async function (): Promise<void> {
const threeDSAvailabilityRequest: { [key: string]: undefined|string|[] } = {
merchantAccount: undefined,
cardNumber: "4111111111111",
@@ -63,15 +58,14 @@ describe("Bin Lookup", function (): void {
.reply(403, JSON.stringify({status: 403, message: "fail", errorCode: "171"}));
try {
await binLookup.get3dsAvailability(threeDSAvailabilityRequest as unknown as ThreeDSAvailabilityRequest);
await binLookupService.get3dsAvailability(threeDSAvailabilityRequest as unknown as binlookup.ThreeDSAvailabilityRequest);
fail("Expected request to fail");
} catch (e) {
expect(e instanceof HttpClientException).toBeTruthy();
}
});
test.each([false, true])("should succeed on get cost estimate. isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
test("should succeed on get cost estimate", async function (): Promise<void> {
const expected = {
cardBin: {
bin: "",
@@ -89,7 +83,7 @@ describe("Bin Lookup", function (): void {
resultCode: "Unsupported",
surchargeType: "ZERO"
};
const costEstimateRequest: CostEstimateRequest = {
const costEstimateRequest: binlookup.CostEstimateRequest = {
amount: { currency: "EUR", value: 1000 },
assumptions: {
assumeLevel3Data: true,
@@ -102,13 +96,13 @@ describe("Bin Lookup", function (): void {
mcc: "7411",
enrolledIn3DSecure: true
},
shopperInteraction: CostEstimateRequest.ShopperInteractionEnum.Ecommerce,
shopperInteraction: binlookup.CostEstimateRequest.ShopperInteractionEnum.Ecommerce,
};
scope.post("/getCostEstimate")
.reply(200, expected);
const response = await binLookup.getCostEstimate(costEstimateRequest);
const response = await binLookupService.getCostEstimate(costEstimateRequest);
expect(response).toEqual(expected);
});

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* eslint-disable @typescript-eslint/naming-convention */
import checkServerIdentity from "../helpers/checkServerIdentity";
import { PeerCertificate } from "tls";

View File

@@ -11,41 +11,19 @@ import {sessionsSuccess} from "../__mocks__/checkout/sessionsSuccess";
import Client from "../client";
import Checkout from "../services/checkout";
import HttpClientException from "../httpClient/httpClientException";
import {
Amount,
CardDetails,
CheckoutBalanceCheckRequest,
CheckoutBalanceCheckResponse,
CheckoutCancelOrderResponse,
CheckoutCreateOrderRequest,
CheckoutCreateOrderResponse,
CheckoutUtilityRequest,
CreatePaymentLinkRequest,
DetailsRequest,
PaymentLinkResponse,
PaymentMethodsRequest,
PaymentRequest,
PaymentResponse,
PaymentSetupRequest,
PaymentVerificationRequest,
CreateCheckoutSessionRequest,
CreateCheckoutSessionResponse,
CardDetailsRequest,
CardDetailsResponse
} from "../typings/checkout/models";
import { checkout } from "../typings";
const merchantAccount = process.env.ADYEN_MERCHANT!;
const reference = "Your order number";
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
function createAmountObject(currency: string, value: number): Amount {
function createAmountObject(currency: string, value: number): checkout.Amount {
return {
currency,
value,
};
}
function createPaymentsDetailsRequest(): DetailsRequest {
function createPaymentsDetailsRequest(): checkout.DetailsRequest {
return {
details: {
mD: "mdValue",
@@ -55,9 +33,9 @@ function createPaymentsDetailsRequest(): DetailsRequest {
};
}
export function createPaymentsCheckoutRequest(): PaymentRequest {
export function createPaymentsCheckoutRequest(): checkout.PaymentRequest {
const paymentMethodDetails = {
type: CardDetails.TypeEnum.Scheme,
type: checkout.CardDetails.TypeEnum.Scheme,
encryptedCardNumber: "test_4111111111111111",
encryptedExpiryMonth: "test_03",
encryptedExpiryYear: "test_2030",
@@ -75,18 +53,18 @@ export function createPaymentsCheckoutRequest(): PaymentRequest {
};
}
function createPaymentSessionRequest(): PaymentSetupRequest {
function createPaymentSessionRequest(): checkout.PaymentSetupRequest {
return {
amount: createAmountObject("USD", 1000),
countryCode: "NL",
merchantAccount,
reference,
returnUrl: "https://your-company.com/...",
channel: PaymentSetupRequest.ChannelEnum.Web,
channel: checkout.PaymentSetupRequest.ChannelEnum.Web,
sdkVersion: "3.7.0"
};
}
function getPaymentLinkSuccess(expiresAt: string): PaymentLinkResponse {
function getPaymentLinkSuccess(expiresAt: string): checkout.PaymentLinkResponse {
return {
amount: createAmountObject("USD", 1000),
expiresAt,
@@ -94,11 +72,11 @@ function getPaymentLinkSuccess(expiresAt: string): PaymentLinkResponse {
url: "PaymentLinkResponse.url",
id: "mocked_id",
merchantAccount,
status: PaymentLinkResponse.StatusEnum.Active
status: checkout.PaymentLinkResponse.StatusEnum.Active
};
}
function createPaymentLinkRequest(): CreatePaymentLinkRequest {
function createPaymentLinkRequest(): checkout.CreatePaymentLinkRequest {
return {
allowedPaymentMethods: ["scheme", "boletobancario"],
amount: createAmountObject("USD", 1000),
@@ -127,7 +105,7 @@ function createPaymentLinkRequest(): CreatePaymentLinkRequest {
};
}
function createSessionRequest(): CreateCheckoutSessionRequest {
function createSessionRequest(): checkout.CreateCheckoutSessionRequest {
return {
amount: createAmountObject("USD", 1000),
countryCode: "NL",
@@ -138,7 +116,7 @@ function createSessionRequest(): CreateCheckoutSessionRequest {
}
let client: Client;
let checkout: Checkout;
let checkoutService: Checkout;
let scope: nock.Scope;
beforeEach((): void => {
@@ -147,7 +125,7 @@ beforeEach((): void => {
}
client = createClient();
scope = nock(`${client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}`);
checkout = new Checkout(client);
checkoutService = new Checkout(client);
});
afterEach(() => {
@@ -156,55 +134,55 @@ afterEach(() => {
describe("Checkout", (): void => {
test("should add idempotency key to request headers", async (): Promise<void> => {
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const paymentsRequest: checkout.PaymentRequest = createPaymentsCheckoutRequest();
scope.post("/payments")
.reply(200, paymentsSuccess)
.matchHeader("Idempotency-Key", "testKey");
await checkout.payments(paymentsRequest, {idempotencyKey: "testKey"});
await checkoutService.payments(paymentsRequest, {idempotencyKey: "testKey"});
const paymentMethodsRequest: PaymentMethodsRequest = {merchantAccount};
const paymentMethodsRequest: checkout.PaymentMethodsRequest = {merchantAccount};
scope.post("/paymentMethods")
.reply(200, paymentMethodsSuccess)
.matchHeader("Idempotency-Key", "testKey");
await checkout.paymentMethods(paymentMethodsRequest, {idempotencyKey: "testKey"});
await checkoutService.paymentMethods(paymentMethodsRequest, {idempotencyKey: "testKey"});
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
const paymentLinkSuccess: checkout.PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
scope.post("/paymentLinks")
.reply(200, paymentLinkSuccess)
.matchHeader("Idempotency-Key", "testKey");
await checkout.paymentLinks(createPaymentLinkRequest(), {idempotencyKey: "testKey"});
await checkoutService.paymentLinks(createPaymentLinkRequest(), {idempotencyKey: "testKey"});
scope.patch("/paymentLinks/321")
.reply(200, { ...paymentLinkSuccess, status: "expired" })
.matchHeader("Idempotency-Key", "testKey");
await checkout.updatePaymentLinks("321", "expired", {idempotencyKey: "testKey"});
await checkoutService.updatePaymentLinks("321", "expired", {idempotencyKey: "testKey"});
scope.get("/paymentLinks/123")
.reply(200, paymentLinkSuccess)
.matchHeader("Idempotency-Key", "testKey");
await checkout.getPaymentLinks("123", {idempotencyKey: "testKey"});
await checkoutService.getPaymentLinks("123", {idempotencyKey: "testKey"});
scope.post("/payments/details")
.reply(200, paymentDetailsSuccess)
.matchHeader("Idempotency-Key", "testKey");
await checkout.paymentsDetails(createPaymentsDetailsRequest(), {idempotencyKey: "testKey"});
await checkoutService.paymentsDetails(createPaymentsDetailsRequest(), {idempotencyKey: "testKey"});
scope.post("/paymentSession")
.reply(200, paymentSessionSuccess)
.matchHeader("Idempotency-Key", "testKey");
const paymentSessionRequest: PaymentSetupRequest = createPaymentSessionRequest();
await checkout.paymentSession(paymentSessionRequest, {idempotencyKey: "testKey"});
const paymentSessionRequest: checkout.PaymentSetupRequest = createPaymentSessionRequest();
await checkoutService.paymentSession(paymentSessionRequest, {idempotencyKey: "testKey"});
scope.post("/payments/result")
.reply(200, paymentsResultSuccess)
.matchHeader("Idempotency-Key", "testKey");
const paymentResultRequest: PaymentVerificationRequest = {
const paymentResultRequest: checkout.PaymentVerificationRequest = {
payload: "This is a test payload",
};
await checkout.paymentResult(paymentResultRequest, {idempotencyKey: "testKey"});
await checkoutService.paymentResult(paymentResultRequest, {idempotencyKey: "testKey"});
const orderRequest: CheckoutCreateOrderRequest = {
const orderRequest: checkout.CheckoutCreateOrderRequest = {
amount: createAmountObject("USD", 1000),
merchantAccount,
reference
@@ -212,12 +190,12 @@ describe("Checkout", (): void => {
scope.post("/orders")
.reply(200, {})
.matchHeader("Idempotency-Key", "testKey");
await checkout.orders(orderRequest, {idempotencyKey: "testKey"});
await checkoutService.orders(orderRequest, {idempotencyKey: "testKey"});
scope.post("/orders/cancel")
.reply(200, {})
.matchHeader("Idempotency-Key", "testKey");
await checkout.ordersCancel({
await checkoutService.ordersCancel({
order: {
orderData: "mock_data",
pspReference: "mock_pspref"
@@ -229,43 +207,40 @@ describe("Checkout", (): void => {
.reply(200, sessionsSuccess)
.matchHeader("Idempotency-Key", "testKey");
const sessionsRequest: CreateCheckoutSessionRequest = createSessionRequest();
await checkout.sessions(sessionsRequest, {idempotencyKey: "testKey"});
const sessionsRequest: checkout.CreateCheckoutSessionRequest = createSessionRequest();
await checkoutService.sessions(sessionsRequest, {idempotencyKey: "testKey"});
});
test.each([false, true])("should make a payment. isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should make a payment.", async (): Promise<void> => {
scope.post("/payments")
.reply(200, paymentsSuccess);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: PaymentResponse = await checkout.payments(paymentsRequest);
const paymentsRequest: checkout.PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: checkout.PaymentResponse = await checkoutService.payments(paymentsRequest);
expect(paymentsResponse.pspReference).toBeTruthy();
});
test.each([false, true])("should return correct Exception, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should return correct Exception", async (): Promise<void> => {
try {
scope.post("/payments")
.reply(401);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
await checkout.payments(paymentsRequest);
const paymentsRequest: checkout.PaymentRequest = createPaymentsCheckoutRequest();
await checkoutService.payments(paymentsRequest);
} catch (e) {
expect(e instanceof HttpClientException).toBeTruthy();
}
});
test.each([false, true])("should have valid payment methods, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
const paymentMethodsRequest: PaymentMethodsRequest = {merchantAccount};
test("should have valid payment methods", async (): Promise<void> => {
const paymentMethodsRequest: checkout.PaymentMethodsRequest = {merchantAccount};
scope.post("/paymentMethods")
.reply(200, paymentMethodsSuccess);
const paymentMethodsResponse = await checkout.paymentMethods(paymentMethodsRequest);
const paymentMethodsResponse = await checkoutService.paymentMethods(paymentMethodsRequest);
if (paymentMethodsResponse && paymentMethodsResponse.paymentMethods) {
expect(paymentMethodsResponse.paymentMethods.length).toBeGreaterThan(0);
} else {
@@ -273,76 +248,69 @@ describe("Checkout", (): void => {
}
});
test.each([false, true])("should have valid payment link, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should have valid payment link", async (): Promise<void> => {
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
const paymentLinkSuccess: checkout.PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
scope.post("/paymentLinks").reply(200, paymentLinkSuccess);
const paymentSuccessLinkResponse = await checkout.paymentLinks(createPaymentLinkRequest());
const paymentSuccessLinkResponse = await checkoutService.paymentLinks(createPaymentLinkRequest());
expect(paymentSuccessLinkResponse).toBeTruthy();
});
test.each([isCI, true])("should get payment link, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should get payment link", async (): Promise<void> => {
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
const paymentLinkSuccess: checkout.PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
scope.post("/paymentLinks").reply(200, paymentLinkSuccess);
const paymentSuccessLinkResponse = await checkout.paymentLinks(createPaymentLinkRequest());
const paymentSuccessLinkResponse = await checkoutService.paymentLinks(createPaymentLinkRequest());
scope.get(`/paymentLinks/${paymentSuccessLinkResponse.id}`).reply(200, paymentLinkSuccess);
const paymentLink = await checkout.getPaymentLinks(paymentSuccessLinkResponse.id);
const paymentLink = await checkoutService.getPaymentLinks(paymentSuccessLinkResponse.id);
expect(paymentLink).toBeTruthy();
});
test.each([isCI, true])("should patch payment link, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should patch payment link", async (): Promise<void> => {
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
const paymentLinkSuccess: checkout.PaymentLinkResponse = getPaymentLinkSuccess(expiresAt);
scope.post("/paymentLinks").reply(200, paymentLinkSuccess);
const paymentSuccessLinkResponse = await checkout.paymentLinks(createPaymentLinkRequest());
const paymentSuccessLinkResponse = await checkoutService.paymentLinks(createPaymentLinkRequest());
scope.patch(`/paymentLinks/${paymentSuccessLinkResponse.id}`).reply(200, { ...paymentLinkSuccess, status: "expired" });
const paymentLink = await checkout.updatePaymentLinks(paymentSuccessLinkResponse.id, "expired");
const paymentLink = await checkoutService.updatePaymentLinks(paymentSuccessLinkResponse.id, "expired");
expect(paymentLink.status).toEqual("expired");
});
test.each([isCI, true])("should have payment details, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should have payment details", async (): Promise<void> => {
scope.post("/payments/details")
.reply(200, paymentDetailsSuccess);
const paymentsResponse = await checkout.paymentsDetails(createPaymentsDetailsRequest());
const paymentsResponse = await checkoutService.paymentsDetails(createPaymentsDetailsRequest());
expect(paymentsResponse.resultCode).toEqual("Authorised");
});
test.each([false, true])("should have payment session success, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should have payment session success", async (): Promise<void> => {
scope.post("/paymentSession")
.reply(200, paymentSessionSuccess);
const paymentSessionRequest: PaymentSetupRequest = createPaymentSessionRequest();
const paymentSessionResponse = await checkout.paymentSession(paymentSessionRequest);
const paymentSessionRequest: checkout.PaymentSetupRequest = createPaymentSessionRequest();
const paymentSessionResponse = await checkoutService.paymentSession(paymentSessionRequest);
expect(paymentSessionResponse.paymentSession).not.toBeUndefined();
});
test.each([isCI, true])("should have payments result, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should have payments result", async (): Promise<void> => {
scope.post("/payments/result")
.reply(200, paymentsResultSuccess);
const paymentResultRequest: PaymentVerificationRequest = {
const paymentResultRequest: checkout.PaymentVerificationRequest = {
payload: "This is a test payload",
};
const paymentResultResponse = await checkout.paymentResult(paymentResultRequest);
const paymentResultResponse = await checkoutService.paymentResult(paymentResultRequest);
expect(paymentResultResponse.resultCode).toEqual("Authorised");
});
test.each([false, true])("should have missing identifier on live, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should have missing identifier on live", async (): Promise<void> => {
client.setEnvironment("LIVE");
try {
new Checkout(client);
@@ -358,22 +326,20 @@ describe("Checkout", (): void => {
});
test.each([false, true])("should succeed on multibanco payment, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should succeed on multibanco payment", async (): Promise<void> => {
scope.post("/payments")
.reply(200, paymentsResultMultibancoSuccess);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: PaymentResponse = await checkout.payments(paymentsRequest);
const paymentsRequest: checkout.PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: checkout.PaymentResponse = await checkoutService.payments(paymentsRequest);
expect(paymentsResponse.pspReference).toBeTruthy();
expect(paymentsResponse.additionalData).toBeTruthy();
});
test.each([false, true])("should get origin keys. isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should get origin keys", async (): Promise<void> => {
const checkoutUtility = new Checkout(client);
const originKeysRequest: CheckoutUtilityRequest = {
const originKeysRequest: checkout.CheckoutUtilityRequest = {
originDomains: ["https://www.your-domain.com"],
};
@@ -389,78 +355,75 @@ describe("Checkout", (): void => {
});
// TODO: add gift card to PaymentMethod and unmock test
test.each([true, true])("should get payment methods balance", async (isMock): Promise<void> => {
!isMock && nock.restore();
const paymentMethodsRequest: CheckoutBalanceCheckRequest = {
test("should get payment methods balance", async (): Promise<void> => {
const paymentMethodsRequest: checkout.CheckoutBalanceCheckRequest = {
merchantAccount,
amount: createAmountObject("USD", 1000),
paymentMethod: { },
reference: "mocked_reference"
};
const paymentMethodsBalanceResponse: CheckoutBalanceCheckResponse = {
const paymentMethodsBalanceResponse: checkout.CheckoutBalanceCheckResponse = {
balance: {currency: "USD", value: 1000},
resultCode: CheckoutBalanceCheckResponse.ResultCodeEnum.Success
resultCode: checkout.CheckoutBalanceCheckResponse.ResultCodeEnum.Success
};
scope.post("/paymentMethods/balance")
.reply(200, paymentMethodsBalanceResponse);
const paymentsResponse: CheckoutBalanceCheckResponse = await checkout.paymentMethodsBalance(paymentMethodsRequest);
const paymentsResponse: checkout.CheckoutBalanceCheckResponse = await checkoutService.paymentMethodsBalance(paymentMethodsRequest);
expect(paymentsResponse.balance.value).toEqual(1000);
});
test.each([false, true])("should create order", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should create order", async (): Promise<void> => {
const expiresAt = "2019-12-17T10:05:29Z";
const orderRequest: CheckoutCreateOrderRequest = {
const orderRequest: checkout.CheckoutCreateOrderRequest = {
amount: createAmountObject("USD", 1000),
merchantAccount,
reference
};
const orderResponse: CheckoutCreateOrderResponse = {
const orderResponse: checkout.CheckoutCreateOrderResponse = {
expiresAt,
amount: createAmountObject("USD", 500),
orderData: "mocked_order_data",
remainingAmount: {currency: "USD", value: 500} ,
resultCode: CheckoutCreateOrderResponse.ResultCodeEnum.Success
resultCode: checkout.CheckoutCreateOrderResponse.ResultCodeEnum.Success
};
scope.post("/orders")
.reply(200, orderResponse);
const response: CheckoutCreateOrderResponse = await checkout.orders(orderRequest);
const response: checkout.CheckoutCreateOrderResponse = await checkoutService.orders(orderRequest);
expect(response).toBeTruthy();
});
test.each([false, true])("should cancel order", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should cancel order", async (): Promise<void> => {
const expiresAt = "2019-12-17T10:05:29Z";
const orderRequest: CheckoutCreateOrderRequest = {
const orderRequest: checkout.CheckoutCreateOrderRequest = {
amount: createAmountObject("USD", 1000),
merchantAccount,
reference
};
const orderResponse: CheckoutCreateOrderResponse = {
const orderResponse: checkout.CheckoutCreateOrderResponse = {
expiresAt,
amount: createAmountObject("USD", 500),
orderData: "mocked_order_data",
remainingAmount: {currency: "USD", value: 500},
resultCode: CheckoutCreateOrderResponse.ResultCodeEnum.Success
resultCode: checkout.CheckoutCreateOrderResponse.ResultCodeEnum.Success
};
scope.post("/orders")
.reply(200, orderResponse);
const createOrderResponse: CheckoutCreateOrderResponse = await checkout.orders(orderRequest);
const createOrderResponse: checkout.CheckoutCreateOrderResponse = await checkoutService.orders(orderRequest);
const orderCancelResponse: CheckoutCancelOrderResponse = {
const orderCancelResponse: checkout.CheckoutCancelOrderResponse = {
pspReference: "mocked_psp_ref",
resultCode: CheckoutCancelOrderResponse.ResultCodeEnum.Received
resultCode: checkout.CheckoutCancelOrderResponse.ResultCodeEnum.Received
};
scope.post("/orders/cancel")
.reply(200, orderCancelResponse);
const response: CheckoutCancelOrderResponse = await checkout.ordersCancel({
const response: checkout.CheckoutCancelOrderResponse = await checkoutService.ordersCancel({
order: {
orderData: createOrderResponse.orderData,
pspReference: createOrderResponse.pspReference!
@@ -470,13 +433,12 @@ describe("Checkout", (): void => {
expect(response).toBeTruthy();
});
test.each([false, true])("should create a session. isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should create a session.", async (): Promise<void> => {
scope.post("/sessions")
.reply(200, sessionsSuccess);
const sessionsRequest: CreateCheckoutSessionRequest = createSessionRequest();
const sessionsResponse: CreateCheckoutSessionResponse = await checkout.sessions(sessionsRequest);
const sessionsRequest: checkout.CreateCheckoutSessionRequest = createSessionRequest();
const sessionsResponse: checkout.CreateCheckoutSessionResponse = await checkoutService.sessions(sessionsRequest);
expect(sessionsResponse.sessionData).toBeTruthy();
expect(sessionsResponse.expiresAt).toBeInstanceOf(Date);
expect(sessionsResponse.expiresAt.getFullYear()).toBeGreaterThan(0);
@@ -493,11 +455,11 @@ describe("Checkout", (): void => {
]
});
const cardDetailsRequest: CardDetailsRequest = {
const cardDetailsRequest: checkout.CardDetailsRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"cardNumber": "411111"
};
const cardDetailsReponse: CardDetailsResponse = await checkout.cardDetails(cardDetailsRequest);
const cardDetailsReponse: checkout.CardDetailsResponse = await checkoutService.cardDetails(cardDetailsRequest);
expect(cardDetailsReponse?.brands?.length).toBe(1);
});
});

View File

@@ -2,23 +2,7 @@ import nock from "nock";
import {createClient} from "../__mocks__/base";
import Client from "../client";
import ClassicIntegration from "../services/classicIntegration";
import { PaymentRequest } from "../typings/payments/paymentRequest";
import { PaymentResult } from "../typings/payments/paymentResult";
import { PaymentRequest3d } from "../typings/payments/paymentRequest3d";
import { PaymentRequest3ds2 } from "../typings/payments/paymentRequest3ds2";
import { AuthenticationResultRequest } from "../typings/payments/authenticationResultRequest";
import { AuthenticationResultResponse } from "../typings/payments/authenticationResultResponse";
import { ThreeDS2ResultRequest } from "../typings/payments/threeDS2ResultRequest";
import { ThreeDS2ResultResponse } from "../typings/payments/threeDS2ResultResponse";
import { ModificationResult } from "../typings/payments/modificationResult";
import { CaptureRequest } from "../typings/payments/captureRequest";
import { CancelRequest } from "../typings/payments/cancelRequest";
import { RefundRequest } from "../typings/payments/refundRequest";
import { CancelOrRefundRequest } from "../typings/payments/cancelOrRefundRequest";
import { TechnicalCancelRequest } from "../typings/payments/technicalCancelRequest";
import { AdjustAuthorisationRequest } from "../typings/payments/adjustAuthorisationRequest";
import { DonationRequest } from "../typings/payments/donationRequest";
import { VoidPendingRefundRequest } from "../typings/payments/voidPendingRefundRequest";
import { payments } from "../typings";
let client: Client;
let classicIntegration: ClassicIntegration;
@@ -50,7 +34,7 @@ describe("Classic Integration", (): void => {
"authCode": "011381"
}
);
const paymentRequest: PaymentRequest = {
const paymentRequest: payments.PaymentRequest = {
"card": {
"number": "4111111111111111",
"expiryMonth": "03",
@@ -66,7 +50,7 @@ describe("Classic Integration", (): void => {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const paymentResult: PaymentResult = await classicIntegration.authorise(paymentRequest);
const paymentResult: payments.PaymentResult = await classicIntegration.authorise(paymentRequest);
expect(paymentResult.pspReference).toEqual("JVBXGSDM53RZNN82");
});
@@ -82,14 +66,14 @@ describe("Classic Integration", (): void => {
"authCode": "011381"
}
);
const paymentRequest: PaymentRequest3d = {
const paymentRequest: payments.PaymentRequest3d = {
"md": "31h..........vOXek7w",
"paResponse": "eNqtmF........wGVA4Ch",
"shopperIP": "61.294.12.12",
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const paymentResult: PaymentResult = await classicIntegration.authorise3d(paymentRequest);
const paymentResult: payments.PaymentResult = await classicIntegration.authorise3d(paymentRequest);
expect(paymentResult.pspReference).toEqual("JVBXGSDM53RZNN82");
});
@@ -105,7 +89,7 @@ describe("Classic Integration", (): void => {
"authCode": "011381"
}
);
const paymentRequest: PaymentRequest3ds2 = {
const paymentRequest: payments.PaymentRequest3ds2 = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"amount": {
"value": 1500,
@@ -119,7 +103,7 @@ describe("Classic Integration", (): void => {
"threeDS2Token": "— - BINARY DATA - -"
};
const paymentResult: PaymentResult = await classicIntegration.authorise3ds2(paymentRequest);
const paymentResult: payments.PaymentResult = await classicIntegration.authorise3ds2(paymentRequest);
expect(paymentResult.pspReference).toEqual("JVBXGSDM53RZNN82");
});
@@ -128,12 +112,12 @@ describe("Classic Integration", (): void => {
"threeDS2Result": { "authenticationValue": "THREEDS2RESULT"}
});
const getAuthenticationResultrequest: AuthenticationResultRequest = {
const getAuthenticationResultrequest: payments.AuthenticationResultRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"pspReference": "9935272408535455"
};
const getAuthenticationResultResponse: AuthenticationResultResponse = await classicIntegration.getAuthenticationResult(getAuthenticationResultrequest);
const getAuthenticationResultResponse: payments.AuthenticationResultResponse = await classicIntegration.getAuthenticationResult(getAuthenticationResultrequest);
expect(getAuthenticationResultResponse?.threeDS2Result?.authenticationValue).toEqual("THREEDS2RESULT");
});
@@ -141,12 +125,12 @@ describe("Classic Integration", (): void => {
scope.post("/retrieve3ds2Result").reply(200, {
"threeDS2Result": { "authenticationValue": "THREEDS2RESULT"}
});
const retrieve3ds2ResultRequest: ThreeDS2ResultRequest = {
const retrieve3ds2ResultRequest: payments.ThreeDS2ResultRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"pspReference": "9935272408535455"
};
const retrieve3ds2ResultResponse: ThreeDS2ResultResponse = await classicIntegration.retrieve3ds2Result(retrieve3ds2ResultRequest);
const retrieve3ds2ResultResponse: payments.ThreeDS2ResultResponse = await classicIntegration.retrieve3ds2Result(retrieve3ds2ResultRequest);
expect(retrieve3ds2ResultResponse?.threeDS2Result?.authenticationValue).toEqual("THREEDS2RESULT");
});
@@ -157,7 +141,7 @@ describe("Classic Integration", (): void => {
"response": "[capture-received]"
});
const modificationRequest: CaptureRequest = {
const modificationRequest: payments.CaptureRequest = {
"originalReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"modificationAmount": {
"value": 500,
@@ -167,8 +151,8 @@ describe("Classic Integration", (): void => {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.capture(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.CaptureReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.capture(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.CaptureReceived);
});
test("Should succesfully send Cancel request", async (): Promise<void> => {
@@ -178,14 +162,14 @@ describe("Classic Integration", (): void => {
"response": "[cancel-received]"
});
const modificationRequest: CancelRequest = {
const modificationRequest: payments.CancelRequest = {
"originalReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"reference": "YourModificationReference",
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.cancel(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.CancelReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.cancel(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.CancelReceived);
});
test("Should succesfully send Refund request", async (): Promise<void> => {
@@ -195,7 +179,7 @@ describe("Classic Integration", (): void => {
"response": "[refund-received]"
});
const modificationRequest: RefundRequest = {
const modificationRequest: payments.RefundRequest = {
"originalReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"modificationAmount": {
"value": 500,
@@ -205,8 +189,8 @@ describe("Classic Integration", (): void => {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.refund(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.RefundReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.refund(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.RefundReceived);
});
test("Should succesfully send CancelOrRefund request", async (): Promise<void> => {
@@ -216,14 +200,14 @@ describe("Classic Integration", (): void => {
"response": "[cancelOrRefund-received]"
});
const modificationRequest: CancelOrRefundRequest = {
const modificationRequest: payments.CancelOrRefundRequest = {
"originalReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"reference": "YourModificationReference",
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.cancelOrRefund(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.CancelOrRefundReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.cancelOrRefund(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.CancelOrRefundReceived);
});
test("Should succesfully send TechnicalCancel request", async (): Promise<void> => {
@@ -233,7 +217,7 @@ describe("Classic Integration", (): void => {
"response": "[technical-cancel-received]"
});
const modificationRequest: TechnicalCancelRequest = {
const modificationRequest: payments.TechnicalCancelRequest = {
"originalMerchantReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"modificationAmount": {
"value": 500,
@@ -243,8 +227,8 @@ describe("Classic Integration", (): void => {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.technicalCancel(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.TechnicalCancelReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.technicalCancel(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.TechnicalCancelReceived);
});
test("Should succesfully send AdjustAuthorisation request", async (): Promise<void> => {
@@ -254,7 +238,7 @@ describe("Classic Integration", (): void => {
"response": "[adjustAuthorisation-received]"
});
const modificationRequest: AdjustAuthorisationRequest = {
const modificationRequest: payments.AdjustAuthorisationRequest = {
"originalReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"modificationAmount": {
"value": 500,
@@ -264,8 +248,8 @@ describe("Classic Integration", (): void => {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.adjustAuthorisation(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.AdjustAuthorisationReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.adjustAuthorisation(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.AdjustAuthorisationReceived);
});
test("Should succesfully send Donate request", async (): Promise<void> => {
@@ -275,7 +259,7 @@ describe("Classic Integration", (): void => {
"response": "[donation-received]"
});
const modificationRequest: DonationRequest = {
const modificationRequest: payments.DonationRequest = {
"originalReference": "COPY_PSP_REFERENCE_FROM_AUTHORISE_RESPONSE",
"modificationAmount": {
"value": 500,
@@ -286,8 +270,8 @@ describe("Classic Integration", (): void => {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT"
};
const modificationResult: ModificationResult = await classicIntegration.donate(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.DonationReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.donate(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.DonationReceived);
});
test("Should succesfully send VoidPendingRefund request", async (): Promise<void> => {
@@ -297,13 +281,13 @@ describe("Classic Integration", (): void => {
"response": "[voidPendingRefund-received]"
});
const modificationRequest: VoidPendingRefundRequest = {
const modificationRequest: payments.VoidPendingRefundRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"tenderReference": "5Iw8001176969533005",
"uniqueTerminalId": "VX820-123456789"
};
const modificationResult: ModificationResult = await classicIntegration.voidPendingRefund(modificationRequest);
expect(modificationResult.response).toEqual(ModificationResult.ResponseEnum.VoidPendingRefundReceived);
const modificationResult: payments.ModificationResult = await classicIntegration.voidPendingRefund(modificationRequest);
expect(modificationResult.response).toEqual(payments.ModificationResult.ResponseEnum.VoidPendingRefundReceived);
});
});

View File

@@ -0,0 +1,11 @@
import Client from "../client";
describe("API Client", function (): void {
test("should be able to make a request using basic auth", async function (): Promise<void> {
new Client({
username: process.env.ADYEN_USER!,
password: process.env.ADYEN_PASSWORD!,
environment: "TEST"
});
});
});

View File

@@ -3,10 +3,10 @@ import { createClient } from "../__mocks__/base";
import { DataProtection } from "../services";
import Client from "../client";
import HttpClientException from "../httpClient/httpClientException";
import {SubjectErasureByPspReferenceRequest, SubjectErasureResponse } from "../typings/dataProtection/models";
import { dataProtection } from "../typings";
let client: Client,
dataProtection: DataProtection,
dataProtectionService: DataProtection,
scope: nock.Scope;
beforeEach((): void => {
@@ -14,7 +14,7 @@ beforeEach((): void => {
nock.activate();
}
client = createClient();
dataProtection = new DataProtection(client);
dataProtectionService = new DataProtection(client);
scope = nock(`${client.config.dataProtectionEndpoint}/${Client.DATA_PROTECTION_API_VERSION}`);
});
@@ -24,11 +24,11 @@ afterEach(() => {
describe("DataProtection", (): void => {
test("should make succesful subjectErasure call", async (): Promise<void> => {
const requestSubjectErasureSuccess: SubjectErasureResponse = {
"result": SubjectErasureResponse.ResultEnum.Success,
const requestSubjectErasureSuccess: dataProtection.SubjectErasureResponse = {
"result": dataProtection.SubjectErasureResponse.ResultEnum.Success,
};
const requestSubjectErasureRequest: SubjectErasureByPspReferenceRequest = {
const requestSubjectErasureRequest: dataProtection.SubjectErasureByPspReferenceRequest = {
"merchantAccount": "MY_MERCHANT_ACCOUNT",
"forceErasure": true,
"pspReference": "0123456789"
@@ -37,22 +37,21 @@ describe("DataProtection", (): void => {
scope.post("/requestSubjectErasure")
.reply(200, requestSubjectErasureSuccess);
const response: SubjectErasureResponse = await dataProtection.requestSubjectErasure(requestSubjectErasureRequest);
expect(response.result).toEqual(SubjectErasureResponse.ResultEnum.Success);
const response: dataProtection.SubjectErasureResponse = await dataProtectionService.requestSubjectErasure(requestSubjectErasureRequest);
expect(response.result).toEqual(dataProtection.SubjectErasureResponse.ResultEnum.Success);
});
test.each([false, true])("should return correct Exception, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should return correct Exception", async (): Promise<void> => {
try {
scope.post("/requestSubjectErasure")
.reply(401);
const requestSubjectErasureRequest: SubjectErasureByPspReferenceRequest = {
const requestSubjectErasureRequest: dataProtection.SubjectErasureByPspReferenceRequest = {
"merchantAccount": "MY_MERCHANT_ACCOUNT",
"forceErasure": true,
"pspReference": "0123456789"
};
await dataProtection.requestSubjectErasure(requestSubjectErasureRequest);
await dataProtectionService.requestSubjectErasure(requestSubjectErasureRequest);
} catch (e) {
expect(e instanceof HttpClientException).toBeTruthy();
}

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import HmacValidator from "../utils/hmacValidator";
import {NotificationItem, NotificationRequestItem } from "../typings/notification/models";
import { ApiConstants } from "../constants/apiConstants";

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock, { Interceptor } from "nock";
import Client from "../client";
import Checkout from "../services/checkout";

View File

@@ -2,13 +2,12 @@ import nock from "nock";
import Client from "../client";
import { createClient } from "../__mocks__/base";
import { Management } from "../services";
import { AllowedOrigin, AllowedOriginsResponse, MeApiCredential } from "../typings/management/models";
import * as models from "../typings/management/models";
import { management } from "../typings";
import * as requests from "../__mocks__/management/requests";
import * as responses from "../__mocks__/management/responses";
let client: Client;
let management: Management;
let managementService: Management;
let scope: nock.Scope;
const merchantId = "merchantId";
@@ -26,7 +25,7 @@ beforeEach((): void => {
}
client = createClient();
scope = nock(`${client.config.managementEndpoint}/${Client.MANAGEMENT_API_VERSION}`);
management = new Management(client);
managementService = new Management(client);
});
afterEach(() => {
@@ -63,7 +62,7 @@ describe("Management", (): void => {
"companyName": "Test",
"active": true,
});
const meResponse: MeApiCredential = await management.Me.retrieve();
const meResponse: management.MeApiCredential = await managementService.Me.retrieve();
expect(meResponse.id).toEqual("S2-6262224667");
});
@@ -78,11 +77,11 @@ describe("Management", (): void => {
}
}
});
const allowedOriginRequest: AllowedOrigin = {
const allowedOriginRequest: management.AllowedOrigin = {
"domain": "https://www.us.mystore.com"
};
const allowedOriginsResponse: AllowedOrigin = await management.Me.createAllowedOrigin(allowedOriginRequest);
const allowedOriginsResponse: management.AllowedOrigin = await managementService.Me.createAllowedOrigin(allowedOriginRequest);
expect(allowedOriginsResponse.domain).toEqual("https://www.us.mystore.com");
});
@@ -102,7 +101,7 @@ describe("Management", (): void => {
]
});
const allowedOriginsResponse: AllowedOriginsResponse = await management.Me.retrieveAllowedOrigins();
const allowedOriginsResponse: management.AllowedOriginsResponse = await managementService.Me.retrieveAllowedOrigins();
expect(allowedOriginsResponse.data?.length).toEqual(1);
});
});
@@ -119,13 +118,13 @@ describe("Management", (): void => {
}
});
const allowedOriginResponse: AllowedOrigin = await management.Me.retrieveAllowedOrigin("S2-123123123123123");
const allowedOriginResponse: management.AllowedOrigin = await managementService.Me.retrieveAllowedOrigin("S2-123123123123123");
expect(allowedOriginResponse.id).toEqual("S2-123123123123123");
});
test("Should remove the allowed origin specified in the path", async () => {
scope.delete("/me/allowedOrigins/S2-123123123123123").reply(204, {});
const allowedOriginResponse: Record<string, unknown> = await management.Me.deleteAllowerdOrigin("S2-123123123123123");
const allowedOriginResponse: Record<string, unknown> = await managementService.Me.deleteAllowerdOrigin("S2-123123123123123");
expect(scope.isDone()).toBe(true);
expect(Object.entries(allowedOriginResponse).length).toBe(0);
});
@@ -135,7 +134,7 @@ describe("Management", (): void => {
scope.get("/merchants?pageNumber=1&pageSize=1")
.reply(200, responses.listMerchantResponse);
const response: models.ListMerchantResponse = await management.MerchantAccount.list({
const response: management.ListMerchantResponse = await managementService.MerchantAccount.list({
params: {
"pageNumber": "1",
"pageSize": "1"
@@ -149,7 +148,7 @@ describe("Management", (): void => {
scope.post("/merchants")
.reply(200, responses.createMerchantResponse);
const response: models.CreateMerchantResponse = await management.MerchantAccount.create(requests.createMerchantRequest);
const response: management.CreateMerchantResponse = await managementService.MerchantAccount.create(requests.createMerchantRequest);
expect(response).toBeTruthy();
});
@@ -158,7 +157,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}`)
.reply(200, responses.merchant);
const response: models.Merchant = await management.MerchantAccount.retrieve(merchantId);
const response: management.Merchant = await managementService.MerchantAccount.retrieve(merchantId);
expect(response).toBeTruthy();
});
@@ -167,7 +166,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/activate`)
.reply(200, responses.requestActivationResponse);
const response: models.RequestActivationResponse = await management.MerchantAccount.activate(merchantId);
const response: management.RequestActivationResponse = await managementService.MerchantAccount.activate(merchantId);
expect(response).toBeTruthy();
});
@@ -178,7 +177,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}/allowedOrigins`)
.reply(200, responses.allowedOriginsResponse);
const response: models.AllowedOriginsResponse = await management.MerchantAllowedOrigins.list(merchantId, apiCredentialId);
const response: management.AllowedOriginsResponse = await managementService.MerchantAllowedOrigins.list(merchantId, apiCredentialId);
expect(response).toBeTruthy();
});
@@ -187,7 +186,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}/allowedOrigins`)
.reply(200, responses.allowedOriginsResponse);
const response: models.AllowedOriginsResponse = await management.MerchantAllowedOrigins.create(merchantId, apiCredentialId, requests.allowedOrigin);
const response: management.AllowedOriginsResponse = await managementService.MerchantAllowedOrigins.create(merchantId, apiCredentialId, requests.allowedOrigin);
expect(response).toBeTruthy();
});
@@ -196,14 +195,14 @@ describe("Management", (): void => {
scope.delete(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}/allowedOrigins/${originId}`)
.reply(204);
await management.MerchantAllowedOrigins.delete(merchantId, apiCredentialId, originId);
await managementService.MerchantAllowedOrigins.delete(merchantId, apiCredentialId, originId);
});
it("should support GET /merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}", async (): Promise<void> => {
scope.get(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}/allowedOrigins/${originId}`)
.reply(200, responses.allowedOrigin);
const response: models.AllowedOrigin = await management.MerchantAllowedOrigins.retrieve(merchantId, apiCredentialId, originId);
const response: management.AllowedOrigin = await managementService.MerchantAllowedOrigins.retrieve(merchantId, apiCredentialId, originId);
expect(response).toBeTruthy();
});
@@ -214,7 +213,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/apiCredentials?pageNumber=1&pageSize=1`)
.reply(200, responses.listMerchantApiCredentialsResponse);
const response: models.ListMerchantApiCredentialsResponse = await management.MerchantApiCredentials.list(merchantId, {
const response: management.ListMerchantApiCredentialsResponse = await managementService.MerchantApiCredentials.list(merchantId, {
params: {
"pageNumber": "1",
"pageSize": "1"
@@ -228,7 +227,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/apiCredentials`)
.reply(200, responses.createApiCredentialResponse);
const response: models.CreateApiCredentialResponse = await management.MerchantApiCredentials.create(merchantId, requests.createMerchantApiCredentialRequest);
const response: management.CreateApiCredentialResponse = await managementService.MerchantApiCredentials.create(merchantId, requests.createMerchantApiCredentialRequest);
expect(response).toBeTruthy();
});
@@ -237,7 +236,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}`)
.reply(200, responses.apiCredential);
const response: models.ApiCredential = await management.MerchantApiCredentials.retrieve(merchantId, apiCredentialId);
const response: management.ApiCredential = await managementService.MerchantApiCredentials.retrieve(merchantId, apiCredentialId);
expect(response).toBeTruthy();
});
@@ -246,7 +245,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}`)
.reply(200, responses.apiCredential);
const response: models.ApiCredential = await management.MerchantApiCredentials.update(merchantId, apiCredentialId, requests.updateMerchantApiCredentialRequest);
const response: management.ApiCredential = await managementService.MerchantApiCredentials.update(merchantId, apiCredentialId, requests.updateMerchantApiCredentialRequest);
expect(response).toBeTruthy();
});
@@ -257,7 +256,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}/generateApiKey`)
.reply(200, responses.generateApiKeyResponse);
const response: models.GenerateApiKeyResponse = await management.MerchantApiKey.create(merchantId, apiCredentialId);
const response: management.GenerateApiKeyResponse = await managementService.MerchantApiKey.create(merchantId, apiCredentialId);
expect(response).toBeTruthy();
});
@@ -268,7 +267,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/apiCredentials/${apiCredentialId}/generateClientKey`)
.reply(200, responses.generateClientKeyResponse);
const response: models.GenerateClientKeyResponse = await management.MerchantClientKey.create(merchantId, apiCredentialId);
const response: management.GenerateClientKeyResponse = await managementService.MerchantClientKey.create(merchantId, apiCredentialId);
expect(response).toBeTruthy();
});
@@ -279,7 +278,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/paymentMethodSettings?storeId=1&businessLineId=1&pageNumber=1&pageSize=1`)
.reply(200, responses.paymentMethodResponse);
const response: models.PaymentMethodResponse = await management.MerchantPaymentMethods.listPaymentMethodSettings(merchantId, {
const response: management.PaymentMethodResponse = await managementService.MerchantPaymentMethods.listPaymentMethodSettings(merchantId, {
params: {
"storeId": "1",
"businessLineId": "1",
@@ -295,9 +294,9 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/paymentMethodSettings`)
.reply(200, responses.paymentMethod);
const response: models.PaymentMethod = await management.MerchantPaymentMethods.create(merchantId, {
const response: management.PaymentMethod = await managementService.MerchantPaymentMethods.create(merchantId, {
...requests.paymentMethodSetupInfo,
type: models.PaymentMethodSetupInfo.TypeEnum.Ideal
type: management.PaymentMethodSetupInfo.TypeEnum.Ideal
});
expect(response).toBeTruthy();
@@ -307,7 +306,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/paymentMethodSettings/${paymentMethodId}`)
.reply(200, responses.paymentMethod);
const response: models.PaymentMethod = await management.MerchantPaymentMethods.retrieve(merchantId, paymentMethodId);
const response: management.PaymentMethod = await managementService.MerchantPaymentMethods.retrieve(merchantId, paymentMethodId);
expect(response).toBeTruthy();
});
@@ -316,7 +315,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/paymentMethodSettings/${paymentMethodId}`)
.reply(200, responses.paymentMethod);
const response: models.PaymentMethod = await management.MerchantPaymentMethods.update(merchantId, paymentMethodId, requests.updatePaymentMethodInfo);
const response: management.PaymentMethod = await managementService.MerchantPaymentMethods.update(merchantId, paymentMethodId, requests.updatePaymentMethodInfo);
expect(response).toBeTruthy();
});
@@ -327,7 +326,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/payoutSettings`)
.reply(200, responses.payoutSettingsResponse);
const response: models.PayoutSettingsResponse = await management.MerchantPayoutSettings.listPayoutSettings(merchantId);
const response: management.PayoutSettingsResponse = await managementService.MerchantPayoutSettings.listPayoutSettings(merchantId);
expect(response).toBeTruthy();
});
@@ -336,7 +335,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/payoutSettings`)
.reply(200, responses.payoutSettings);
const response: models.PayoutSettings = await management.MerchantPayoutSettings.create(merchantId, requests.payoutSettingsRequest);
const response: management.PayoutSettings = await managementService.MerchantPayoutSettings.create(merchantId, requests.payoutSettingsRequest);
expect(response).toBeTruthy();
});
@@ -345,14 +344,14 @@ describe("Management", (): void => {
scope.delete(`/merchants/${merchantId}/payoutSettings/${payoutSettingsId}`)
.reply(200);
await management.MerchantPayoutSettings.delete(merchantId, payoutSettingsId);
await managementService.MerchantPayoutSettings.delete(merchantId, payoutSettingsId);
});
it("should support GET /merchants/{merchantId}/payoutSettings/{payoutSettingsId}", async (): Promise<void> => {
scope.get(`/merchants/${merchantId}/payoutSettings/${payoutSettingsId}`)
.reply(200, responses.payoutSettings);
const response: models.PayoutSettings = await management.MerchantPayoutSettings.retrieve(merchantId, payoutSettingsId);
const response: management.PayoutSettings = await managementService.MerchantPayoutSettings.retrieve(merchantId, payoutSettingsId);
expect(response).toBeTruthy();
});
@@ -361,7 +360,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/payoutSettings/${payoutSettingsId}`)
.reply(200, responses.payoutSettings);
const response: models.PayoutSettings = await management.MerchantPayoutSettings.update(merchantId, payoutSettingsId, requests.updatePayoutSettingsRequest);
const response: management.PayoutSettings = await managementService.MerchantPayoutSettings.update(merchantId, payoutSettingsId, requests.updatePayoutSettingsRequest);
expect(response).toBeTruthy();
});
@@ -372,7 +371,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/billingEntities?name=bill`)
.reply(200, responses.billingEntitiesResponse);
const response: models.BillingEntitiesResponse = await management.MerchantTerminalOrders.listBillingEntities(merchantId, {
const response: management.BillingEntitiesResponse = await managementService.MerchantTerminalOrders.listBillingEntities(merchantId, {
params: {
"name": "bill"
}
@@ -385,7 +384,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/shippingLocations?name=1&offset=1&limit=1`)
.reply(200, responses.shippingLocationsResponse);
const response: models.ShippingLocationsResponse = await management.MerchantTerminalOrders.listShippingLocations(merchantId, {
const response: management.ShippingLocationsResponse = await managementService.MerchantTerminalOrders.listShippingLocations(merchantId, {
params: {
"name": "1",
"offset": "1",
@@ -400,7 +399,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/shippingLocations`)
.reply(200, responses.shippingLocation);
const response: models.ShippingLocation = await management.MerchantTerminalOrders.createShippingLocation(merchantId, requests.shippingLocation);
const response: management.ShippingLocation = await managementService.MerchantTerminalOrders.createShippingLocation(merchantId, requests.shippingLocation);
expect(response).toBeTruthy();
});
@@ -409,7 +408,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/terminalModels`)
.reply(200, responses.terminalModelsResponse);
const response: models.TerminalModelsResponse = await management.MerchantTerminalOrders.listTerminalModels(merchantId);
const response: management.TerminalModelsResponse = await managementService.MerchantTerminalOrders.listTerminalModels(merchantId);
expect(response).toBeTruthy();
});
@@ -418,7 +417,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/terminalOrders?customerOrderReference=1&status=1&offset=1&limit=1`)
.reply(200, responses.terminalOrdersResponse);
const response: models.TerminalOrdersResponse = await management.MerchantTerminalOrders.listTerminalOrders(merchantId, {
const response: management.TerminalOrdersResponse = await managementService.MerchantTerminalOrders.listTerminalOrders(merchantId, {
params: {
"customerOrderReference": "1",
"status": "1",
@@ -434,7 +433,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/terminalOrders`)
.reply(200, responses.terminalOrder);
const response: models.TerminalOrder = await management.MerchantTerminalOrders.create(merchantId, requests.terminalOrderRequest);
const response: management.TerminalOrder = await managementService.MerchantTerminalOrders.create(merchantId, requests.terminalOrderRequest);
expect(response).toBeTruthy();
});
@@ -443,7 +442,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/terminalOrders/${orderId}`)
.reply(200, responses.terminalOrder);
const response: models.TerminalOrder = await management.MerchantTerminalOrders.retrieve(merchantId, orderId);
const response: management.TerminalOrder = await managementService.MerchantTerminalOrders.retrieve(merchantId, orderId);
expect(response).toBeTruthy();
});
@@ -452,7 +451,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/terminalOrders/${orderId}`)
.reply(200, responses.terminalOrder);
const response: models.TerminalOrder = await management.MerchantTerminalOrders.update(merchantId, orderId, requests.terminalOrderRequest);
const response: management.TerminalOrder = await managementService.MerchantTerminalOrders.update(merchantId, orderId, requests.terminalOrderRequest);
expect(response).toBeTruthy();
});
@@ -461,7 +460,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/terminalOrders/${orderId}/cancel`)
.reply(200, responses.terminalOrder);
const response: models.TerminalOrder = await management.MerchantTerminalOrders.cancel(merchantId, orderId);
const response: management.TerminalOrder = await managementService.MerchantTerminalOrders.cancel(merchantId, orderId);
expect(response).toBeTruthy();
});
@@ -470,7 +469,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/terminalProducts?country=1&terminalModelId=1&offset=1&limit=1`)
.reply(200, responses.terminalProductsResponse);
const response: models.TerminalProductsResponse = await management.MerchantTerminalOrders.listTerminalProducts(merchantId, {
const response: management.TerminalProductsResponse = await managementService.MerchantTerminalOrders.listTerminalProducts(merchantId, {
params: {
"country": "1",
"terminalModelId": "1",
@@ -488,7 +487,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/terminalLogos?model=1`)
.reply(200, responses.logo);
const response: models.Logo = await management.MerchantTerminalSettings.retrieveLogo(merchantId, {
const response: management.Logo = await managementService.MerchantTerminalSettings.retrieveLogo(merchantId, {
params: {
"model": "1"
}
@@ -501,7 +500,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/terminalLogos?model=1`)
.reply(200, responses.logo);
const response: models.Logo = await management.MerchantTerminalSettings.updateLogo(merchantId, requests.logo, {
const response: management.Logo = await managementService.MerchantTerminalSettings.updateLogo(merchantId, requests.logo, {
params: {
"model": "1"
}
@@ -514,7 +513,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/terminalSettings`)
.reply(200, responses.terminalSettings);
const response: models.TerminalSettings = await management.MerchantTerminalSettings.retrieve(merchantId);
const response: management.TerminalSettings = await managementService.MerchantTerminalSettings.retrieve(merchantId);
expect(response).toBeTruthy();
});
@@ -523,7 +522,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/terminalSettings`)
.reply(200, responses.terminalSettings);
const response: models.TerminalSettings = await management.MerchantTerminalSettings.update(merchantId, requests.terminalSettings);
const response: management.TerminalSettings = await managementService.MerchantTerminalSettings.update(merchantId, requests.terminalSettings);
expect(response).toBeTruthy();
});
@@ -534,7 +533,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/users?pageNumber=1&pageSize=1`)
.reply(200, responses.listMerchantUsersResponse);
const response: models.ListMerchantUsersResponse = await management.MerchantUsers.list(merchantId, {
const response: management.ListMerchantUsersResponse = await managementService.MerchantUsers.list(merchantId, {
params: {
"pageNumber": "1",
"pageSize": "1"
@@ -548,7 +547,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/users`)
.reply(200, responses.createUserResponse);
const response: models.CreateUserResponse = await management.MerchantUsers.create(merchantId, requests.createMerchantUserRequest);
const response: management.CreateUserResponse = await managementService.MerchantUsers.create(merchantId, requests.createMerchantUserRequest);
expect(response).toBeTruthy();
});
@@ -557,7 +556,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/users/${userId}`)
.reply(200, responses.user);
const response: models.User = await management.MerchantUsers.retrieve(merchantId, userId);
const response: management.User = await managementService.MerchantUsers.retrieve(merchantId, userId);
expect(response).toBeTruthy();
});
@@ -566,7 +565,7 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/users/${userId}`)
.reply(200, responses.user);
const response: models.User = await management.MerchantUsers.update(merchantId, userId, requests.updateMerchantUserRequest);
const response: management.User = await managementService.MerchantUsers.update(merchantId, userId, requests.updateMerchantUserRequest);
expect(response).toBeTruthy();
});
@@ -577,7 +576,7 @@ describe("Management", (): void => {
scope.get(`/merchants/${merchantId}/webhooks?pageNumber=1&pageSize=1`)
.reply(200, responses.listWebhooksResponse);
const response: models.ListWebhooksResponse = await management.MerchantWebhooks.list(merchantId, {
const response: management.ListWebhooksResponse = await managementService.MerchantWebhooks.list(merchantId, {
params: {
"pageNumber": "1",
"pageSize": "1"
@@ -591,11 +590,11 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/webhooks`)
.reply(200, responses.webhook);
const response: models.Webhook = await management.MerchantWebhooks.create(merchantId, {
const response: management.Webhook = await managementService.MerchantWebhooks.create(merchantId, {
...requests.createMerchantWebhookRequest,
communicationFormat: models.CreateMerchantWebhookRequest.CommunicationFormatEnum.Json,
networkType: models.CreateMerchantWebhookRequest.NetworkTypeEnum.Public,
sslVersion: models.CreateMerchantWebhookRequest.SslVersionEnum.Tls
communicationFormat: management.CreateMerchantWebhookRequest.CommunicationFormatEnum.Json,
networkType: management.CreateMerchantWebhookRequest.NetworkTypeEnum.Public,
sslVersion: management.CreateMerchantWebhookRequest.SslVersionEnum.Tls
});
expect(response).toBeTruthy();
@@ -605,14 +604,14 @@ describe("Management", (): void => {
scope.delete(`/merchants/${merchantId}/webhooks/${webhookId}`)
.reply(204);
await management.MerchantWebhooks.delete(merchantId, webhookId);
await managementService.MerchantWebhooks.delete(merchantId, webhookId);
});
it("should support GET /merchants/{merchantId}/webhooks/{webhookId}", async (): Promise<void> => {
scope.get(`/merchants/${merchantId}/webhooks/${webhookId}`)
.reply(200, responses.webhook);
const response: models.Webhook = await management.MerchantWebhooks.retrieve(merchantId, webhookId);
const response: management.Webhook = await managementService.MerchantWebhooks.retrieve(merchantId, webhookId);
expect(response).toBeTruthy();
});
@@ -621,11 +620,11 @@ describe("Management", (): void => {
scope.patch(`/merchants/${merchantId}/webhooks/${webhookId}`)
.reply(200, responses.webhook);
const response: models.Webhook = await management.MerchantWebhooks.update(merchantId, webhookId, {
const response: management.Webhook = await managementService.MerchantWebhooks.update(merchantId, webhookId, {
...requests.updateMerchantWebhookRequest,
communicationFormat: models.CreateMerchantWebhookRequest.CommunicationFormatEnum.Soap,
networkType: models.CreateMerchantWebhookRequest.NetworkTypeEnum.Local,
sslVersion: models.CreateMerchantWebhookRequest.SslVersionEnum.Sslv3
communicationFormat: management.CreateMerchantWebhookRequest.CommunicationFormatEnum.Soap,
networkType: management.CreateMerchantWebhookRequest.NetworkTypeEnum.Local,
sslVersion: management.CreateMerchantWebhookRequest.SslVersionEnum.Sslv3
});
expect(response).toBeTruthy();
@@ -635,7 +634,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/webhooks/${webhookId}/generateHmac`)
.reply(200, responses.generateHmacKeyResponse);
const response: models.GenerateHmacKeyResponse = await management.MerchantWebhooks.generateHmac(merchantId, webhookId);
const response: management.GenerateHmacKeyResponse = await managementService.MerchantWebhooks.generateHmac(merchantId, webhookId);
expect(response).toBeTruthy();
});
@@ -644,7 +643,7 @@ describe("Management", (): void => {
scope.post(`/merchants/${merchantId}/webhooks/${webhookId}/test`)
.reply(200, responses.testWebhookResponse);
const testWebhookRequest: models.TestWebhookRequest = {
const testWebhookRequest: management.TestWebhookRequest = {
"notification": {
"amount": {
"currency": "string",
@@ -659,7 +658,7 @@ describe("Management", (): void => {
},
"types": ["string"]
};
const response: models.TestWebhookResponse = await management.MerchantWebhooks.test(merchantId, webhookId, testWebhookRequest);
const response: management.TestWebhookResponse = await managementService.MerchantWebhooks.test(merchantId, webhookId, testWebhookRequest);
expect(response).toBeTruthy();
});

View File

@@ -154,7 +154,6 @@ let checkout: Checkout;
let scope: nock.Scope;
const paymentPspReference = "863620292981235A";
const invalidPaymentPspReference = "invalid_psp_reference";
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
beforeEach((): void => {
if (!nock.isActive()) {
@@ -170,8 +169,7 @@ afterEach(() => {
});
describe("Modification", (): void => {
test.each([isCI, true])("should perform an amount update request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should perform an amount update request", async (): Promise<void> => {
const request = createAmountUpdateRequest();
scope.post(`/payments/${paymentPspReference}/amountUpdates`)
.reply(200, createAmountUpdateResponse());
@@ -187,8 +185,7 @@ describe("Modification", (): void => {
}
});
test.each([false, true])("should fail to perform an amount update request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should fail to perform an amount update request", async (): Promise<void> => {
expect.assertions(2);
const request = createAmountUpdateRequest();
scope.post(`/payments/${invalidPaymentPspReference}/amountUpdates`)
@@ -206,8 +203,7 @@ describe("Modification", (): void => {
}
});
test.each([isCI, true])("should perform a cancels request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should perform a cancels request", async (): Promise<void> => {
const request = createCancelsRequest();
scope.post(`/payments/${paymentPspReference}/cancels`)
.reply(200, createCancelsResponse());
@@ -223,8 +219,7 @@ describe("Modification", (): void => {
}
});
test.each([false, true])("should fail to perform a cancels request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should fail to perform a cancels request", async (): Promise<void> => {
expect.assertions(2);
const request = createCancelsRequest();
scope.post(`/payments/${invalidPaymentPspReference}/cancels`)
@@ -241,8 +236,7 @@ describe("Modification", (): void => {
}
});
test.each([isCI, true])("should perform a standalone cancels request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should perform a standalone cancels request", async (): Promise<void> => {
const request = createStandaloneCancelsRequest();
scope.post("/cancels")
.reply(200, createStandaloneCancelsResponse());
@@ -258,8 +252,7 @@ describe("Modification", (): void => {
}
});
test.each([isCI, true])("should perform a captures request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should perform a captures request", async (): Promise<void> => {
const request = createCapturesRequest();
scope.post(`/payments/${paymentPspReference}/captures`)
.reply(200, createCapturesResponse());
@@ -275,8 +268,7 @@ describe("Modification", (): void => {
}
});
test.each([false, true])("should fail to perform a captures request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should fail to perform a captures request", async (): Promise<void> => {
expect.assertions(2);
const request = createCapturesRequest();
scope.post(`/payments/${invalidPaymentPspReference}/captures`)
@@ -293,8 +285,7 @@ describe("Modification", (): void => {
}
});
test.each([isCI, true])("should perform a refunds request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should perform a refunds request", async (): Promise<void> => {
const request = createRefundsRequest();
scope.post(`/payments/${paymentPspReference}/refunds`)
.reply(200, createRefundsResponse());
@@ -310,8 +301,7 @@ describe("Modification", (): void => {
}
});
test.each([false, true])("should fail to perform a refunds request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should fail to perform a refunds request", async (): Promise<void> => {
expect.assertions(2);
const request = createRefundsRequest();
scope.post(`/payments/${invalidPaymentPspReference}/refunds`)
@@ -328,8 +318,7 @@ describe("Modification", (): void => {
}
});
test.each([isCI, true])("should perform a reversals request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should perform a reversals request", async (): Promise<void> => {
const request = createReversalsRequest();
scope.post(`/payments/${paymentPspReference}/reversals`)
.reply(200, createReversalsResponse());
@@ -345,8 +334,7 @@ describe("Modification", (): void => {
}
});
test.each([false, true])("should fail to perform a reversals request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should fail to perform a reversals request", async (): Promise<void> => {
expect.assertions(2);
const request = createReversalsRequest();
scope.post(`/payments/${invalidPaymentPspReference}/reversals`)

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2022 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import authorisationTrue from "../__mocks__/notification/authorisationTrue.json";
import captureTrue from "../__mocks__/notification/captureTrue.json";
import captureFalse from "../__mocks__/notification/captureFalse.json";

View File

@@ -2,17 +2,9 @@ import nock from "nock";
import { createClient } from "../__mocks__/base";
import Payout from "../services/payout";
import Client from "../client";
import {
ModifyRequest,
PayoutRequest,
Recurring,
StoreDetailAndSubmitRequest,
StoreDetailRequest,
SubmitRequest
} from "../typings/payouts/models";
import { payouts } from "../typings";
import { ApiConstants } from "../constants/apiConstants";
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
const storeDetailAndSubmitThirdParty = JSON.stringify({
additionalData: {
fraudResultType: "GREEN",
@@ -44,7 +36,7 @@ const defaultData = {
shopperReference: "shopperReference",
};
const mockStoreDetailRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): StoreDetailRequest => ({
const mockStoreDetailRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): payouts.StoreDetailRequest => ({
...defaultData,
card: {
cvc: "737",
@@ -53,29 +45,29 @@ const mockStoreDetailRequest = (merchantAccount: string = process.env.ADYEN_MERC
number: "4111111111111111",
holderName: "John Smith"
},
entityType: StoreDetailRequest.EntityTypeEnum.Company,
entityType: payouts.StoreDetailRequest.EntityTypeEnum.Company,
recurring: {
contract: Recurring.ContractEnum.Payout,
contract: payouts.Recurring.ContractEnum.Payout,
},
merchantAccount,
});
const mockSubmitRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): SubmitRequest => ({
const mockSubmitRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): payouts.SubmitRequest => ({
selectedRecurringDetailReference: "LATEST",
recurring: {
contract: Recurring.ContractEnum.Payout
contract: payouts.Recurring.ContractEnum.Payout
},
...defaultData,
...amountAndReference,
merchantAccount,
});
const mockStoreDetailAndSubmitRequest = (merchantAccount?: string): StoreDetailAndSubmitRequest => ({
const mockStoreDetailAndSubmitRequest = (merchantAccount?: string): payouts.StoreDetailAndSubmitRequest => ({
...amountAndReference,
...(mockStoreDetailRequest(merchantAccount)),
});
const mockPayoutRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): PayoutRequest => ({
const mockPayoutRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): payouts.PayoutRequest => ({
...amountAndReference,
...defaultData,
card: {
@@ -90,7 +82,7 @@ const mockPayoutRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!
let client: Client;
let clientStore: Client;
let clientReview: Client;
let payout: Payout;
let payoutService: Payout;
let scope: nock.Scope;
beforeEach((): void => {
@@ -101,7 +93,7 @@ beforeEach((): void => {
clientStore = createClient(process.env.ADYEN_STOREPAYOUT_APIKEY);
clientReview = createClient(process.env.ADYEN_REVIEWPAYOUT_APIKEY);
scope = nock(`${client.config.endpoint}/pal/servlet/Payout/${Client.API_VERSION}`);
payout = new Payout(client);
payoutService = new Payout(client);
});
afterEach((): void => {
@@ -109,60 +101,56 @@ afterEach((): void => {
});
describe("PayoutTest", function (): void {
test.each([isCI, true])("should succeed on store detail and submit third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
const request: StoreDetailAndSubmitRequest = mockStoreDetailAndSubmitRequest();
test("should succeed on store detail and submit third party", async function (): Promise<void> {
payoutService = new Payout(clientStore);
const request: payouts.StoreDetailAndSubmitRequest = mockStoreDetailAndSubmitRequest();
scope.post("/storeDetailAndSubmitThirdParty").reply(200, storeDetailAndSubmitThirdParty);
const result = await payout.storeDetailAndSubmitThirdParty(request);
const result = await payoutService.storeDetailAndSubmitThirdParty(request);
expect(result.resultCode).toEqual("[payout-submit-received]");
expect(result.pspReference).toBeTruthy();
});
test.each([false, true])("should succeed on store detail, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
test("should succeed on store detail", async function (): Promise<void> {
payoutService = new Payout(clientStore);
scope.post("/storeDetail").reply(200, storeDetail);
const request: StoreDetailRequest = mockStoreDetailRequest();
const result = await payout.storeDetail(request);
const request: payouts.StoreDetailRequest = mockStoreDetailRequest();
const result = await payoutService.storeDetail(request);
expect("Success").toEqual(result.resultCode);
expect(result.pspReference).toBeTruthy();
expect(result.recurringDetailReference).toBeTruthy();
});
test.each([isCI, true])("should succeed on confirm third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
test("should succeed on confirm third party", async function (): Promise<void> {
payoutService = new Payout(clientStore);
scope.post("/storeDetail").reply(200, storeDetail);
const storeRequest: StoreDetailRequest = mockStoreDetailRequest();
const storeResult = await payout.storeDetail(storeRequest);
const storeRequest: payouts.StoreDetailRequest = mockStoreDetailRequest();
const storeResult = await payoutService.storeDetail(storeRequest);
payout = new Payout(clientReview);
payoutService = new Payout(clientReview);
scope.post("/confirmThirdParty")
.reply(200, {
pspReference: "8815131762537886",
response: "[payout-confirm-received]"
});
const request: ModifyRequest = {
const request: payouts.ModifyRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: storeResult.pspReference
};
const result = await payout.confirmThirdParty(request);
const result = await payoutService.confirmThirdParty(request);
expect(result.response).toEqual("[payout-confirm-received]");
expect(result.pspReference).toBeTruthy();
});
test.each([isCI, true])("should succeed on submit third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
test("should succeed on submit third party", async function (): Promise<void> {
payoutService = new Payout(clientStore);
scope.post("/submitThirdParty").reply(200, storeDetailAndSubmitThirdParty);
const request: SubmitRequest = mockSubmitRequest();
const result = await payout.submitThirdparty(request);
const request: payouts.SubmitRequest = mockSubmitRequest();
const result = await payoutService.submitThirdparty(request);
expect(result.resultCode).toEqual("[payout-submit-received]");
expect(result.pspReference).toBeTruthy();
@@ -173,15 +161,14 @@ describe("PayoutTest", function (): void {
}
});
test.each([false, true])("should succeed on decline third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
test("should succeed on decline third party", async function (): Promise<void> {
payoutService = new Payout(clientStore);
scope.post("/storeDetail").reply(200, storeDetail);
const storeRequest: StoreDetailRequest = mockStoreDetailRequest();
const storeResult = await payout.storeDetail(storeRequest);
const storeRequest: payouts.StoreDetailRequest = mockStoreDetailRequest();
const storeResult = await payoutService.storeDetail(storeRequest);
payout = new Payout(clientReview);
const request: ModifyRequest = {
payoutService = new Payout(clientReview);
const request: payouts.ModifyRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: storeResult.pspReference
};
@@ -190,21 +177,20 @@ describe("PayoutTest", function (): void {
pspReference: "8815131762537886",
response: "[payout-decline-received]"
});
const result = await payout.declineThirdParty(request);
const result = await payoutService.declineThirdParty(request);
expect(result.response).toEqual("[payout-decline-received]");
expect(result.pspReference).toBeTruthy();
});
test.each([isCI, true])("should succeed on payout, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
test("should succeed on payout", async function (): Promise<void> {
scope.post("/payout").reply(200, {
pspReference: "8815131762537886",
resultCode: "Received",
});
const request = mockPayoutRequest();
const result = await payout.payout(request);
const result = await payoutService.payout(request);
expect(result.resultCode).toEqual("Received");
expect(result.pspReference).toBeTruthy();

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createMock } from "ts-auto-mock";
import { createBasicAuthClient } from "../__mocks__/base";

View File

@@ -5,30 +5,18 @@ import { listRecurringDetailsSuccess } from "../__mocks__/recurring/listRecurrin
import { notifyShopperSuccess } from "../__mocks__/recurring/notifyShopperSuccess";
import RecurringService from "../services/recurring";
import Client from "../client";
import { paymentsSuccess } from "../__mocks__/checkout/paymentsSuccess";
import { createPaymentsCheckoutRequest } from "./checkout.spec";
import Checkout from "../services/checkout";
import { PaymentRequest } from "../typings/checkout/models";
import {
ScheduleAccountUpdaterRequest,
ScheduleAccountUpdaterResult,
DisableRequest,
RecurringDetailsRequest,
Recurring,
NotifyShopperRequest
} from "../typings/recurring/models";
import { recurring } from "../typings";
const createRecurringDetailsRequest = (): RecurringDetailsRequest => {
const createRecurringDetailsRequest = (): recurring.RecurringDetailsRequest => {
return {
merchantAccount: process.env.ADYEN_MERCHANT!,
recurring: { contract: Recurring.ContractEnum.Recurring },
recurring: { contract: recurring.Recurring.ContractEnum.Recurring },
shopperReference: "shopperReference",
};
};
let client: Client;
let recurring: RecurringService;
let checkout: Checkout;
let recurringService: RecurringService;
let scope: nock.Scope;
beforeEach((): void => {
@@ -36,8 +24,7 @@ beforeEach((): void => {
nock.activate();
}
client = createClient();
recurring = new RecurringService(client);
checkout = new Checkout(client);
recurringService = new RecurringService(client);
scope = nock(`${client.config.endpoint}/pal/servlet/Recurring/${Client.RECURRING_API_VERSION}`);
});
@@ -51,30 +38,24 @@ describe("Recurring", (): void => {
.reply(200, listRecurringDetailsSuccess);
const request = createRecurringDetailsRequest();
const result = await recurring.listRecurringDetails(request);
const result = await recurringService.listRecurringDetails(request);
expect(result).toBeTruthy();
expect(result.details?.[0].recurringDetailReference).toBe("recurringReference");
});
test("should disable", async (): Promise<void> => {
scope.post("/payments")
.reply(200, paymentsSuccess);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const res = await checkout.payments(paymentsRequest);
scope.post("/disable")
.reply(200, disableSuccess);
const request: DisableRequest = {
const request: recurring.DisableRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
shopperReference: "shopperReference",
recurringDetailReference: res.additionalData!["recurring.recurringDetailReference"]
recurringDetailReference: "recurring.recurringDetailReference",
};
try {
const result = await recurring.disable(request);
const result = await recurringService.disable(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e);
@@ -85,7 +66,7 @@ describe("Recurring", (): void => {
scope.post("/notifyShopper")
.reply(200, notifyShopperSuccess);
const notifyShopperRequest: NotifyShopperRequest = {
const notifyShopperRequest: recurring.NotifyShopperRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
shopperReference: "shopperReference",
storedPaymentMethodId: "8415995487234100",
@@ -99,7 +80,7 @@ describe("Recurring", (): void => {
};
try {
const result = await recurring.notifyShopper(notifyShopperRequest);
const result = await recurringService.notifyShopper(notifyShopperRequest);
expect(result).toBeTruthy();
} catch (e) {
fail(e);
@@ -108,7 +89,7 @@ describe("Recurring", (): void => {
test("should schedule account updater", async (): Promise<void> => {
const scheduleAccountUpdaterSuccess: ScheduleAccountUpdaterResult = {
const scheduleAccountUpdaterSuccess: recurring.ScheduleAccountUpdaterResult = {
pspReference: "mocked_psp",
result: "SUCCESS"
};
@@ -116,7 +97,7 @@ describe("Recurring", (): void => {
scope.post("/scheduleAccountUpdater")
.reply(200, scheduleAccountUpdaterSuccess);
const request: ScheduleAccountUpdaterRequest = {
const request: recurring.ScheduleAccountUpdaterRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
reference: "ref",
card: {
@@ -128,7 +109,7 @@ describe("Recurring", (): void => {
};
try {
const result = await recurring.scheduleAccountUpdater(request);
const result = await recurringService.scheduleAccountUpdater(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e);

View File

@@ -2,23 +2,11 @@ import nock from "nock";
import Client from "../client";
import {createClient} from "../__mocks__/base";
import {StoredValue} from "../services";
import { StoredValueIssueRequest,
StoredValueIssueResponse,
StoredValueStatusChangeRequest,
StoredValueStatusChangeResponse,
StoredValueLoadRequest,
StoredValueLoadResponse,
StoredValueBalanceCheckRequest,
StoredValueBalanceCheckResponse,
StoredValueBalanceMergeRequest,
StoredValueBalanceMergeResponse,
StoredValueVoidRequest,
StoredValueVoidResponse
} from "../typings/storedValue/models";
import { storedValue } from "../typings";
let client: Client;
let storedValue: StoredValue;
let storedValueService: StoredValue;
let scope: nock.Scope;
beforeEach((): void => {
@@ -27,7 +15,7 @@ beforeEach((): void => {
}
client = createClient();
scope = nock(`${client.config.storedValueEndpoint}/${Client.STOREDVALUE_API_VERSION}`);
storedValue = new StoredValue(client);
storedValueService = new StoredValue(client);
});
afterEach(() => {
@@ -50,7 +38,7 @@ describe("StoredValue", (): void => {
"type": "givex"
}
});
const issueRequest: StoredValueIssueRequest = {
const issueRequest: storedValue.StoredValueIssueRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"store": "YOUR_STORE_ID",
"paymentMethod": {
@@ -63,7 +51,7 @@ describe("StoredValue", (): void => {
"reference": "YOUR_REFERENCE"
};
const issueResponse: StoredValueIssueResponse = await storedValue.issue(issueRequest);
const issueResponse: storedValue.StoredValueIssueResponse = await storedValueService.issue(issueRequest);
expect(issueResponse.pspReference).toEqual("851564651069192J");
});
@@ -83,7 +71,7 @@ describe("StoredValue", (): void => {
"type": "givex"
}
});
const issueRequest: StoredValueIssueRequest = {
const issueRequest: storedValue.StoredValueIssueRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"store": "YOUR_STORE_ID",
"paymentMethod": {
@@ -93,7 +81,7 @@ describe("StoredValue", (): void => {
"reference": "YOUR_REFERENCE"
};
const issueResponse: StoredValueIssueResponse = await storedValue.issue(issueRequest);
const issueResponse: storedValue.StoredValueIssueResponse = await storedValueService.issue(issueRequest);
expect(issueResponse.pspReference).toEqual("851564651069192J");
});
@@ -109,8 +97,8 @@ describe("StoredValue", (): void => {
"resultCode": "Success"
});
const statusRequest: StoredValueStatusChangeRequest = {
"status": StoredValueStatusChangeRequest.StatusEnum.Active,
const statusRequest: storedValue.StoredValueStatusChangeRequest = {
"status": storedValue.StoredValueStatusChangeRequest.StatusEnum.Active,
"amount": {
"currency": "USD",
"value": 1000
@@ -125,7 +113,7 @@ describe("StoredValue", (): void => {
"reference": "YOUR_REFERENCE"
};
const changeStatusResponse: StoredValueStatusChangeResponse = await storedValue.changeStatus(statusRequest);
const changeStatusResponse: storedValue.StoredValueStatusChangeResponse = await storedValueService.changeStatus(statusRequest);
expect(changeStatusResponse.pspReference).toEqual("851564652149588K");
});
@@ -140,8 +128,8 @@ describe("StoredValue", (): void => {
"resultCode": "Success"
});
const statusRequest: StoredValueStatusChangeRequest = {
"status": StoredValueStatusChangeRequest.StatusEnum.Inactive,
const statusRequest: storedValue.StoredValueStatusChangeRequest = {
"status": storedValue.StoredValueStatusChangeRequest.StatusEnum.Inactive,
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"store":"YOUR_STORE_ID",
"paymentMethod": {
@@ -149,11 +137,11 @@ describe("StoredValue", (): void => {
},
"recurringDetailReference": "7219627091701347",
"shopperReference": "YOUR_UNIQUE_SHOPPER_ID_P3fW3k9D2tvXFu6l",
"shopperInteraction": StoredValueStatusChangeRequest.ShopperInteractionEnum.Ecommerce,
"shopperInteraction": storedValue.StoredValueStatusChangeRequest.ShopperInteractionEnum.Ecommerce,
"reference": "YOUR_REFERENCE"
};
const changeStatusResponse: StoredValueStatusChangeResponse = await storedValue.changeStatus(statusRequest);
const changeStatusResponse: storedValue.StoredValueStatusChangeResponse = await storedValueService.changeStatus(statusRequest);
expect(changeStatusResponse.pspReference).toEqual("851564652149588K");
});
@@ -168,12 +156,12 @@ describe("StoredValue", (): void => {
"resultCode": "Success"
});
const loadRequest: StoredValueLoadRequest = {
const loadRequest: storedValue.StoredValueLoadRequest = {
"amount": {
"currency": "USD",
"value": 2000
},
"loadType": StoredValueLoadRequest.LoadTypeEnum.MerchandiseReturn,
"loadType": storedValue.StoredValueLoadRequest.LoadTypeEnum.MerchandiseReturn,
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"store":"YOUR_STORE_ID",
"paymentMethod": {
@@ -184,7 +172,7 @@ describe("StoredValue", (): void => {
"reference": "YOUR_REFERENCE"
};
const loadResponse: StoredValueLoadResponse = await storedValue.load(loadRequest);
const loadResponse: storedValue.StoredValueLoadResponse = await storedValueService.load(loadRequest);
expect(loadResponse.pspReference).toEqual("851564654294247B");
});
@@ -199,7 +187,7 @@ describe("StoredValue", (): void => {
"resultCode": "Success"
});
const checkBalanceRequest: StoredValueBalanceCheckRequest = {
const checkBalanceRequest: storedValue.StoredValueBalanceCheckRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"store":"YOUR_STORE_ID",
"paymentMethod": {
@@ -210,7 +198,7 @@ describe("StoredValue", (): void => {
"reference": "YOUR_REFERENCE"
};
const checkBalanceResponse: StoredValueBalanceCheckResponse = await storedValue.checkBalance(checkBalanceRequest);
const checkBalanceResponse: storedValue.StoredValueBalanceCheckResponse = await storedValueService.checkBalance(checkBalanceRequest);
expect(checkBalanceResponse.pspReference).toEqual("881564657480267D");
});
@@ -225,7 +213,7 @@ describe("StoredValue", (): void => {
"resultCode": "Success"
});
const mergeBalanceRequest: StoredValueBalanceMergeRequest = {
const mergeBalanceRequest: storedValue.StoredValueBalanceMergeRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"store":"YOUR_STORE_ID",
"sourcePaymentMethod": {
@@ -240,7 +228,7 @@ describe("StoredValue", (): void => {
"reference": "YOUR_REFERENCE"
};
const mergeBalanceResponse: StoredValueBalanceMergeResponse = await storedValue.mergebalance(mergeBalanceRequest);
const mergeBalanceResponse: storedValue.StoredValueBalanceMergeResponse = await storedValueService.mergebalance(mergeBalanceRequest);
expect(mergeBalanceResponse.pspReference).toEqual("881564657480267D");
});
@@ -255,13 +243,13 @@ describe("StoredValue", (): void => {
"resultCode": "Success"
});
const voidTransactionRequest: StoredValueVoidRequest = {
const voidTransactionRequest: storedValue.StoredValueVoidRequest = {
"merchantAccount": "YOUR_MERCHANT_ACCOUNT",
"originalReference": "851564654294247B",
"reference": "YOUR_REFERENCE"
};
const voidTransactionResponse: StoredValueVoidResponse = await storedValue.voidTransaction(voidTransactionRequest);
const voidTransactionResponse: storedValue.StoredValueVoidResponse = await storedValueService.voidTransaction(voidTransactionRequest);
expect(voidTransactionResponse.pspReference).toEqual("851564673300692A");
});
});

View File

@@ -1,29 +1,10 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2022 Adyen N.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient, createTerminalAPIPaymentRequest, createTerminalAPIRefundRequest } from "../__mocks__/base";
import { asyncRes } from "../__mocks__/terminalApi/async";
import { syncRefund, syncRes, syncResEventNotification } from "../__mocks__/terminalApi/sync";
import Client from "../client";
import TerminalCloudAPI from "../services/terminalCloudAPI";
import { SaleToAcquirerData, TerminalApiResponse } from "../typings/terminal/models";
import { terminal} from "../typings";
let client: Client;
let terminalCloudAPI: TerminalCloudAPI;
@@ -44,10 +25,8 @@ afterEach((): void => {
nock.cleanAll();
});
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
describe("Terminal Cloud API", (): void => {
test.each([isCI])("should make an async payment request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should make an async payment request", async (): Promise<void> => {
scope.post("/async").reply(200, asyncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
@@ -57,19 +36,17 @@ describe("Terminal Cloud API", (): void => {
expect(requestResponse).toEqual("ok");
});
test.each([isCI])("should make a sync payment request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should make a sync payment request", async (): Promise<void> => {
scope.post("/sync").reply(200, syncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const terminalAPIResponse: TerminalApiResponse = await terminalCloudAPI.sync(terminalAPIPaymentRequest);
const terminalAPIResponse: terminal.TerminalApiResponse = await terminalCloudAPI.sync(terminalAPIPaymentRequest);
expect(terminalAPIResponse.SaleToPOIResponse?.PaymentResponse).toBeDefined();
expect(terminalAPIResponse.SaleToPOIResponse?.MessageHeader).toBeDefined();
});
test.each([isCI])("should return event notification if response contains it, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should return event notification if response contains it", async (): Promise<void> => {
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
scope.post("/sync").reply(200, syncResEventNotification);
@@ -79,12 +56,11 @@ describe("Terminal Cloud API", (): void => {
expect(terminalAPIResponse.SaleToPOIRequest?.EventNotification).toBeDefined();
});
test.each([isCI])("should make an async refund request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should make an async refund request", async (): Promise<void> => {
scope.post("/sync").reply(200, syncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const terminalAPIResponse: TerminalApiResponse = await terminalCloudAPI.sync(terminalAPIPaymentRequest);
const terminalAPIResponse: terminal.TerminalApiResponse = await terminalCloudAPI.sync(terminalAPIPaymentRequest);
const pOITransactionId = terminalAPIResponse.SaleToPOIResponse!.PaymentResponse!.POIData!.POITransactionID;
expect(pOITransactionId).toBeTruthy();
@@ -94,7 +70,7 @@ describe("Terminal Cloud API", (): void => {
const terminalAPIRefundRequest = createTerminalAPIRefundRequest(pOITransactionId);
const id = Math.floor(Math.random() * Math.floor(10000000)).toString();
terminalAPIRefundRequest.SaleToPOIRequest.MessageHeader.ServiceID = id;
const saleToAcquirerData: SaleToAcquirerData = new SaleToAcquirerData();
const saleToAcquirerData: terminal.SaleToAcquirerData = new terminal.SaleToAcquirerData();
saleToAcquirerData.currency = "EUR";
terminalAPIRefundRequest.SaleToPOIRequest.ReversalRequest!.SaleData!.SaleToAcquirerData = saleToAcquirerData;
const terminalAPIRefundResponse = await terminalCloudAPI.sync(terminalAPIRefundRequest);

View File

@@ -1,28 +1,9 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2021 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient, createTerminalAPIPaymentRequest } from "../__mocks__/base";
import { localEncRes, wrongEncRes } from "../__mocks__/terminalApi/local";
import Client from "../client";
import TerminalLocalAPI from "../services/terminalLocalAPI";
import { SecurityKey, TerminalApiResponse } from "../typings/terminal/models";
import { terminal } from "../typings";
import NexoCryptoException from "../services/exception/nexoCryptoException";
let client: Client;
@@ -43,34 +24,30 @@ afterEach((): void => {
nock.cleanAll();
});
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
describe("Terminal Local API", (): void => {
test.each([isCI, true])("should make a local payment, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
test("should make a local payment", async (): Promise<void> => {
scope.post("/").reply(200, localEncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const securityKey: SecurityKey = {
const securityKey: terminal.SecurityKey = {
AdyenCryptoVersion: 0,
KeyIdentifier: "CryptoKeyIdentifier12345",
KeyVersion: 0,
Passphrase: "p@ssw0rd123456",
};
const terminalApiResponse: TerminalApiResponse =
const terminalApiResponse: terminal.TerminalApiResponse =
await terminalLocalAPI.request(terminalAPIPaymentRequest, securityKey);
expect(terminalApiResponse.SaleToPOIResponse?.PaymentResponse).toBeDefined();
expect(terminalApiResponse.SaleToPOIResponse?.MessageHeader).toBeDefined();
});
test.each([isCI, true])("should return NexoCryptoException, isMock: %p", async (isMock: boolean): Promise<void> => {
!isMock && nock.restore();
test("should return NexoCryptoException", async (): Promise<void> => {
scope.post("/").reply(200, wrongEncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const securityKey: SecurityKey = {
const securityKey: terminal.SecurityKey = {
AdyenCryptoVersion: 0,
KeyIdentifier: "CryptoKeyIdentifier12345",
KeyVersion: 0,

View File

@@ -2,21 +2,10 @@ import nock from "nock";
import Client from "../client";
import { createClient } from "../__mocks__/base";
import TerminalManagement from "../services/terminalManagement";
import {
AssignTerminalsRequest,
AssignTerminalsResponse,
FindTerminalRequest,
FindTerminalResponse,
GetStoresUnderAccountRequest,
GetStoresUnderAccountResponse,
GetTerminalDetailsRequest,
GetTerminalDetailsResponse,
GetTerminalsUnderAccountRequest,
GetTerminalsUnderAccountResponse
} from "../typings/terminalManagement/models";
import { terminalManagement } from "../typings";
let client: Client;
let terminalManagement: TerminalManagement;
let terminalManagementService: TerminalManagement;
let scope: nock.Scope;
beforeEach((): void => {
@@ -25,7 +14,7 @@ beforeEach((): void => {
}
client = createClient();
scope = nock(`${client.config.terminalManagementEndpoint}/${Client.TERMINAL_MANAGEMENT_API_VERSION}`);
terminalManagement = new TerminalManagement(client);
terminalManagementService = new TerminalManagement(client);
});
afterEach(() => {
@@ -40,14 +29,14 @@ describe("POS Terminal Management API", (): void => {
"P400Plus-275479597": "RemoveConfigScheduled"
}
});
const request: AssignTerminalsRequest = {
const request: terminalManagement.AssignTerminalsRequest = {
"companyAccount": "YOUR_COMPANY_ACCOUNT",
"terminals": [
"P400Plus-275479597"
]
};
const response: AssignTerminalsResponse = await terminalManagement.assignTerminals(request);
const response: terminalManagement.AssignTerminalsResponse = await terminalManagementService.assignTerminals(request);
expect(response.results["P400Plus-275479597"]).toEqual("RemoveConfigScheduled");
});
@@ -60,11 +49,11 @@ describe("POS Terminal Management API", (): void => {
"merchantInventory": false,
"terminal": "P400Plus-275479597"
});
const request: FindTerminalRequest = {
const request: terminalManagement.FindTerminalRequest = {
"terminal": "P400Plus-275479597"
};
const response: FindTerminalResponse = await terminalManagement.findTerminal(request);
const response: terminalManagement.FindTerminalResponse = await terminalManagementService.findTerminal(request);
expect(response.terminal).toEqual("P400Plus-275479597");
});
@@ -87,11 +76,11 @@ describe("POS Terminal Management API", (): void => {
}
]
});
const request: GetStoresUnderAccountRequest = {
const request: terminalManagement.GetStoresUnderAccountRequest = {
"companyAccount": "YOUR_COMPANY_ACCOUNT"
};
const response: GetStoresUnderAccountResponse = await terminalManagement.getStoresUnderAccount(request);
const response: terminalManagement.GetStoresUnderAccountResponse = await terminalManagementService.getStoresUnderAccount(request);
expect(response.stores).toHaveLength(1);
expect(response.stores![0].status).toEqual("Active");
@@ -113,11 +102,11 @@ describe("POS Terminal Management API", (): void => {
"country": "NETHERLANDS",
"dhcpEnabled": false
});
const request: GetTerminalDetailsRequest = {
const request: terminalManagement.GetTerminalDetailsRequest = {
"terminal": "P400Plus-275479597"
};
const response: GetTerminalDetailsResponse = await terminalManagement.getTerminalDetails(request);
const response: terminalManagement.GetTerminalDetailsResponse = await terminalManagementService.getTerminalDetails(request);
expect(response.deviceModel).toBe("P400Plus");
});
@@ -144,11 +133,11 @@ describe("POS Terminal Management API", (): void => {
}
]
});
const request: GetTerminalsUnderAccountRequest = {
const request: terminalManagement.GetTerminalsUnderAccountRequest = {
"companyAccount": "YOUR_COMPANY_ACCOUNT"
};
const response: GetTerminalsUnderAccountResponse = await terminalManagement.getTerminalsUnderAccount(request);
const response: terminalManagement.GetTerminalsUnderAccountResponse = await terminalManagementService.getTerminalsUnderAccount(request);
expect(response.merchantAccounts).toHaveLength(1);
expect(response.merchantAccounts![0].stores).toHaveLength(1);

View File

@@ -3,7 +3,7 @@ import { createClient } from "../__mocks__/base";
import { transfersSuccess, getTransactionSuccess, listTransactionsSuccess } from "../__mocks__/transfers/responses";
import Client from "../client";
import { Transfers } from "../services";
import { TransferInfo, Transfer, Transaction, TransactionSearchResponse, IbanAccountIdentification} from "../typings/transfer/models";
import { transfer} from "../typings";
let client: Client;
let transferService: Transfers;
@@ -26,9 +26,9 @@ describe("Transfers", (): void => {
test("should transfer fund", async (): Promise<void> => {
scope.post("/transfers")
.reply(200, transfersSuccess);
const request = new TransferInfo();
const request = new transfer.TransferInfo();
request.amount = { currency: "EUR", value: 1000};
request.category = TransferInfo.CategoryEnum.Bank;
request.category = transfer.TransferInfo.CategoryEnum.Bank;
request.counterparty = {
balanceAccountId: "123",
transferInstrumentId: "transfer_id",
@@ -38,26 +38,26 @@ describe("Transfers", (): void => {
},
accountIdentification: {
iban: "NLRABO12321",
type: IbanAccountIdentification.TypeEnum.Iban
type: transfer.IbanAccountIdentification.TypeEnum.Iban
}
},
};
const response: Transfer = await transferService.transfers(request);
const response: transfer.Transfer = await transferService.transfers(request);
expect(response.id).toEqual("1W1UG35U8A9J5ZLG");
});
test("should get transaction", async (): Promise<void> => {
scope.get("/transactions/123")
.reply(200, getTransactionSuccess);
const response: Transaction = await transferService.getTransaction("123");
const response: transfer.Transaction = await transferService.getTransaction("123");
expect(response.id).toEqual("IZK7C25U7DYVX03Y");
});
test("should list transactions", async (): Promise<void> => {
scope.get("/transactions")
.reply(200, listTransactionsSuccess);
const response: TransactionSearchResponse = await transferService.listTransactions();
const response: transfer.TransactionSearchResponse = await transferService.listTransactions();
expect(response.data?.length).toEqual(3);
if(response.data && response.data?.length > 0) {
expect(response?.data[0]?.id).toEqual("1VVF0D5U66PIUIVP");

View File

@@ -6,6 +6,10 @@ import ClientInterface from "./httpClient/clientInterface";
type ClientParametersOverload =
| { config: Config }
| { config: Config; httpClient: ClientInterface }
| { username: string; password: string; environment: Environment}
| { username: string; password: string; environment: Environment; httpClient: ClientInterface }
| { username: string; password: string; environment: Environment; liveEndpointUrlPrefix: string }
| { username: string; password: string; environment: Environment; liveEndpointUrlPrefix: string; httpClient: ClientInterface }
| { username: string; password: string; environment: Environment; applicationName: string }
| { username: string; password: string; environment: Environment; applicationName: string; httpClient: ClientInterface }
| { username: string; password: string; environment: Environment; applicationName: string; liveEndpointUrlPrefix: string }
@@ -90,10 +94,12 @@ class Client {
const environment = options.environment || this.config.environment;
if (environment) {
this.setEnvironment(environment, options.liveEndpointUrlPrefix);
if (options.username && options.password && options.applicationName) {
if (options.username && options.password) {
this.config.username = options.username;
this.config.password = options.password;
this.config.applicationName = options.applicationName;
if(options.applicationName) {
this.config.applicationName = options.applicationName;
}
}
if (options.apiKey) {
@@ -169,4 +175,4 @@ class Client {
}
}
export default Client;
export default Client;

View File

@@ -9,9 +9,11 @@
/// <reference path="platformsFund.ts" />
/// <reference path="platformsNotificationConfiguration.ts" />
export * as balancePlatform from './balancePlatform/models';
export * as binlookup from './binlookup/models';
export * as checkout from './checkout/models';
export * as notification from './notification/models';
export * as payments from './payments/models';
export * as payouts from './payouts/models';
export * as platformsNotifications from './platformsNotifications/models';
export * as platformsAccount from './platformsAccount/models';

View File

@@ -25,7 +25,8 @@ import * as https from "https";
import { URLSearchParams } from "url";
export namespace IRequest {
type QueryString = URLSearchParams | string | NodeJS.Dict<string | string[]> | Iterable<[string, string]> | Array<[string, string]>;
type QueryString = ConstructorParameters<typeof URLSearchParams>[0];
export type Options = https.RequestOptions & {
idempotencyKey?: string;
params?: QueryString;

View File

@@ -843,10 +843,10 @@
resolved "https://registry.yarnpkg.com/@types/node/-/node-18.0.3.tgz#463fc47f13ec0688a33aec75d078a0541a447199"
integrity sha512-HzNRZtp4eepNitP+BD6k2L6DROIDG4Q0fm4x+dwfsr6LGmROENnok75VGw40628xf+iR24WeMFcHuuBDUAzzsQ==
"@types/node@14.0.9":
version "14.0.9"
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.9.tgz#43896ab87fc82bda1dfd600cdf44a0c8a64e11d2"
integrity sha512-0sCTiXKXELOBxvZLN4krQ0FPOAA7ij+6WwvD0k/PHd9/KAkr4dXel5J9fh6F4x1FwAQILqAWkmpeuS6mjf1iKA==
"@types/node@14.18.36":
version "14.18.36"
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.18.36.tgz#c414052cb9d43fab67d679d5f3c641be911f5835"
integrity sha512-FXKWbsJ6a1hIrRxv+FoukuHnGTgEzKYGi7kilfMae96AL9UNkPFNWJEEYWzdRI9ooIkbr4AKldyuSTLql06vLQ==
"@types/parse-json@^4.0.0":
version "4.0.0"
@@ -3863,7 +3863,7 @@ new-github-release-url@2.0.0:
dependencies:
type-fest "^2.5.1"
nock@*, nock@13.2.9:
nock@*:
version "13.2.9"
resolved "https://registry.yarnpkg.com/nock/-/nock-13.2.9.tgz#4faf6c28175d36044da4cfa68e33e5a15086ad4c"
integrity sha512-1+XfJNYF1cjGB+TKMWi29eZ0b82QOvQs2YoLNzbpWGqFMtRQHTa57osqdGj4FrFPgkO4D4AZinzUJR9VvW3QUA==
@@ -3873,6 +3873,16 @@ nock@*, nock@13.2.9:
lodash "^4.17.21"
propagate "^2.0.0"
nock@13.3.0:
version "13.3.0"
resolved "https://registry.yarnpkg.com/nock/-/nock-13.3.0.tgz#b13069c1a03f1ad63120f994b04bfd2556925768"
integrity sha512-HHqYQ6mBeiMc+N038w8LkMpDCRquCHWeNmN3v6645P3NhN2+qXOBqvPqo7Rt1VyCMzKhJ733wZqw5B7cQVFNPg==
dependencies:
debug "^4.1.0"
json-stringify-safe "^5.0.1"
lodash "^4.17.21"
propagate "^2.0.0"
node-domexception@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/node-domexception/-/node-domexception-1.0.0.tgz#6888db46a1f71c0b76b3f7555016b63fe64766e5"
@@ -5093,10 +5103,10 @@ typedarray-to-buffer@^3.1.5:
dependencies:
is-typedarray "^1.0.0"
typescript@4.9.3:
version "4.9.3"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.3.tgz#3aea307c1746b8c384435d8ac36b8a2e580d85db"
integrity sha512-CIfGzTelbKNEnLpLdGFgdyKhG23CKdKgQPOBc+OUNrkJ2vr+KSzsSV5kq5iWhEQbok+quxgGzrAtGWCyU7tHnA==
typescript@4.9.4:
version "4.9.4"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.4.tgz#a2a3d2756c079abda241d75f149df9d561091e78"
integrity sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==
unbox-primitive@^1.0.2:
version "1.0.2"