### Install Adyen Node.js Library Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Use npm to install the Adyen Node.js API library. Ensure Node.js version 18 or later is installed. ```bash npm install --save @adyen/api-library ``` -------------------------------- ### Capital API Examples Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Demonstrates how to use the CapitalAPI to manage business financing, including viewing grant offers, requesting grants, and tracking disbursements. ```APIDOC ## CapitalAPI `CapitalAPI` wraps Adyen Capital (v1) to embed business financing for marketplace users: view grant offers, request grants, and track disbursements. ```typescript import { Client, CapitalAPI, EnvironmentEnum } from "@adyen/api-library"; import { capital } from "@adyen/api-library/lib/src/typings"; const client = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST }); const capitalApi = new CapitalAPI(client); // List active grant offers for an account holder const offers: capital.GrantOffers = await capitalApi.GrantOffersApi.getGrantOffers( { params: { accountHolderId: "AH00000000000001" } } as any ); console.log(offers.grantOffers?.map(o => ({ id: o.id, amount: o.amount }))); // Request a grant const grant: capital.Grant = await capitalApi.GrantsApi.requestGrant({ grantOfferId: offers.grantOffers![0].id! }); console.log(grant.id, grant.status); // Get grant account balance const grantAccount: capital.GrantAccount = await capitalApi.GrantAccountsApi.getGrantAccount(); console.log(grantAccount.balances); // Get all disbursements for a grant const disbursements: capital.Disbursements = await capitalApi.GrantsApi.getDisbursementsForGrant(grant.id!); console.log(disbursements.data?.length); ``` ``` -------------------------------- ### Payment API Examples Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Illustrates how to use the PaymentAPI for classic payments, including authorizing and capturing payments. ```APIDOC ## PaymentAPI (Classic Payments) `PaymentAPI` wraps the classic Payments API v68 for server-side 3DS flows and direct integrations. ```typescript import { Client, PaymentAPI, EnvironmentEnum, Types } from "@adyen/api-library"; const client = new Client({ username: "ws@Company.YourCompany", password: "YOUR_WS_PASSWORD", environment: EnvironmentEnum.TEST }); const paymentApi = new PaymentAPI(client); // Classic authorise payment const authResponse: Types.payment.PaymentResult = await paymentApi.PaymentsApi.authorise({ merchantAccount: "YOUR_MERCHANT_ACCOUNT", reference: "CLASSIC-ORDER-001", amount: { currency: "EUR", value: 1500 }, card: { number: "4111111111111111", expiryMonth: "03", expiryYear: "2030", cvc: "737", holderName: "J. Smith" } }); console.log(authResponse.resultCode, authResponse.pspReference); // Capture a previously authorised payment const captureResponse: Types.payment.ModificationResult = await paymentApi.ModificationsApi.capture({ merchantAccount: "YOUR_MERCHANT_ACCOUNT", modificationAmount: { currency: "EUR", value: 1500 }, originalReference: authResponse.pspReference! }); console.log(captureResponse.response); // "[capture-received]" ``` ``` -------------------------------- ### Client Setup for Live Environment Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Configures the Adyen client for live transactions. Requires an API key, environment set to LIVE, and your live URL prefix. ```typescript const { Client, EnvironmentEnum } = require('@adyen/api-library'); const client = new Client({apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, liveEndpointUrlPrefix: "YOUR_LIVE_URL_PREFIX"}); ``` -------------------------------- ### Terminal Cloud API Examples Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Shows how to use the TerminalCloudAPI to send payment requests to Adyen-hosted terminals via the cloud. ```APIDOC ## TerminalCloudAPI (In-Person Payments – Cloud) `TerminalCloudAPI` sends synchronous or asynchronous `SaleToPOIRequest` messages to Adyen-hosted terminals via the cloud Terminal API. ```typescript import { Client, TerminalCloudAPI, EnvironmentEnum, RegionEnum, Types } from "@adyen/api-library"; import { MessageClassType, MessageCategoryType, MessageType } from "@adyen/api-library/lib/src/typings/terminal/models"; const client = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, region: RegionEnum.EU }); const terminalCloudAPI = new TerminalCloudAPI(client); const paymentRequest: Types.terminal.SaleToPOIRequest = { MessageHeader: { MessageClass: MessageClassType.Service, MessageCategory: MessageCategoryType.Payment, MessageType: MessageType.Request, ProtocolVersion: "3.0", ServiceID: "SERVICE-001", SaleID: "POS-SystemID12345", POIID: "V400m-123456789" }, PaymentRequest: { SaleData: { SaleTransactionID: { TransactionID: "TX-001", TimeStamp: new Date().toISOString() } }, PaymentTransaction: { AmountsReq: { Currency: "EUR", RequestedAmount: 10.00 } } } }; // Synchronous request (waits for terminal response) const syncResponse: Types.terminal.TerminalApiResponse = await terminalCloudAPI.sync(paymentRequest); console.log(syncResponse.SaleToPOIResponse?.PaymentResponse?.Response?.Result); // Asynchronous request (returns "ok" on success; listen for event notification) const asyncResponse = await terminalCloudAPI.async(paymentRequest); if (typeof asyncResponse === "string") { console.log("Async accepted:", asyncResponse); // "ok" } else { console.error("Async failed:", asyncResponse.SaleToPOIRequest?.EventNotification); } ``` ``` -------------------------------- ### Initialize Adyen Client with Different Configurations Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Demonstrates initializing the Adyen `Client` for TEST and LIVE environments using API key authentication. For LIVE environments, specify `liveEndpointUrlPrefix` for online payments or `region` for Terminal API. Includes examples for username/password authentication and setting custom timeouts and application names. ```typescript import { Client, Config, EnvironmentEnum, RegionEnum } from "@adyen/api-library"; // TEST environment (API key auth) const testClient = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST }); // LIVE environment for online payment APIs (requires liveEndpointUrlPrefix) const liveClient = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, liveEndpointUrlPrefix: "YOUR_LIVE_URL_PREFIX" // e.g. "1797a841fbb37ca7-AdyenDemo" }); // LIVE environment for Terminal API (requires region) const terminalLiveClient = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, region: RegionEnum.EU // RegionEnum.EU | AU | US | APSE }); // Username/password auth (classic Payments / Payouts) const classicClient = new Client({ username: "ws@Company.YourCompany", password: "YOUR_WS_PASSWORD", environment: EnvironmentEnum.TEST }); // Custom timeout (default is 30 000 ms) testClient.setTimeouts(60000); // Custom application name (added to User-Agent) testClient.setApplicationName("MyShop/2.0"); ``` -------------------------------- ### Client Setup for Live Environments Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Configures the Adyen API client for live transactions, including specifying the API key, environment, and live endpoint URL prefix. ```APIDOC ## Client Setup ### Description Sets up the Adyen API client for live processing. This is required for APIs that use a Live URL Prefix. ### Method Client Initialization ### Parameters - **apiKey** (string) - Required - Your Adyen API key. - **environment** (string) - Required - The environment to use (e.g., `EnvironmentEnum.LIVE`). - **liveEndpointUrlPrefix** (string) - Required - Your Live URL Prefix obtained from Adyen. ### Request Example ```typescript const { Client, EnvironmentEnum } = require('@adyen/api-library'); const client = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, liveEndpointUrlPrefix: "YOUR_LIVE_URL_PREFIX" }); ``` ``` -------------------------------- ### Make a Payment Request with Adyen Node.js Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Example of initializing the Adyen client and making a payment request using the Checkout API. Requires API key, environment, and merchant account details. ```javascript // Step 1: Require the parts of the module you want to use const { Client, CheckoutAPI, EnvironmentEnum} = require('@adyen/api-library'); // Step 2: Initialize the client object const client = new Client({apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST}); // Step 3: Initialize the API object const checkoutApi = new CheckoutAPI(client); // Step 4: Create the request object const paymentRequest = { amount: { currency: "USD", value: 1000 // value in minor units }, reference: "Your order number", paymentMethod: { type: "scheme", encryptedCardNumber: "test_4111111111111111", encryptedExpiryMonth: "test_03", encryptedExpiryYear: "test_2030", encryptedSecurityCode: "test_737" }, shopperReference: "YOUR_UNIQUE_SHOPPER_ID_IOfW3k9G2PvXFu2j", storePaymentMethod: true, shopperInteraction: "Ecommerce", recurringProcessingModel: "CardOnFile", returnUrl: "https://your-company.com/", merchantAccount: "YOUR_MERCHANT_ACCOUNT" }; // Step 5: Make the request checkoutApi.PaymentsApi.payments(paymentRequest) .then(paymentResponse => console.log(paymentResponse.pspReference)) .catch(error => console.log(error)); ``` -------------------------------- ### Create a Hosted Payment Session Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Creates a checkout session for use with Adyen's Drop-in or Components. Requires merchant account, reference, return URL, amount, and optionally installment options. ```typescript // 4. Create a hosted payment session (for Drop-In / Components) const sessionResponse: Types.checkout.CreateCheckoutSessionResponse = await checkoutApi.PaymentsApi.sessions({ merchantAccount: "YOUR_MERCHANT_ACCOUNT", reference: "ORDER-12345", returnUrl: "https://your-company.com/checkout/result", countryCode: "NL", amount: { currency: "EUR", value: 1000 }, installmentOptions: { card: { plans: [Types.checkout.CheckoutSessionInstallmentOption.PlansEnum.Bonus] } } }); console.log(sessionResponse.sessionData); // pass to Drop-In/Component console.log(sessionResponse.expiresAt); // Date object ``` -------------------------------- ### LegalEntityManagementAPI Operations Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Examples of using the LegalEntityManagementAPI to create legal entities, manage business lines, upload documents, and retrieve Terms of Service. ```APIDOC ## LegalEntityManagementAPI `LegalEntityManagementAPI` wraps the Legal Entity Management API v3 for onboarding users as legal entities, managing documents, business lines, and Terms of Service acceptance. ### Create Legal Entity This method creates a new legal entity. #### Method POST #### Endpoint /legalEntities #### Request Body - **type** (string) - Required - The type of legal entity (e.g., `individual`). - **individual** (object) - Required if type is `individual` - The individual's details. - **name** (object) - Required - The name of the individual. - **firstName** (string) - Required - The first name. - **lastName** (string) - Required - The last name. - **birthData** (object) - Optional - The birth data of the individual. - **dateOfBirth** (string) - Required - The date of birth (YYYY-MM-DD). - **email** (string) - Optional - The email address. - **residentialAddress** (object) - Optional - The residential address. - **country** (string) - Required - The country code (e.g., NL). - **street** (string) - Required - The street name. - **houseNumberOrName** (string) - Required - The house number or name. - **postalCode** (string) - Required - The postal code. - **city** (string) - Required - The city name. #### Response #### Success Response (200) - **id** (string) - The unique identifier of the legal entity. ### Response Example ```json { "id": "LE3227C2232245..." } ``` ### Create Business Line This method creates a business line for a legal entity. #### Method POST #### Endpoint /businessLines #### Request Body - **legalEntityId** (string) - Required - The ID of the legal entity. - **industryCode** (string) - Required - The industry code. - **service** (string) - Required - The service provided (e.g., `paymentProcessing`). - **sourceOfFunds** (object) - Required - The source of funds. - **type** (string) - Required - The type of source of funds (e.g., `businessOperation`). ### Upload Document for Verification Checks This method uploads a document for KYC verification. #### Method POST #### Endpoint /documents #### Request Body - **attachment** (object) - Required - The document attachment details. - **content** (string) - Required - Base64 encoded file content. - **contentType** (string) - Required - The content type of the file (e.g., `image/jpeg`). - **filename** (string) - Required - The filename. - **pageName** (string) - Required - The page name (e.g., `front`). - **description** (string) - Optional - A description for the document. - **legalEntityId** (string) - Required - The ID of the legal entity. - **type** (string) - Required - The type of document (e.g., `identityCard`). #### Response #### Success Response (200) - **id** (string) - The unique identifier of the uploaded document. ### Get Terms of Service Document This method retrieves the Terms of Service document for a legal entity. #### Method GET #### Endpoint /termsOfService/{id} #### Parameters ##### Path Parameters - **id** (string) - Required - The unique identifier of the legal entity. ##### Query Parameters - **type** (string) - Required - The type of Terms of Service document (e.g., `adyenForPlatformsAdvanced`). - **language** (string) - Required - The language of the document (e.g., `en-US`). #### Response #### Success Response (200) - **termsOfServiceDocumentId** (string) - The unique identifier of the Terms of Service document. ``` -------------------------------- ### TransfersAPI Operations Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Examples of using the TransfersAPI to move funds, retrieve transfers, and query transactions. ```APIDOC ## TransfersAPI `TransfersAPI` wraps the Transfers API v4 and the Transactions API. It moves funds between balance accounts and bank accounts, retrieves individual transfers, and queries transaction history. ### Transfer Funds This method transfers funds between balance accounts and bank accounts. #### Method POST #### Endpoint /transfers #### Request Body - **amount** (object) - Required - The amount to transfer. - **currency** (string) - Required - The currency code (e.g., EUR). - **value** (integer) - Required - The amount value in the smallest currency unit. - **category** (string) - Required - The category of the transfer (e.g., `bank`). - **counterparty** (object) - Required - The counterparty details. - **bankAccount** (object) - Required - The bank account details. - **accountHolder** (object) - Required - The account holder's information. - **fullName** (string) - Required - The full name of the account holder. - **accountIdentification** (object) - Required - The bank account identification. - **iban** (string) - Required - The IBAN of the bank account. - **type** (string) - Required - The type of account identification (e.g., `iban`). - **description** (string) - Optional - A description for the transfer. - **reference** (string) - Optional - A reference for the transfer. ### Request Example ```json { "amount": {"currency": "EUR", "value": 1000}, "category": "bank", "counterparty": { "bankAccount": { "accountHolder": {"fullName": "Jane Smith"}, "accountIdentification": { "iban": "NL91ABNA0417164300", "type": "iban" } } }, "description": "Invoice payment", "reference": "INV-001" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the transfer. - **status** (string) - The status of the transfer (e.g., `received`). ### Response Example ```json { "id": "1W1UG35U8A9J5ZLG", "status": "received" } ``` ### Retrieve a Specific Transfer This method retrieves details of a specific transfer. #### Method GET #### Endpoint /transfers/{id} #### Parameters ##### Path Parameters - **id** (string) - Required - The unique identifier of the transfer. #### Response #### Success Response (200) - **amount** (object) - The amount of the transfer. - **status** (string) - The status of the transfer. ### Response Example ```json { "amount": {"currency": "EUR", "value": 1000}, "status": "received" } ``` ### List Transfers in a Date Range This method lists transfers within a specified date range. #### Method GET #### Endpoint /transfers #### Parameters ##### Query Parameters - **createdSince** (string) - Required - The start date for the transfer search (ISO 8601 format). - **createdUntil** (string) - Required - The end date for the transfer search (ISO 8601 format). - **balancePlatform** (string) - Required - The unique identifier of the balance platform. #### Response #### Success Response (200) - **data** (array) - An array of transfer objects. - **length** (integer) - The number of transfers returned. ### Response Example ```json { "data": [ { "id": "1W1UG35U8A9J5ZLG", "status": "received" } ] } ``` ### Get a Single Transaction This method retrieves details of a single transaction. #### Method GET #### Endpoint /transactions/{id} #### Parameters ##### Path Parameters - **id** (string) - Required - The unique identifier of the transaction. #### Response #### Success Response (200) - **id** (string) - The unique identifier of the transaction. - **status** (string) - The status of the transaction. ### Response Example ```json { "id": "IZK7C25U7DYVX03Y", "status": "pending" } ``` ### List Transactions in a Date Range This method lists transactions within a specified date range. #### Method GET #### Endpoint /transactions #### Parameters ##### Query Parameters - **createdSince** (string) - Required - The start date for the transaction search (ISO 8601 format). - **createdUntil** (string) - Required - The end date for the transaction search (ISO 8601 format). - **balancePlatform** (string) - Required - The unique identifier of the balance platform. #### Response #### Success Response (200) - **data** (array) - An array of transaction objects. - **id** (string) - The unique identifier of the transaction. ### Response Example ```json { "data": [ { "id": "IZK7C25U7DYVX03Y" } ] } ``` ``` -------------------------------- ### Get Card Brand Details by BIN Prefix Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves details about a card brand based on the Bank Identification Number (BIN) prefix. ```APIDOC ## Get Card Brand Details by BIN Prefix ### Description Retrieves details about a card brand based on the Bank Identification Number (BIN) prefix. ### Method `checkoutApi.PaymentsApi.cardDetails` ### Parameters #### Request Body - **merchantAccount** (string) - Required - Your Adyen merchant account. - **cardNumber** (string) - Required - The BIN prefix of the card number. ### Response #### Success Response (200) - **brands** (array) - A list of card brands matching the BIN prefix. - **supported** (boolean) - Whether the brand is supported. - **type** (string) - The type of the card brand (e.g., "visa"). ### Request Example ```typescript const cardDetails: Types.checkout.CardDetailsResponse = await checkoutApi.PaymentsApi.cardDetails({ merchantAccount: "YOUR_MERCHANT_ACCOUNT", cardNumber: "411111" }); console.log(cardDetails.brands?.[0]); ``` ### Response Example ```json { "brands": [ { "supported": true, "type": "visa" } ] } ``` ``` -------------------------------- ### Get Card Brand Details by BIN Prefix Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Fetches card brand information based on the Bank Identification Number (BIN) prefix. Useful for validating card numbers or displaying relevant brand logos. ```typescript // 6. Get card brand details by BIN prefix const cardDetails: Types.checkout.CardDetailsResponse = await checkoutApi.PaymentsApi.cardDetails({ merchantAccount: "YOUR_MERCHANT_ACCOUNT", cardNumber: "411111" }); console.log(cardDetails.brands?.[0]); // { supported: true, type: "visa" } ``` -------------------------------- ### Get Terminal Settings Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the terminal settings for a merchant. ```APIDOC ## Get Terminal Settings ### Description Retrieves the terminal settings configured for a specific merchant account. ### Method `mgmt.TerminalSettingsMerchantLevelApi.getTerminalSettings(merchantId)` ### Parameters #### Path Parameters - **merchantId** (string) - Required - The merchant account ID. ### Response Example ```json { "terminalSettings": { ... } } ``` ``` -------------------------------- ### Set Up Webhook Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Configures a new webhook at the merchant level. ```APIDOC ## Set Up Webhook ### Description Sets up a new webhook for a merchant account. This allows Adyen to send notifications to your server. ### Method `mgmt.WebhooksMerchantLevelApi.setUpWebhook(merchantId, webhookData)` ### Parameters #### Path Parameters - **merchantId** (string) - Required - The merchant account ID. #### Request Body - **url** (string) - Required - The URL where notifications should be sent. - **username** (string) - Optional - Username for basic authentication. - **password** (string) - Optional - Password for basic authentication. - **active** (boolean) - Required - Whether the webhook is active. - **communicationFormat** (enum) - Required - The format of the communication (e.g., 'Json'). - **networkType** (enum) - Required - The network type (e.g., 'Public'). - **encryptionProtocol** (enum) - Optional - The encryption protocol to use (e.g., 'Tlsv12'). ### Response Example ```json { "id": "string", "url": "string", "username": "string", "active": true, "communicationFormat": "Json", "networkType": "Public", "encryptionProtocol": "Tlsv12" } ``` ``` -------------------------------- ### Get API Credential Details Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the details of the current API credential. ```APIDOC ## Get API Credential Details ### Description Retrieves the details of the current API credential, including its ID, company name, and active status. ### Method `mgmt.MyAPICredentialApi.getApiCredentialDetails()` ### Response Example ```json { "id": "string", "companyName": "string", "active": true } ``` ``` -------------------------------- ### Get the Result of a Completed Session Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the status and details of a completed payment session. ```APIDOC ## Get the Result of a Completed Session ### Description Retrieves the status and details of a completed payment session. ### Method `checkoutApi.PaymentsApi.getResultOfPaymentSession` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the payment session. #### Request Body - **sessionResult** (object) - Required - The result of the session. ### Response #### Success Response (200) - **status** (string) - The status of the session (e.g., "completed"). ### Request Example ```typescript const sessionResult: Types.checkout.SessionResultResponse = await checkoutApi.PaymentsApi.getResultOfPaymentSession("CS12345678", sessionResult); console.log(sessionResult.status); ``` ### Response Example ```json { "status": "completed" } ``` ``` -------------------------------- ### Initialize Adyen Client Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Instantiate the Adyen client by providing your API key and specifying the environment (TEST or LIVE). The API key should be generated from the Adyen Customer Area. ```javascript const client = new Client({apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST}); ``` -------------------------------- ### Initialize ManagementAPI Client Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Instantiate the ManagementAPI client with your API key and environment. Ensure you replace 'YOUR_API_KEY' with your actual Adyen API key. ```typescript import { Client, ManagementAPI, EnvironmentEnum, Types } from "@adyen/api-library"; import { management } from "@adyen/api-library/lib/src/typings"; const client = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST }); const mgmt = new ManagementAPI(client); ``` -------------------------------- ### Get a Single Transaction with TransactionsAPI Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves details for a specific transaction using its unique ID. Requires a transaction ID. ```typescript // Get a single transaction const tx: transfers.Transaction = await transfersApi.TransactionsApi.getTransaction("IZK7C25U7DYVX03Y"); ``` -------------------------------- ### Get All Balance Accounts of Account Holder Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves a list of all balance accounts associated with a given account holder, with support for pagination. ```APIDOC ## Get All Balance Accounts of Account Holder ### Description Retrieves a paginated list of balance accounts for a specified account holder. ### Method GET ### Endpoint /accountHolders/{accountHolderId}/balanceAccounts ### Parameters #### Path Parameters - **accountHolderId** (string) - Required - The ID of the account holder whose balance accounts are to be retrieved. #### Query Parameters - **limit** (string) - Optional - The maximum number of balance accounts to return per page. - **offset** (string) - Optional - The number of balance accounts to skip before starting to collect the result set. ### Response #### Success Response (200) - **data** (array) - A list of balance account objects. - **hasNext** (boolean) - Indicates if there are more results available. ``` -------------------------------- ### Create Account Holder, Balance Account, Sweep, and Payment Instrument with BalancePlatformAPI Source: https://context7.com/adyen/adyen-node-api-library/llms.txt This snippet demonstrates the full lifecycle of creating core financial objects using the BalancePlatformAPI. Ensure you have your API key, environment, and balance platform details configured. ```typescript import { Client, BalancePlatformAPI, EnvironmentEnum, Types } from "@adyen/api-library"; const client = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST }); const bp = new BalancePlatformAPI(client); // Create an account holder const accountHolder: Types.balancePlatform.AccountHolder = await bp.AccountHoldersApi.createAccountHolder({ balancePlatform: "YOUR_BALANCE_PLATFORM", description: "S.Hopper - Staff 123", legalEntityId: "LE322KT223222D5FJ7THR293F", contactDetails: { email: "s.hopper@example.com", phone: { number: "+315551231234", type: Types.balancePlatform.Phone.TypeEnum.Mobile }, address: { city: "Amsterdam", country: "NL", street: "Brannan Street", houseNumberOrName: "274", postalCode: "1020CD" } } }); console.log(accountHolder.id); // "AH3227C223222B5CMD2SXFKGT" // Create a balance account linked to the account holder const balanceAccount: Types.balancePlatform.BalanceAccount = await bp.BalanceAccountsApi.createBalanceAccount({ accountHolderId: accountHolder.id!, description: "EUR Balance Account", defaultCurrencyCode: "EUR" }); console.log(balanceAccount.id); // List all balance accounts for an account holder (with pagination) const allBalances = await bp.AccountHoldersApi.getAllBalanceAccountsOfAccountHolder( accountHolder.id!, { params: { limit: "5", offset: "0" } } as any ); // Add a sweep to a balance account (automatic fund sweeping) const sweep: Types.balancePlatform.SweepConfigurationV2 = await bp.BalanceAccountsApi.createSweep("BA32272223222B59CZ3T52DKZ", { counterparty: { merchantAccount: "YOUR_MERCHANT_ACCOUNT" }, triggerAmount: { currency: "EUR", value: 50000 }, currency: "EUR", schedule: { type: Types.balancePlatform.SweepSchedule.TypeEnum.Daily }, type: Types.balancePlatform.SweepConfigurationV2.TypeEnum.Pull }); // Create a payment instrument (virtual card) const pi: Types.balancePlatform.PaymentInstrument = await bp.PaymentInstrumentsApi.createPaymentInstrument({ balanceAccountId: balanceAccount.id!, type: Types.balancePlatform.PaymentInstrumentInfo.TypeEnum.Card, issuingCountryCode: "NL", card: { formFactor: Types.balancePlatform.CardInfo.FormFactorEnum.Virtual, brandVariant: "mc_prepaid", cardholderName: "S Hopper" } }); console.log(pi.id, pi.card?.lastFour); ``` -------------------------------- ### Get Terminal Settings for Merchant Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the terminal settings for a given merchant account. This allows you to view and manage configurations related to Adyen terminals. ```typescript // Get terminal settings for a merchant const terminalSettings: management.TerminalSettings = await mgmt.TerminalSettingsMerchantLevelApi.getTerminalSettings("MERCHANT_ID"); ``` -------------------------------- ### Generate All Node.js Services Source: https://github.com/adyen/adyen-node-api-library/blob/main/AGENTS.md Run this Gradle command from the adyen-sdk-automation directory to generate all services for the Node.js library. ```bash ./gradlew :node:services ``` -------------------------------- ### Get Current API Credential Details Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the details of the currently authenticated API credential. This is useful for verifying credentials or obtaining basic account information. ```typescript // Get current API credential details const me: management.MeApiCredential = await mgmt.MyAPICredentialApi.getApiCredentialDetails(); console.log(me.id, me.companyName, me.active); ``` -------------------------------- ### Hosted Onboarding API Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Provides endpoints to generate links for Adyen-hosted pages like onboarding and PCI compliance questionnaires. These links can be shared with account holders to complete their onboarding process. ```APIDOC ## Hosted Onboarding API (v6) ### Description Provides endpoints that you can use to generate links to Adyen-hosted pages, such as an onboarding page or a PCI compliance questionnaire. You can provide these links to your account holders so that they can complete their onboarding. ### Service [HostedOnboardingPage](/src/services/platforms.ts) ``` -------------------------------- ### TypeScript Payment Request with Async/Await Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Demonstrates making a payment request in TypeScript using async/await syntax and Adyen's Types for better type safety. Includes detailed payment request object construction. ```typescript const { Client, EnvironmentEnum, CheckoutAPI, Types } = require('@adyen/api-library'); const client = new Client({apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, liveEndpointUrlPrefix: "YOUR_LIVE_URL_PREFIX"}); const makePaymentsRequest = async () => { const paymentsRequest : Types.checkout.PaymentRequest = { amount: { currency: "USD", value: 1000 // Value in minor units. }, reference: "Your order number", paymentMethod: { type: Types.checkout.CardDetails.TypeEnum.Scheme, encryptedCardNumber: "test_4111111111111111", encryptedExpiryMonth: "test_03", encryptedExpiryYear: "test_2030", encryptedSecurityCode: "test_737" }, shopperReference: "YOUR_UNIQUE_SHOPPER_ID_IOfW3k9G2PvXFu2j", storePaymentMethod: true, shopperInteraction: Types.checkout.PaymentRequest.ShopperInteractionEnum.Ecommerce, recurringProcessingModel: Types.checkout.PaymentRequest.RecurringProcessingModelEnum.CardOnFile, returnUrl: "https://your-company.com/", merchantAccount: "YOUR_MERCHANT_ACCOUNT" }; const checkoutAPI = new CheckoutAPI(client); const paymentResponse : Types.checkout.PaymentResponse = await checkoutAPI.PaymentsApi.payments(paymentsRequest); console.log(paymentResponse.pspReference); } makePaymentsRequest(); ``` -------------------------------- ### TypeScript Usage with Async/Await Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Demonstrates how to use the Adyen Node.js library with TypeScript and async/await syntax for making payment requests. ```APIDOC ## TypeScript Payment Request ### Description Shows how to make a payment request using TypeScript, including type definitions and async/await. ### Method Async Function ### Request Example ```typescript const { Client, EnvironmentEnum, CheckoutAPI, Types } = require('@adyen/api-library'); const client = new Client({apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.LIVE, liveEndpointUrlPrefix: "YOUR_LIVE_URL_PREFIX"}); const makePaymentsRequest = async () => { const paymentsRequest : Types.checkout.PaymentRequest = { amount: { currency: "USD", value: 1000 // Value in minor units. }, reference: "Your order number", paymentMethod: { type: Types.checkout.CardDetails.TypeEnum.Scheme, encryptedCardNumber: "test_4111111111111111", encryptedExpiryMonth: "test_03", encryptedExpiryYear: "test_2030", encryptedSecurityCode: "test_737" }, shopperReference: "YOUR_UNIQUE_SHOPPER_ID_IOfW3k9G2PvXFu2j", storePaymentMethod: true, shopperInteraction: Types.checkout.PaymentRequest.ShopperInteractionEnum.Ecommerce, recurringProcessingModel: Types.checkout.PaymentRequest.RecurringProcessingModelEnum.CardOnFile, returnUrl: "https://your-company.com/", merchantAccount: "YOUR_MERCHANT_ACCOUNT" }; const checkoutAPI = new CheckoutAPI(client); const paymentResponse : Types.checkout.PaymentResponse = await checkoutAPI.PaymentsApi.payments(paymentsRequest); console.log(paymentResponse.pspReference); } makePaymentsRequest(); ``` ``` -------------------------------- ### Get Result of a Completed Session Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the status of a completed payment session using the session ID. This is useful for confirming the final outcome of a transaction initiated via a session. ```typescript // 5. Get the result of a completed session const sessionResult: Types.checkout.SessionResultResponse = await checkoutApi.PaymentsApi.getResultOfPaymentSession("CS12345678", sessionResult); console.log(sessionResult.status); // "completed" ``` -------------------------------- ### Set Up Webhook at Merchant Level Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Configures a webhook for a merchant account. Requires the merchant ID and a webhook configuration object including URL, credentials, and communication settings. ```typescript // Set up a webhook at merchant level const webhook: management.Webhook = await mgmt.WebhooksMerchantLevelApi.setUpWebhook("MERCHANT_ID", { url: "https://your-server.com/adyen/webhooks", username: "YOUR_WH_USER", password: "YOUR_WH_PASS", active: true, communicationFormat: management.CreateMerchantWebhookRequest.CommunicationFormatEnum.Json, networkType: management.CreateMerchantWebhookRequest.NetworkTypeEnum.Public, encryptionProtocol: management.CreateMerchantWebhookRequest.EncryptionProtocolEnum.Tlsv12 }); ``` -------------------------------- ### Initialize Local Terminal API Integration with Encryption Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md This snippet demonstrates setting up the Adyen Node API library for local Terminal API integration with encryption. Ensure your certificate is correctly path-ed and the local endpoint is accurate. A security key object with necessary details is also required. ```javascript // Step 1: Require the parts of the module you want to use const {Client, TerminalLocalAPI} = require("@adyen/api-library"); // Step 2: Add your Certificate Path and Local Endpoint to the config path. Install the certificate and save it in your project folder as "cert.cer" const config = new Config(); config.certificatePath = "./cert.cer"; config.terminalApiLocalEndpoint = "The IP of your terminal (eg https://192.168.47.169)"; config.apiKey = "YOUR_API_KEY_HERE"; // Step 3: Setup a security password for your terminal in CA, and import the security key object: const securityKey = { AdyenCryptoVersion: 1, KeyIdentifier: "keyIdentifier", KeyVersion: 1, Passphrase: "passphrase", }; // Step 4 Initialize the client and the API objects client = new Client({ config }); const terminalLocalAPI = new TerminalLocalAPI(client); // Step 5: Create the request object const paymentRequest = { // Similar to the saleToPOIRequest used for Cloud API } // Step 6: Make the request const terminalApiResponse = await terminalLocalAPI.request(paymentRequest, securityKey); ``` -------------------------------- ### Link Local Adyen Node.js Library to Automation Project Source: https://github.com/adyen/adyen-node-api-library/blob/main/AGENTS.md Link your local Adyen Node.js API library to the automation project by replacing the 'node/repo' directory with a symbolic link. This ensures the automation project targets your local development version. ```bash rm -rf node/repo ln -s /path/to/your/adyen-node-api-library node/repo ``` -------------------------------- ### Get Terms of Service Document with LegalEntityManagementAPI Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Retrieves the Terms of Service document for a legal entity. Requires the legal entity ID, document type, and language. The response includes the terms of service document ID. ```typescript // Get Terms of Service document const tos = await lem.TermsOfServiceApi.getTermsOfServiceDocument(le.id!, { type: Types.legalEntityManagement.GetTermsOfServiceDocumentRequest.TypeEnum.AdyenForPlatformsAdvanced, language: "en-US" }); console.log(tos.termsOfServiceDocumentId); ``` -------------------------------- ### Generate Single Node.js Service (Checkout) Source: https://github.com/adyen/adyen-node-api-library/blob/main/AGENTS.md Generate a specific service, such as Checkout, for the Node.js library using this Gradle command. ```bash ./gradlew :node:checkout ``` -------------------------------- ### Configure Custom HTTP Client with Axios Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Sets up the Adyen client to use Axios as the custom HTTP client. Ensure all required properties like API key and content-type are handled by the custom client. ```javascript const {Client, Config} = require('@adyen/api-library'); const axios = require("axios"); // ... more code const config = new Config(); const client = new Client({ config, httpClient: { async request(endpoint, json, config, isApiKeyRequired, requestOptions) { const response = await axios({ method: 'POST', url: endpoint, data: JSON.parse(json), headers: { "X-API-Key": config.apiKey, "Content-type": "application/json" }, }); return response.data; } } }); // ... more code ``` -------------------------------- ### Making a Payment Request Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md This snippet demonstrates how to construct a payment request object and use the CheckoutAPI to process a payment. ```APIDOC ## POST /payments ### Description Initiates a payment transaction. ### Method POST ### Endpoint /payments ### Request Body - **amount** (object) - Required - The transaction amount. - **currency** (string) - Required - The currency of the amount (e.g., "USD"). - **value** (number) - Required - The transaction amount in minor units (e.g., 1000 for $10.00). - **reference** (string) - Required - Your unique order number. - **paymentMethod** (object) - Required - Details of the payment method. - **type** (string) - Required - The type of payment method (e.g., "scheme"). - **encryptedCardNumber** (string) - Required - The encrypted card number. - **encryptedExpiryMonth** (string) - Required - The encrypted expiry month. - **encryptedExpiryYear** (string) - Required - The encrypted expiry year. - **encryptedSecurityCode** (string) - Required - The encrypted security code. - **shopperReference** (string) - Required - Your unique shopper ID. - **storePaymentMethod** (boolean) - Optional - Whether to store the payment method for future use. - **shopperInteraction** (string) - Optional - The shopper's interaction type (e.g., "Ecommerce"). - **recurringProcessingModel** (string) - Optional - The recurring processing model (e.g., "CardOnFile"). - **returnUrl** (string) - Optional - The URL to redirect the shopper to after the payment. - **merchantAccount** (string) - Required - Your Adyen merchant account. ### Request Example ```javascript const paymentRequest = { amount: { currency: "USD", value: 1000 // value in minor units }, reference: "Your order number", paymentMethod: { type: "scheme", encryptedCardNumber: "test_4111111111111111", encryptedExpiryMonth: "test_03", encryptedExpiryYear: "test_2030", encryptedSecurityCode: "test_737" }, shopperReference: "YOUR_UNIQUE_SHOPPER_ID_IOfW3k9G2PvXFu2j", storePaymentMethod: true, shopperInteraction: "Ecommerce", recurringProcessingModel: "CardOnFile", returnUrl: "https://your-company.com/", merchantAccount: "YOUR_MERCHANT_ACCOUNT" }; checkoutApi.PaymentsApi.payments(paymentRequest) .then(paymentResponse => console.log(paymentResponse.pspReference)) .catch(error => console.log(error)); ``` ### Response #### Success Response (200) - **pspReference** (string) - The unique identifier for the payment transaction. ``` -------------------------------- ### Create a Legal Entity with LegalEntityManagementAPI Source: https://context7.com/adyen/adyen-node-api-library/llms.txt Onboards a new legal entity, specifying its type and individual details. Requires a valid API key and environment configuration. The response includes the newly created legal entity's ID. ```typescript import { Client, LegalEntityManagementAPI, EnvironmentEnum, Types } from "@adyen/api-library"; const client = new Client({ apiKey: "YOUR_API_KEY", environment: EnvironmentEnum.TEST }); const lem = new LegalEntityManagementAPI(client); // Create a legal entity const le: Types.legalEntityManagement.LegalEntity = await lem.LegalEntitiesApi.createLegalEntity({ type: Types.legalEntityManagement.LegalEntityInfo.TypeEnum.Individual, individual: { name: { firstName: "Sam", lastName: "Hopper" }, birthData: { dateOfBirth: "1990-01-01" }, email: "s.hopper@example.com", residentialAddress: { country: "NL", street: "Brannan Street", houseNumberOrName: "274", postalCode: "1020CD", city: "Amsterdam" } } }); console.log(le.id); // "LE3227C2232245..." ``` -------------------------------- ### Make a Payment Request Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Initiates a payment request using the CheckoutAPI object. Handles success by logging the PSP reference and errors by logging the error object. ```javascript checkoutApi.PaymentsApi.payments(paymentRequest) .then(paymentResponse => console.log(paymentResponse.pspReference)) .catch(error => console.log(error)); ``` -------------------------------- ### Custom HTTP Client Configuration Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Shows how to configure a custom HTTP client, such as Axios, for making API requests instead of the default Node.js https module. ```APIDOC ## Custom HTTP Client ### Description Allows configuration of a custom HTTP client for making API requests, offering more flexibility than the default Node.js https module. ### Method Client Configuration ### Parameters - **httpClient** (object) - Required - An object implementing the request method. - **request** (function) - Async function that handles the HTTP request. - **endpoint** (string) - The API endpoint URL. - **json** (string) - The request body as a JSON string. - **config** (object) - Client configuration object. - **isApiKeyRequired** (boolean) - Whether the API key is required for the request. - **requestOptions** (object) - Additional request options. ### Request Example ```javascript const {Client, Config} = require('@adyen/api-library'); const axios = require("axios"); const config = new Config(); const client = new Client({ config, httpClient: { async request(endpoint, json, config, isApiKeyRequired, requestOptions) { const response = await axios({ method: 'POST', url: endpoint, data: JSON.parse(json), headers: { "X-API-Key": config.apiKey, "Content-type": "application/json" }, }); return response.data; } } }); ``` ``` -------------------------------- ### Initialize Adyen API Object Source: https://github.com/adyen/adyen-node-api-library/blob/main/README.md Create an instance of a specific Adyen API object (e.g., CheckoutAPI) by passing the initialized client object. This prepares the object for making API calls. ```javascript const checkoutApi = new CheckoutAPI(client); ```