### Install Trolley JavaScript SDK Source: https://github.com/trolley/javascript-sdk/blob/master/README.md Command to install the Trolley JavaScript SDK using npm. This should be run in your project's root directory. ```bash npm install --save trolleyhq ``` -------------------------------- ### Start Batch Processing Source: https://context7.com/trolley/javascript-sdk/llms.txt Initiates the processing of a batch to send payments. ```typescript const processingBatch = await client.batch.startProcessing("B-abc123"); console.log(processingBatch.status); // "processing" ``` -------------------------------- ### GET /batches Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/batchgateway.md Fetch all batches using an iterator. ```APIDOC ## GET /batches ### Description Fetch all batches with an Iterator. ### Method GET ### Endpoint /batches ### Response #### Success Response (200) - **batches** (Batch[]) - A list of batch objects. ``` -------------------------------- ### GET /batch/summary Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves a detailed summary of a batch, including totals by payment method. ```APIDOC ## GET /batch/summary ### Description Retrieves a detailed summary of the batch including totals by payment method. ### Method GET ### Parameters #### Path Parameters - **batchId** (string) - Required - The unique identifier of the batch. ``` -------------------------------- ### Get All Account Balances Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves account balances for all enabled bank accounts. Iterates through the balances and logs their details. ```typescript const balances = await client.balances.all(); balances.forEach(balance => { console.log(`${balance.type}: ${balance.amount} ${balance.currency}`); console.log(`Account: ${balance.accountNumber}`); console.log(`Primary: ${balance.primary}`); }); ``` -------------------------------- ### Get Batch Summary Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves a detailed summary of a batch, including totals by payment method. ```typescript const summary = await client.batch.summary("B-abc123"); console.log(summary.total.count); console.log(summary.total.debitAmount); console.log(summary.total.merchantFees); console.log(summary.total.totalFees); console.log(summary.total.sendingAmount); // Summary by payment method Object.entries(summary.detail).forEach(([method, info]) => { console.log(`${method}: ${info.count} payments, ${info.sendingAmount} total`); }); ``` -------------------------------- ### Get PayPal Balance by Type Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves the balance for the 'paypal' account type. Logs the balance amount and currency. ```typescript // Get PayPal balance const paypalBalances = await client.balances.find("paypal"); paypalBalances.forEach(balance => { console.log(`PayPal Balance: ${balance.amount} ${balance.currency}`); }); ``` -------------------------------- ### GET /batch/paymentList Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves a paginated list of payments within a specific batch. ```APIDOC ## GET /batch/paymentList ### Description Retrieves paginated list of payments within a batch. ### Method GET ### Parameters #### Path Parameters - **batchId** (string) - Required - The unique identifier of the batch. - **page** (number) - Required - The page number for pagination. - **pageSize** (number) - Required - The number of records per page. ``` -------------------------------- ### GET /payment/find Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves a specific payment by its ID. ```APIDOC ## GET /payment/find ### Description Retrieves a specific payment by its ID. ### Method GET ### Parameters #### Path Parameters - **paymentId** (string) - Required - The unique identifier of the payment. ``` -------------------------------- ### GET /recipients/search Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientgateway.md Searches for recipients based on pagination and search terms. ```APIDOC ## GET /recipients/search ### Description Search for recipients. ### Parameters #### Query Parameters - **page** (number) - Required - The page number - **pageSize** (number) - Required - The number of items per page - **term** (string) - Required - The search term ### Response #### Success Response (200) - **recipients** (Recipient[]) - A list of matching recipients ``` -------------------------------- ### Search for payments in a batch Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/paymentgateway.md Find payments within a specific batch. Supports pagination and searching by a term. Default page size is 10 and starts from page 1. ```javascript const payments = await client.payment.search('B-xx999bb', 1, 10, ''); ``` -------------------------------- ### GET /batches/{batchId} Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/batchgateway.md Retrieves a specific batch by its ID. ```APIDOC ## GET /batches/{batchId} ### Description Retrieves a batch based on the batch id. ### Method GET ### Endpoint /batches/{batchId} ### Parameters #### Path Parameters - **batchId** (string) - Required - Trolley payment id (e.g. "B-xx999bb") ### Response #### Success Response (200) - **batch** (Batch) - The requested batch object. ``` -------------------------------- ### GET /recipients/{recipientId}/accounts Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientaccountgateway.md Fetch all of the accounts for a given Trolley recipient. ```APIDOC ## GET /recipients/{recipientId}/accounts ### Description Fetch all of the accounts for a given Trolley recipient. ### Parameters #### Path Parameters - **recipientId** (string) - Required - The Trolley recipient ID (e.g. R-xyzzy) ### Request Example ```javascript const accounts = await client.recipientAccount.all('R-1234'); ``` ``` -------------------------------- ### GET /recipients/{recipientId}/accounts/{accountId} Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientaccountgateway.md Fetch a specific account for a given Trolley recipient. ```APIDOC ## GET /recipients/{recipientId}/accounts/{accountId} ### Description Fetch a specific account for a given Trolley recipient. ### Parameters #### Path Parameters - **recipientId** (string) - Required - The Trolley recipient ID (e.g. R-xyzzy) - **accountId** (string) - Required - The Trolley account ID (e.g. A-xyzzy) ### Request Example ```javascript const account = await client.recipientAccount.find('R-1234', 'A-789'); ``` ``` -------------------------------- ### Get Batch Summary Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/batchgateway.md Retrieves a transaction totaled summary for a specific batch. ```APIDOC ## GET /batch/{batchId}/summary ### Description Get a transaction totaled summary for this batch. ### Method GET ### Endpoint /batch/{batchId}/summary ### Parameters #### Path Parameters - **batchId** (string) - Required - Trolley payment id (e.g. "B-xx999bb") ### Response #### Success Response (200) - **BatchSummary** (object) - An object containing the batch summary details. #### Response Example ```json { "example": "{\"total\": 1000, \"currency\": \"USD\", \"count\": 10}" } ``` ``` -------------------------------- ### Get Trolley Balance by Type Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves the balance for the 'paymentrails' account type. Logs the balance amount and currency. ```typescript // Get Trolley (PaymentRails) balance const trolleyBalances = await client.balances.find("paymentrails"); trolleyBalances.forEach(balance => { console.log(`Trolley Balance: ${balance.amount} ${balance.currency}`); }); ``` -------------------------------- ### Connecting to the API Source: https://context7.com/trolley/javascript-sdk/llms.txt Demonstrates how to create a client gateway instance for interacting with the Trolley API using API keys and optional custom base URLs. ```APIDOC ## Connecting to the API The `connect()` function creates a client gateway instance that provides access to all API operations. It requires your Trolley API public key and secret key for authentication. ### Request Example ```typescript const trolley = require('trolleyhq'); // Create a client connection const client = trolley.connect({ key: "YOUR-ACCESS-KEY", secret: "YOUR-SECRET-KEY", }); // Optional: Set a custom API base URL for testing const testClient = trolley.connect({ key: "YOUR-ACCESS-KEY", secret: "YOUR-SECRET-KEY", apiBase: "https://api.sandbox.trolley.com", }); // Alternative: Set credentials globally const { Configuration } = require('trolleyhq'); Configuration.setApiKey("YOUR-ACCESS-KEY"); Configuration.setApiSecret("YOUR-SECRET-KEY"); const globalClient = Configuration.gateway(); ``` ``` -------------------------------- ### connect Source: https://github.com/trolley/javascript-sdk/blob/master/docs/README.md Initializes the Trolley client using provided configuration parameters. ```APIDOC ## connect ### Description Create a client for the Trolley (Payment Rails) JavaScript API. ### Parameters #### Request Body - **config** (ConfigurationParams) - Required - The configuration parameters including key and secret. ### Request Example { "key": "MY_PUBLIC_KEY", "secret": "MY_PRIVATE_KEY" } ### Response - **Gateway** (Object) - Returns a Gateway instance for interacting with the API. ``` -------------------------------- ### Initialize Trolley Client and Find Recipient (Async/Await) Source: https://github.com/trolley/javascript-sdk/blob/master/README.md Sets up the Trolley client with API credentials and demonstrates finding a recipient using async/await. Ensure your API key and secret are correctly configured. ```javascript const trolley = require('trolleyhq'); const client = trolley.connect({ key: "YOUR-ACCESS-KEY", secret: "YOUR-SECRET-SECRET", }); // Async/Await version async function main() { const recipient = await client.recipient.find("R-G7SXXpm6cs4aTUd9YhmgWC"); console.log(recipient.id); } main(); ``` -------------------------------- ### Run Trolley SDK Integration Tests Source: https://github.com/trolley/javascript-sdk/blob/master/README.md Commands to set up and run integration tests for the Trolley SDK. This involves copying an environment file, setting credentials, and executing the test suite. ```bash # if not already, copy the example env file to create an env file $ cp .env.test .env # Set access key and secret in the env file TROLLEY_ACCESS_KEY="ACCESS_KEY" TROLLEY_SECRET_KEY="SECRET_KEY" #Run the fixture based tests $ npm test ``` -------------------------------- ### Initialize Trolley Client and Find Recipient (Promises) Source: https://github.com/trolley/javascript-sdk/blob/master/README.md Sets up the Trolley client with API credentials and demonstrates finding a recipient using promises. Includes basic error handling. Ensure your API key and secret are correctly configured. ```javascript client.recipient.find("R-G7SXXpm6cs4aTUd9YhmgWC").then(recipient => { console.log(recipient.id); }).catch(err => { console.log("ERROR", err); }); ``` -------------------------------- ### Configuration Methods Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/configuration.md Methods for setting configuration parameters for the Trolley SDK. ```APIDOC ## Configuration Methods ### Description These static methods allow you to globally configure the Trolley JavaScript SDK. ### Methods #### `setApiKey(key: string): void` * **Description**: Globally set the public API key to connect to Trolley. * **Parameters**: * `key` (string) - Required - Your Trolley API public key. #### `setApiSecret(secret: string): void` * **Description**: Globally set the secret API key to connect to Trolley. * **Parameters**: * `secret` (string) - Required - Your Trolley API secret Key. #### `setEnvironment(environment: "production" | "sandbox" | "integration"): void` * **Description**: Set the Trolley API environment that you are using. * **Parameters**: * `environment` (string) - Required - One of "production", "sandbox", or "integration". ``` -------------------------------- ### all() Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/balancesgateway.md Fetch the account balance for all enabled bank accounts. ```APIDOC ## all() ### Description Fetch the account balance for all enabled bank accounts. ### Returns - **Promise** - A promise that resolves to an array of balance objects. ### Example ```javascript const balances = await client.balances.all(); ``` ``` -------------------------------- ### Create a Batch Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/batchgateway.md Creates a new batch with optional payments. Requires a BatchInput object and an optional array of PaymentInput objects. ```javascript const batch = await client.batch.create({ description: "My Batch", sourceCurrency: "USD", }, [ { recipient: { email: "john@example.com", }, sourceAmount: "10.20", }, ]); ``` -------------------------------- ### Configuration Properties Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/configuration.md Properties available for configuring the Trolley SDK. ```APIDOC ## Configuration Properties ### Description These properties allow you to inspect the current configuration of the Trolley SDK. ### Properties * **apiBase** (string) - The base URL for the Trolley API. * **apiKey** (string) - The public API key for authentication. * **apiSecret** (string) - The secret API key for authentication. ``` -------------------------------- ### GET /recipients/{recipientId} Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientgateway.md Finds a specific recipient by their unique Trolley recipient ID. ```APIDOC ## GET /recipients/{recipientId} ### Description Find a specific recipient by their Trolley recipient ID. ### Parameters #### Path Parameters - **recipientId** (string) - Required - The Trolley recipient ID (e.g. R-xyzzy) ### Response #### Success Response (200) - **recipient** (Recipient) - The recipient object ``` -------------------------------- ### ConfigurationParams Interface Source: https://github.com/trolley/javascript-sdk/blob/master/docs/interfaces/configurationparams.md Defines the structure for the configuration object required to initialize the Trolley SDK. ```APIDOC ## ConfigurationParams Interface ### Description The ConfigurationParams interface is used to define the authentication and environment settings for the Trolley JavaScript SDK. ### Properties - **environment** (string) - Optional - The environment to use. Options: "production", "sandbox", "integration", "development". - **key** (string) - Required - The Trolley public key. - **secret** (string) - Required - The Trolley private key. ### Request Example { "key": "your_public_key", "secret": "your_private_key", "environment": "sandbox" } ``` -------------------------------- ### Create a Batch Source: https://context7.com/trolley/javascript-sdk/llms.txt Creates a new payment batch, optionally including a list of payments. ```typescript // Create empty batch const batch = await client.batch.create({ description: "Weekly Contractor Payments", sourceCurrency: "USD", }); console.log(batch.id); // "B-abc123" console.log(batch.status); // "open" // Create batch with payments included const batchWithPayments = await client.batch.create( { description: "Q4 Royalty Payments", sourceCurrency: "USD", }, [ { recipient: { email: "john@example.com" }, sourceAmount: "100.00", memo: "October royalties", }, { recipient: { email: "jane@example.com" }, sourceAmount: "250.00", memo: "October royalties", }, { recipient: { id: "R-abc123xyz" }, targetAmount: "500.00", targetCurrency: "EUR", }, ] ); ``` -------------------------------- ### POST /batches Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/batchgateway.md Creates a new batch with optional payments. ```APIDOC ## POST /batches ### Description Creates a batch with optional payments. ### Method POST ### Endpoint /batches ### Parameters #### Request Body - **batch** (BatchInput) - Required - The batch details. - **payments** (PaymentInput[]) - Optional - A list of payments to include in the batch. ### Request Example { "description": "My Batch", "sourceCurrency": "USD" } ### Response #### Success Response (200) - **batch** (Batch) - The created batch object. ``` -------------------------------- ### Exceptions Module Overview Source: https://github.com/trolley/javascript-sdk/blob/master/docs/modules/exceptions.md This section provides an overview of the exceptions module and lists the available exception classes. ```APIDOC ## Module: Exceptions This module provides custom exception classes for handling various error scenarios within the Trolley JavaScript SDK. ### Available Exception Classes: * `Authentication`: Represents errors related to authentication failures. * `Authorization`: Represents errors related to authorization failures. * `BaseException`: The base class for all custom exceptions in this module. * `DownForMaintenance`: Indicates that the service is temporarily unavailable due to maintenance. * `Malformed`: Represents errors where the request data is malformed or invalid. * `NotFound`: Indicates that a requested resource could not be found. * `ServerError`: Represents errors originating from the server. * `Unexpected`: Catches any other unexpected errors. ``` -------------------------------- ### List All Batches Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves all batches in the account. ```typescript const batches = await client.batch.all(); batches.forEach(batch => { console.log(`Batch ${batch.id}: ${batch.description}`); console.log(`Status: ${batch.status}, Payments: ${batch.totalPayments}`); }); ``` -------------------------------- ### find(kind) Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/balancesgateway.md Fetch the account balance for the given account type. ```APIDOC ## find(kind) ### Description Fetch the account balance for the given account type. ### Parameters - **kind** ("paypal" | "paymentrails") - Required - The account type to get the balances for. ### Returns - **Promise** - A promise that resolves to an array of balance objects. ### Example ```javascript const balances = await client.balances.find("paymentrails"); ``` ``` -------------------------------- ### POST /payment/create Source: https://context7.com/trolley/javascript-sdk/llms.txt Creates a new payment within an existing batch. ```APIDOC ## POST /payment/create ### Description Creates a new payment within an existing batch. ### Method POST ### Parameters #### Path Parameters - **batchId** (string) - Required - The unique identifier of the batch. #### Request Body - **recipient** (object) - Required - Recipient details (email or id). - **sourceAmount** (string) - Optional - Amount in source currency. - **targetAmount** (string) - Optional - Amount in target currency. - **targetCurrency** (string) - Optional - Currency code for target amount. - **memo** (string) - Optional - Payment description. ``` -------------------------------- ### Connect to Trolley API Source: https://github.com/trolley/javascript-sdk/blob/master/docs/README.md Use this function to create a client for the Trolley JavaScript API. Provide your public and private keys for authentication. ```typescript const client = trolley.connect({ key: "MY_PUBLIC_KEY", secret: "MY_PRIVATE_KEY", }); ``` -------------------------------- ### Fetch all account balances Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/balancesgateway.md Retrieves the account balance for all enabled bank accounts. ```javascript const balances = await client.balances.all(); ``` -------------------------------- ### Create a Payment Source: https://context7.com/trolley/javascript-sdk/llms.txt Creates a new payment within an existing batch. Supports both source amount and target currency configurations. ```typescript const payment = await client.payment.create("B-abc123", { recipient: { email: "contractor@example.com", }, sourceAmount: "150.00", memo: "Project milestone payment", }); console.log(payment.id); // "P-xyz789" console.log(payment.status); console.log(payment.sourceAmount); // Create payment with target amount in different currency const euroPayment = await client.payment.create("B-abc123", { recipient: { id: "R-abc123xyz", }, targetAmount: "100.00", targetCurrency: "EUR", memo: "Euro payment", }); ``` -------------------------------- ### Create a new payment Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/paymentgateway.md Use this method to create a new payment within a specified batch. Requires batch ID and payment details. ```javascript const payment = await client.payment.create('B-xx99bb', { recipient: { email: 'tom.jones@example.com', }, sourceAmount: '10.99', }); ``` -------------------------------- ### Batch Management API Source: https://context7.com/trolley/javascript-sdk/llms.txt APIs for managing payment batches. ```APIDOC ## POST /batch/create ### Description Creates a new payment batch, optionally with payments included. Batches group multiple payments for processing together. ### Method POST ### Endpoint /batch/create ### Parameters #### Request Body - **description** (string) - Optional - A description for the batch. - **sourceCurrency** (string) - Required - The currency for payments in the batch. - **payments** (array) - Optional - An array of payment objects to include in the batch. - **recipient** (object) - Required - Information about the recipient. - **email** (string) - Recipient's email address. - **id** (string) - Recipient's ID. - **sourceAmount** (string) - Required if targetAmount is not provided - The amount to send in the source currency. - **targetAmount** (string) - Required if sourceAmount is not provided - The amount to send in the target currency. - **targetCurrency** (string) - Required if targetAmount is provided - The target currency for the payment. - **memo** (string) - Optional - A memo for the payment. ### Request Example ```json { "description": "Weekly Contractor Payments", "sourceCurrency": "USD" } ``` ```json { "description": "Q4 Royalty Payments", "sourceCurrency": "USD" }, [ { "recipient": { "email": "john@example.com" }, "sourceAmount": "100.00", "memo": "October royalties" }, { "recipient": { "id": "R-abc123xyz" }, "targetAmount": "500.00", "targetCurrency": "EUR" } ] ``` ### Response #### Success Response (200) - **id** (string) - The ID of the created batch. - **status** (string) - The status of the batch (e.g., "open"). #### Response Example ```json { "id": "B-abc123", "status": "open" } ``` ``` ```APIDOC ## GET /batch/find ### Description Retrieves a specific batch by its ID. ### Method GET ### Endpoint /batch/find ### Parameters #### Path Parameters - **batchId** (string) - Required - The ID of the batch to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the batch. - **status** (string) - The status of the batch. - **description** (string) - The description of the batch. - **amount** (string) - The total amount of the batch. - **currency** (string) - The currency of the batch. - **totalPayments** (integer) - The number of payments in the batch. - **createdAt** (string) - The creation timestamp. - **updatedAt** (string) - The last updated timestamp. ### Response Example ```json { "id": "B-abc123", "status": "open", "description": "Weekly Contractor Payments", "amount": "1500.00", "currency": "USD", "totalPayments": 10, "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:05:00Z" } ``` ``` ```APIDOC ## GET /batch/all ### Description Retrieves all batches in the account. ### Method GET ### Endpoint /batch/all ### Response #### Success Response (200) - **id** (string) - The ID of the batch. - **description** (string) - The description of the batch. - **status** (string) - The status of the batch. - **totalPayments** (integer) - The number of payments in the batch. ### Response Example ```json [ { "id": "B-abc123", "description": "Weekly Contractor Payments", "status": "open", "totalPayments": 10 }, { "id": "B-def456", "description": "Q4 Royalty Payments", "status": "processing", "totalPayments": 5 } ] ``` ``` ```APIDOC ## GET /batch/search ### Description Searches for batches with pagination support. ### Method GET ### Endpoint /batch/search ### Parameters #### Query Parameters - **page** (integer) - Required - The page number to retrieve. - **pageSize** (integer) - Required - The number of results per page. - **query** (string) - Optional - A search query string. ### Response #### Success Response (200) - **meta** (object) - Metadata about the search results. - **records** (integer) - The total number of records found. - **batches** (array) - An array of batch objects. - **id** (string) - The ID of the batch. - **description** (string) - The description of the batch. - **status** (string) - The status of the batch. ### Response Example ```json { "meta": { "records": 2 }, "batches": [ { "id": "B-abc123", "description": "Weekly Contractor Payments", "status": "open" }, { "id": "B-def456", "description": "Q4 Royalty Payments", "status": "processing" } ] } ``` ``` ```APIDOC ## PUT /batch/update ### Description Updates a batch's metadata. Note: Cannot update payments via this method. ### Method PUT ### Endpoint /batch/update ### Parameters #### Path Parameters - **batchId** (string) - Required - The ID of the batch to update. #### Request Body - **description** (string) - Optional - The new description for the batch. ### Request Example ```json { "description": "Updated: Weekly Contractor Payments - Week 42" } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the batch was successfully updated, false otherwise. #### Response Example ```json true ``` ``` ```APIDOC ## DELETE /batch/remove ### Description Deletes a batch. Can delete single or multiple batches. ### Method DELETE ### Endpoint /batch/remove ### Parameters #### Path Parameters - **batchId** (string or array) - Required - The ID of the batch or an array of batch IDs to delete. ### Response #### Success Response (200) - **success** (boolean) - True if the batch(es) were successfully deleted, false otherwise. #### Response Example ```json true ``` ``` ```APIDOC ## POST /batch/generateQuote ### Description Generates a foreign exchange quote for the batch, locking in exchange rates. ### Method POST ### Endpoint /batch/generateQuote ### Parameters #### Path Parameters - **batchId** (string) - Required - The ID of the batch for which to generate a quote. ### Response #### Success Response (200) - **status** (string) - The updated status of the batch (e.g., "quoted"). - **quoteExpiredAt** (string) - The timestamp when the quote expires. #### Response Example ```json { "status": "quoted", "quoteExpiredAt": "2023-10-28T10:00:00Z" } ``` ``` ```APIDOC ## POST /batch/startProcessing ### Description Initiates the processing of a batch to send payments. ### Method POST ### Endpoint /batch/startProcessing ### Parameters #### Path Parameters - **batchId** (string) - Required - The ID of the batch to start processing. ### Response #### Success Response (200) - **status** (string) - The updated status of the batch (e.g., "processing"). #### Response Example ```json { "status": "processing" } ``` ``` -------------------------------- ### Class: Authentication Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/exceptions.authentication.md The Authentication class represents errors related to authentication processes within the SDK. It inherits from BaseException and includes standard error properties. ```APIDOC ## Class: Authentication ### Description Represents an authentication-related exception in the Trolley JavaScript SDK. Inherits from BaseException. ### Properties - **message** (string) - The error message associated with the authentication failure. - **name** (string) - The name of the error. - **stack** (string | undefined) - Optional stack trace information for debugging purposes. ``` -------------------------------- ### Create an Invoice Payment Source: https://context7.com/trolley/javascript-sdk/llms.txt Links a payment to an invoice or invoice line. ```typescript const invoicePayment = await client.invoicePayment.create({ batchId: "B-abc123", ids: [ { invoiceId: "INV-abc123", invoiceLineId: "LINE-001", paymentId: "P-xyz789", amount: { value: "5000.00", currency: "USD" }, }, ], }); console.log(invoicePayment.batchId); console.log(invoicePayment.paymentId); console.log(invoicePayment.invoicePayments); ``` -------------------------------- ### Class: Unexpected Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/exceptions.unexpected.md Details regarding the Unexpected exception class properties inherited from the standard Error object. ```APIDOC ## Class: Unexpected ### Description The Unexpected class represents an unforeseen error condition within the Trolley JavaScript SDK. It extends the BaseException class. ### Properties - **message** (string) - The error message associated with the exception. - **name** (string) - The name of the error. - **stack** (string | undefined) - Optional stack trace information for the error. ``` -------------------------------- ### POST /recipients Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientgateway.md Creates a new recipient in the system. ```APIDOC ## POST /recipients ### Description Create a given recipient. ### Parameters #### Request Body - **body** (RecipientInput) - Required - The recipient information to create ### Request Example { "type": "individual", "firstName": "Tom", "lastName": "Jones", "email": "tom.jones@example.com", "address": { "street1": "123 Main St", "country": "US" } } ### Response #### Success Response (200) - **recipient** (Recipient) - The created recipient object ``` -------------------------------- ### Search Batches Source: https://context7.com/trolley/javascript-sdk/llms.txt Searches for batches with pagination support. ```typescript const results = await client.batch.search(1, 10, "royalty"); console.log(`Found ${results.meta.records} batches`); results.forEach(batch => { console.log(`${batch.id}: ${batch.description} - ${batch.status}`); }); ``` -------------------------------- ### PaymentInput Interface Source: https://github.com/trolley/javascript-sdk/blob/master/docs/interfaces/paymentinput.md Details of the PaymentInput interface properties. ```APIDOC ## Interface: PaymentInput ### Description Represents the input for a payment transaction, including optional details like memo and recipient information, as well as amounts and currency. ### Properties #### memo *__Optional__* `string` An optional memo for the payment. #### recipient *__Required__* `object` Details of the payment recipient. ##### Type declaration - **email** (`string`, Optional): The email address of the recipient. - **id** (`string`, Optional): The unique identifier for the recipient. - **referenceId** (`string`, Optional): A reference ID associated with the recipient. #### sourceAmount *__Optional__* `string` The amount in the source currency. #### targetAmount *__Optional__* `string` The amount in the target currency. #### targetCurrency *__Optional__* `string` The target currency for the payment. ``` -------------------------------- ### Create an Invoice Source: https://context7.com/trolley/javascript-sdk/llms.txt Creates a new invoice with specified recipient and line items. ```typescript const invoice = await client.invoice.create({ recipientId: "R-abc123xyz", description: "Consulting Services - January 2024", externalId: "INV-2024-001", invoiceDate: "2024-01-01", dueDate: "2024-01-31", lines: [ { description: "Software Development", category: "services", unitAmount: { value: "5000.00", currency: "USD" }, taxReportable: true, forceUsTaxActivity: false, externalId: "LINE-001", tags: ["development"], }, { description: "Design Consultation", category: "services", unitAmount: { value: "1500.00", currency: "USD" }, taxReportable: true, forceUsTaxActivity: false, externalId: "LINE-002", tags: ["design"], }, ], }); console.log(invoice.id); console.log(invoice.invoiceNumber); console.log(invoice.status); console.log(invoice.totalAmount); console.log(invoice.dueAmount); ``` -------------------------------- ### Connect to Trolley API Source: https://context7.com/trolley/javascript-sdk/llms.txt Establishes a connection to the Trolley API using your access and secret keys. Supports setting a custom API base URL for testing or global configuration. ```typescript const trolley = require('trolleyhq'); // Create a client connection const client = trolley.connect({ key: "YOUR-ACCESS-KEY", secret: "YOUR-SECRET-KEY", }); // Optional: Set a custom API base URL for testing const testClient = trolley.connect({ key: "YOUR-ACCESS-KEY", secret: "YOUR-SECRET-KEY", apiBase: "https://api.sandbox.trolley.com", }); // Alternative: Set credentials globally const { Configuration } = require('trolleyhq'); Configuration.setApiKey("YOUR-ACCESS-KEY"); Configuration.setApiSecret("YOUR-SECRET-KEY"); const globalClient = Configuration.gateway(); ``` -------------------------------- ### Fetch account balance by type Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/balancesgateway.md Retrieves the account balance for a specific account type, such as 'paypal' or 'paymentrails'. ```javascript const balances = await client.balances.find("paymentrails"); ``` -------------------------------- ### Handle Specific API Errors Source: https://context7.com/trolley/javascript-sdk/llms.txt Demonstrates handling various Trolley SDK errors, including Not Found, Authentication, Authorization, Malformed requests, Server errors, Maintenance, and Unexpected errors. Logs specific messages and validation details when available. ```typescript const { Errors } = require('trolleyhq/lib/errors'); async function handlePayment() { try { const recipient = await client.recipient.find("R-invalid-id"); } catch (error) { if (error instanceof Errors.NotFoundError) { console.log("Recipient not found"); console.log(error.validationErrors); } else if (error instanceof Errors.AuthenticationError) { console.log("Invalid API credentials"); } else if (error instanceof Errors.AuthorizationError) { console.log("Insufficient permissions"); } else if (error instanceof Errors.MalformedError) { console.log("Invalid request data"); error.validationErrors?.forEach(err => { console.log(`Field: ${err.field}, Code: ${err.code}, Message: ${err.message}`); }); } else if (error instanceof Errors.ServerError) { console.log("Server error occurred"); } else if (error instanceof Errors.DownForMaintenanceError) { console.log("API is down for maintenance"); } else if (error instanceof Errors.UnexpectedError) { console.log(`Unexpected error: ${error.message}`); } } } ``` -------------------------------- ### Create a new recipient account Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientaccountgateway.md Creates a new account for a recipient using the provided account details object. ```javascript const account = await client.recipientAccount.create('R-1234', { type: "bank-transfer", primary: true, country: "CA", currency: "CAD", accountNum: "012345678", bankId: "004", branchId: "47261", accountHolderName: "John Smith", }); ``` -------------------------------- ### Create a Recipient Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientgateway.md Creates a new recipient using the provided recipient information object. ```javascript const recipient = await client.recipient.create({ type: "individual", firstName: "Tom", lastName: "Jones", email: "tom.jones@example.com", address: { street1: "123 Main St", country: "US", } }); ``` -------------------------------- ### Create Invoice Lines Source: https://context7.com/trolley/javascript-sdk/llms.txt Adds new line items to an existing invoice. ```typescript const lines = await client.invoiceLine.create("INV-abc123", [ { description: "Additional Consulting Hours", category: "services", unitAmount: { value: "750.00", currency: "USD" }, taxReportable: true, forceUsTaxActivity: false, externalId: "LINE-003", tags: ["consulting"], }, ]); lines.forEach(line => { console.log(`Created line ${line.id}: ${line.description}`); console.log(`Amount: ${line.unitAmount.value} ${line.unitAmount.currency}`); }); ``` -------------------------------- ### NotFound Exception Class Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/exceptions.notfound.md Details about the NotFound exception class, including its properties and inheritance hierarchy. ```APIDOC ## Class: NotFound ### Hierarchy ↳ [BaseException](exceptions.baseexception.md) **↳ NotFound** ### Properties * [message](exceptions.notfound.md#message) * [name](exceptions.notfound.md#name) * [stack](exceptions.notfound.md#stack) --- ## Properties ### `` message **● message**: *`string`* *Inherited from Error.message* *Defined in /Users/koblas/repos/paymentrails/javascript-sdk/node_modules/typedoc/node_modules/typescript/lib/lib.es5.d.ts:886* --- ### `` name **● name**: *`string`* *Inherited from Error.name* *Defined in /Users/koblas/repos/paymentrails/javascript-sdk/node_modules/typedoc/node_modules/typescript/lib/lib.es5.d.ts:885* --- ### `` `` stack **● stack**: *`undefined` | `string`* *Inherited from Error.stack* *Overrides Error.stack* *Defined in /Users/koblas/repos/paymentrails/javascript-sdk/node_modules/typedoc/node_modules/typescript/lib/lib.es5.d.ts:887* --- ``` -------------------------------- ### Authorization Exception Class Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/exceptions.authorization.md Details about the Authorization exception class, including its properties and inheritance hierarchy. ```APIDOC ## Class: Authorization ### Description Represents an authorization-related exception within the Trolley JavaScript SDK. ### Hierarchy ↳ [BaseException](exceptions.baseexception.md) **↳ Authorization** ### Properties * **message** (string) - Inherited from Error.message. The error message. * **name** (string) - Inherited from Error.name. The name of the error, typically 'Authorization'. * **stack** (string | undefined) - Inherited from Error.stack. The stack trace of the error. ``` -------------------------------- ### BatchInput Interface Source: https://github.com/trolley/javascript-sdk/blob/master/docs/interfaces/batchinput.md The BatchInput interface defines the structure for batch inputs in the Trolley JavaScript SDK. ```APIDOC ## Interface: BatchInput ### Description Represents the structure for batch inputs, including optional description and source currency. ### Properties * **description** (string) - Optional - A description for the batch. * **sourceCurrency** (string) - Optional - The currency code for the source of the batch. ``` -------------------------------- ### POST /offlinePayment/create Source: https://context7.com/trolley/javascript-sdk/llms.txt Records an offline payment made outside of Trolley. ```APIDOC ## POST /offlinePayment/create ### Description Records an offline payment made outside of Trolley for tax reporting purposes. ### Method POST ### Parameters #### Path Parameters - **recipientId** (string) - Required - The unique identifier of the recipient. #### Request Body - **amount** (string) - Required - Payment amount. - **currency** (string) - Required - Currency code. - **taxReportable** (boolean) - Optional - Whether the payment is tax reportable. - **memo** (string) - Optional - Payment description. ``` -------------------------------- ### Generate FX Quote Source: https://context7.com/trolley/javascript-sdk/llms.txt Generates a foreign exchange quote for a batch to lock in exchange rates. ```typescript const quotedBatch = await client.batch.generateQuote("B-abc123"); console.log(quotedBatch.status); // "quoted" console.log(quotedBatch.quoteExpiredAt); // Quote expiration timestamp ``` -------------------------------- ### BaseException Class Reference Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/exceptions.baseexception.md Overview of the BaseException class properties inherited from the standard Error object. ```APIDOC ## Class: BaseException ### Description The BaseException class is the base error class for the Trolley JavaScript SDK. It inherits from the standard JavaScript Error class and is extended by specific error types such as DownForMaintenance, ServerError, Unexpected, NotFound, Authentication, Authorization, and Malformed. ### Properties - **message** (string) - The error message describing the issue. - **name** (string) - The name of the error. - **stack** (string | undefined) - Optional stack trace information for debugging purposes. ``` -------------------------------- ### Fetch all recipient accounts Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientaccountgateway.md Retrieves a list of all accounts for a specified recipient ID. Throws a NotFound error if the recipient does not exist. ```javascript const accounts = await client.recipientAccount.all('R-1234'); ``` -------------------------------- ### Create an Offline Payment Source: https://context7.com/trolley/javascript-sdk/llms.txt Records an offline payment made outside of Trolley for tax reporting purposes. ```typescript const offlinePayment = await client.offlinePayment.create("R-abc123xyz", { amount: "1000.00", currency: "USD", taxReportable: true, withholdingAmount: "240.00", withholdingCurrency: "USD", memo: "Cash payment for services", category: "services", processedAt: "2024-01-15", externalId: "EXT-12345", tags: ["consulting", "Q1-2024"], }); console.log(offlinePayment.id); // "OP-abc789" console.log(offlinePayment.amount); console.log(offlinePayment.taxReportable); ``` -------------------------------- ### POST /recipients/{recipientId}/accounts Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/recipientaccountgateway.md Create a new recipient account. ```APIDOC ## POST /recipients/{recipientId}/accounts ### Description Create a new recipient account. ### Parameters #### Path Parameters - **recipientId** (string) - Required - The Trolley recipient ID (e.g. R-xyzzy) #### Request Body - **body** (any) - Required - Account information ### Request Example ```javascript const account = await client.recipientAccount.create('R-1234', { type: "bank-transfer", primary: true, country: "CA", currency: "CAD", accountNum: "012345678", bankId: "004", branchId: "47261", accountHolderName: "John Smith", }); ``` ``` -------------------------------- ### Payment Gateway API Source: https://github.com/trolley/javascript-sdk/blob/master/docs/classes/paymentgateway.md This section details the various methods available in the Payment Gateway class for managing payments. ```APIDOC ## POST /payments ### Description Create a new payment in a batch. ### Method POST ### Endpoint /payments ### Parameters #### Path Parameters - **batchId** (string) - Required - Trolley payment id (e.g. "B-xx999bb") #### Request Body - **body** (any) - Required - Payment information ### Request Example ```json { "recipient": { "email": "tom.jones@example.com" }, "sourceAmount": "10.99" } ``` ### Response #### Success Response (200) - **Payment** (object) - Details of the created payment #### Response Example ```json { "id": "P-aabbccc", "batchId": "B-xx99bb", "recipient": { "email": "tom.jones@example.com" }, "sourceAmount": "10.99" } ``` ``` ```APIDOC ## GET /payments/{paymentId} ### Description Find a specific payment. ### Method GET ### Endpoint /payments/{paymentId} ### Parameters #### Path Parameters - **paymentId** (string) - Required - Trolley payment id (e.g. "P-aabccc") ### Response #### Success Response (200) - **Payment** (object) - Details of the found payment #### Response Example ```json { "id": "P-aabbccc", "batchId": "B-xx99bb", "recipient": { "email": "tom.jones@example.com" }, "sourceAmount": "10.99" } ``` ``` ```APIDOC ## DELETE /payments/{paymentId}/{batchId} ### Description Delete a given payment. Note: you can only delete non-processed payments. ### Method DELETE ### Endpoint /payments/{paymentId}/{batchId} ### Parameters #### Path Parameters - **paymentId** (string) - Required - Trolley payment id (e.g. "P-aabccc") - **batchId** (string) - Required - Trolley payment id (e.g. "B-xx999bb") ### Response #### Success Response (200) - **boolean** - True if the payment was successfully deleted, false otherwise. #### Response Example ```json true ``` ``` ```APIDOC ## GET /batches/{batchId}/payments ### Description Search for payments in a given batch. ### Method GET ### Endpoint /batches/{batchId}/payments ### Parameters #### Path Parameters - **batchId** (string) - Required - Trolley payment id (e.g. "B-xx999bb") #### Query Parameters - **page** (number) - Optional - Page number (1 based). Default: 1 - **pageSize** (number) - Optional - Page size (0...1000). Default: 10 - **term** (string) - Optional - Any search terms to look for. Default: "" ### Response #### Success Response (200) - **Payment[]** (array) - An array of payment objects matching the search criteria. #### Response Example ```json [ { "id": "P-aabbccc", "batchId": "B-xx99bb", "recipient": { "email": "tom.jones@example.com" }, "sourceAmount": "10.99" } ] ``` ``` ```APIDOC ## PUT /payments/{paymentId}/{batchId} ### Description Update a given payment. ### Method PUT ### Endpoint /payments/{paymentId}/{batchId} ### Parameters #### Path Parameters - **paymentId** (string) - Required - Trolley payment id (e.g. "P-aabccc") - **batchId** (string) - Required - Trolley payment id (e.g. "B-xx999bb") #### Request Body - **body** (any) - Required - Payment update information ### Request Example ```json { "sourceAmount": "99.99" } ``` ### Response #### Success Response (200) - **boolean** - True if the payment was successfully updated, false otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### List Batch Payments Source: https://context7.com/trolley/javascript-sdk/llms.txt Retrieves a paginated list of payments within a specific batch. ```typescript const payments = await client.batch.paymentList("B-abc123", 1, 25); payments.forEach(payment => { console.log(`Payment ${payment.id}: ${payment.sourceAmount} to ${payment.recipient.email}`); console.log(`Status: ${payment.status}`); }); ```