### Basic GET Request Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Demonstrates a basic GET request to retrieve a list of customers. ```javascript const response = await dwolla.get("/customers"); console.log("Total customers:", response.body.total); ``` -------------------------------- ### Initialize Dwolla Client with TypeScript Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Demonstrates how to initialize the Dwolla client using TypeScript and make a GET request to fetch customers. Ensure you have the necessary dependencies installed. ```typescript import { Client } from "dwolla-v2"; const dwolla = new Client({ key: "...", secret: "...", environment: "sandbox" }); const response = await dwolla.get("/customers"); console.log(response.status); console.log(response.body); ``` -------------------------------- ### Perform a GET Request Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Example of making a GET request to retrieve a list of customers with pagination parameters. ```javascript // GET https://api.dwolla.com/customers?offset=20&limit=10 const response = await dwolla.get("customers", { offset: 20, limit: 10 }); console.log("Response Total: ", response.body.total); ``` -------------------------------- ### Example of Creating a Token with Options Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md This example shows how to instantiate a `Token` object using the `TokenOptions` interface. It provides values for access token, refresh token, expiration, scope, and account ID. ```javascript const token = client.token({ access_token: "aB3cd4EF5GhijKlMnOpQrStuvWxYz1234567890", refresh_token: "refresh_token_value", expires_in: 3600, scope: "funding|transfers", account_id: "account-id-value" }); ``` -------------------------------- ### Initialize Dwolla Client Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Example of initializing the Dwolla client with sandbox environment and a grant callback to save tokens. ```javascript const client = new Client({ key: process.env.DWOLLA_KEY, secret: process.env.DWOLLA_SECRET, environment: "sandbox", onGrant: async (token) => { // Save token to database await db.tokens.save(token); } }); ``` -------------------------------- ### Install Dwolla SDK using npm, yarn, or pnpm Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Install the Dwolla SDK package using your preferred Node.js package manager. ```shell # npm $ npm install --save dwolla-v2 # yarn $ yarn add dwolla-v2 # pnpm $ pnpm add dwolla-v2 ``` -------------------------------- ### Basic Production Client Setup Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Instantiate the Dwolla client for production use. Ensure DWOLLA_APP_KEY and DWOLLA_APP_SECRET environment variables are set. ```javascript const Client = require("dwolla-v2").Client; const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET, environment: "production" }); module.exports = dwolla; ``` -------------------------------- ### Query Parameter Handling Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Illustrates how null, undefined, and array values are handled when constructing query parameters for a GET request. Null and undefined values are omitted. ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 0, search: undefined, // Omitted verified: null // Omitted }); // Results in: GET /customers?limit=25&offset=0 ``` -------------------------------- ### Example of Handling an API Response Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md This example demonstrates how to process a successful API response from `dwolla.get()`. It checks the status code and logs customer data from the response body. ```javascript const response = await dwolla.get("/customers"); if (response.status === 200) { console.log("Total:", response.body.total); console.log("Customers:", response.body._embedded.customers); } ``` -------------------------------- ### Token GET Request Path Variations Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md Demonstrates equivalent ways to specify paths for GET requests using the Token instance. Supports relative paths, full URLs, HAL resource objects, and partial URLs. ```javascript await token.get("/customers"); await token.get("customers"); await token.get("https://api-sandbox.dwolla.com/customers"); ``` ```javascript const customer = { _links: { self: { href: "/customers/123" } } }; await token.get(customer); ``` -------------------------------- ### GET Request with Full URL Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Shows how to perform a GET request using a complete URL instead of just an API path. ```javascript const response = await dwolla.get("https://api-sandbox.dwolla.com/customers"); ``` -------------------------------- ### GET Request with Custom Headers Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Illustrates how to add custom HTTP headers to a GET request. ```javascript const response = await dwolla.get("/customers", {}, { "X-Request-ID": "req-123", "X-Custom-Header": "value" }); ``` -------------------------------- ### Perform GET Request with Token Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md Use the `get` method to perform an authenticated GET request. It accepts a path, optional query parameters, and optional headers. ```javascript token.get(path, query, headers) ``` ```javascript try { const response = await token.get("/customers", { limit: 25 }); console.log("Customers:", response.body); } catch (error) { console.error("Status:", error.status, "Error:", error.body); } ``` -------------------------------- ### get() Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md Performs a GET request using this token for authentication. It accepts a path, optional query parameters, and optional headers. ```APIDOC ## GET ### Description Performs a GET request using this token for authentication. ### Method GET ### Endpoint [path] ### Parameters #### Path Parameters - **path** (string | object) - Required - API path, full URL, or HAL resource object with `_links.self.href` - **query** (object) - Optional - Query parameters object - **headers** (object) - Optional - Additional HTTP headers ### Request Example ```javascript try { const response = await token.get("/customers", { limit: 25 }); console.log("Customers:", response.body); } catch (error) { console.error("Status:", error.status, "Error:", error.body); } ``` ### Response #### Success Response (200) - **status** (number) - The HTTP status code of the response. - **headers** (object) - The HTTP headers of the response. - **body** (object) - The response body. #### Response Example ```json { "status": 200, "headers": { ... }, "body": { ... } } ``` ### Error Handling - `Error` with `.status`, `.headers`, `.body` properties if status >= 400 ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Shows how to include query parameters for filtering or pagination in a GET request. ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 50, search: "jane" }); ``` -------------------------------- ### Create Dwolla Auth Instance Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Example of creating an authentication instance with specified redirect URI, scopes, and verified account requirement. ```javascript const auth = client.auth({ redirect_uri: "https://myapp.com/oauth-callback", scope: "funding|transfers", state: "random-csrf-token-1234567890", verified_account: true }); ``` -------------------------------- ### Example Usage of Query Parameters Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Demonstrates how to use the QueryParams type with the `dwolla.get()` method. Null values are omitted from the query string. ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 0, search: "jane", verified: true, archived: null // Omitted }); // Results in: ?limit=25&offset=0&search=jane&verified=true ``` -------------------------------- ### Initialize Dwolla Client and Make API Request Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Initializes the Dwolla client with credentials and environment, then makes an authenticated GET request to retrieve customers. Ensure DWOLLA_APP_KEY and DWOLLA_APP_SECRET environment variables are set. ```javascript const Client = require("dwolla-v2").Client; const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET, environment: "sandbox" }); // Make authenticated API requests const response = await dwolla.get("/customers", { limit: 25 }); console.log(response.body); ``` -------------------------------- ### Perform a POST Request to Create a Customer Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Example of making a POST request to create a new customer. This request is not idempotent as it lacks an `Idempotency-Key` header. ```javascript // POST https://api.dwolla.com/customers body={ ... } // This request is not idempotent since `Idempotecy-Key` is not passed as a header const response = await dwolla.post("customers", { firstName: "Jane", lastName: "Doe", email: "jane.doe@example.com" }); console.log("Created Resource: ", response.headers.get("Location")); ``` -------------------------------- ### Accessing Response Data Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md Example of making a GET request and accessing the status, headers, and specific properties of the response body. ```javascript const response = await dwolla.get("/customers"); console.log(response.status); // 200 console.log(response.headers); // Headers { ... } console.log(response.body.total); // 100 console.log(response.body._embedded.customers); // [...] ``` -------------------------------- ### Make Request with Custom Headers Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Example of including custom headers, such as 'X-Custom-Header', along with an 'Idempotency-Key' in a request. ```javascript // With custom headers await token.get("/customers", {}, { "X-Custom-Header": "value", "Idempotency-Key": "..." }); ``` -------------------------------- ### Client.get() Signature Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Signature for performing a GET request using the Client instance. ```javascript client.get(path, query, headers) ``` -------------------------------- ### Token GET Request with Query Parameters Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md Shows how to include query parameters in GET requests. Empty values are omitted, and array indices/brackets are handled by default. ```javascript await token.get("/customers", { limit: 25, offset: 50, search: null // omitted from query }); // Results in: GET /customers?limit=25&offset=50 ``` -------------------------------- ### GET Request Using HAL Resource Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Demonstrates using a HAL resource object directly as the path for a GET request, typically for fetching details of a specific resource. ```javascript const customer = response.body._embedded.customers[0]; const details = await dwolla.get(customer); // Uses customer._links.self.href ``` -------------------------------- ### Performing GET Requests Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/INDEX.md Use the `get` method for retrieving data from an API endpoint. It accepts the path, optional query parameters, and headers. ```javascript const response = await client.get(path, query, headers); ``` -------------------------------- ### Perform a POST Request to Upload a Document Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Example of making a POST request to upload a document for a customer using multipart/form-data. Requires the `form-data` package. ```javascript // POST https://api.dwolla.com/{id}/documents multipart/form-data ... // Note: Requires form-data peer dependency to be downloaded and installed const formData = new FormData(); formData.append("documentType", "license"); formData.append("file", ffs.createReadStream("mclovin.jpg"), { contentType: "image/jpeg", filename: "mclovin.jpg", knownLength: fs.statSync("mclovin.jpg").size }); const response = await dwolla.post(`${customerUrl}/documents`, formData); console.log("Created Resource: ", response.headers.get("Location")); ``` -------------------------------- ### Multi-Environment Client Setup Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Set up multiple Dwolla client configurations for different environments (development and production) based on the NODE_ENV variable. Defaults to development if NODE_ENV is not set. ```javascript const Client = require("dwolla-v2").Client; const ENV = process.env.NODE_ENV || "development"; const clients = { development: new Client({ key: process.env.DWOLLA_DEV_KEY, secret: process.env.DWOLLA_DEV_SECRET, environment: "sandbox" }), production: new Client({ key: process.env.DWOLLA_PROD_KEY, secret: process.env.DWOLLA_PROD_SECRET, environment: "production" }) }; module.exports = clients[ENV]; ``` -------------------------------- ### Token.get() Signature Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Signature for performing a GET request using the Token instance. ```javascript token.get(path, query, headers) ``` -------------------------------- ### Docker Environment Setup for Dwolla Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Configure Dwolla environment variables within a Dockerfile for production deployment. Credentials should be passed at runtime. ```dockerfile FROM node:16 WORKDIR /app COPY . . RUN npm install ENV DWOLLA_ENVIRONMENT=production # DWOLLA_APP_KEY and DWOLLA_APP_SECRET passed at runtime CMD ["node", "app.js"] ``` -------------------------------- ### Handling POST Request Success (201 Created) Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md Example demonstrates checking for a 201 status code after a POST request and retrieving the resource URL from the 'Location' header. ```javascript const response = await dwolla.post("/customers", customerData); if (response.status === 201) { const resourceUrl = response.headers.get("Location"); console.log("Created at:", resourceUrl); } else if (response.status === 200) { // Less common for POST } ``` -------------------------------- ### Perform a DELETE Request Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Example of making a DELETE request to remove a resource. ```javascript // DELETE https://api.dwolla.com/[resource] await dwolla.delete("resource"); ``` -------------------------------- ### Token Manager onGrant Callback Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/TokenManager.md Demonstrates how to use the `onGrant` callback in the Client options to persist newly obtained tokens. This callback is invoked whenever TokenManager acquires a fresh token. ```javascript const client = new Client({ key: "...", secret: "...", onGrant: async (token) => { // Called whenever TokenManager gets a new token // Useful for persisting tokens await db.tokens.save({ accessToken: token.access_token, refreshToken: token.refresh_token, expiresIn: token.expires_in, obtainedAt: Date.now() }); } }); ``` -------------------------------- ### Retrieve Dwolla Customer Funding Sources Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use the generic `get` method to retrieve all funding sources associated with a customer. ```javascript await dwolla.get(`/customers/${id}/funding-sources`); ``` -------------------------------- ### Complete OAuth Authorization Flow Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Auth.md Demonstrates the complete OAuth 2.0 authorization code flow using the Dwolla v2 Node.js client. This includes generating the authorization URL, redirecting the user, and handling the callback to exchange the code for a token. ```javascript const express = require("express"); const Client = require("dwolla-v2").Client; const crypto = require("crypto"); const app = express(); const dwolla = new Client({ key: process.env.DWOLLA_KEY, secret: process.env.DWOLLA_SECRET, environment: "sandbox" }); // Step 1: User initiates OAuth app.get("/login", (req, res) => { const state = crypto.randomBytes(16).toString("hex"); // Store state in session for verification req.session.oauthState = state; const auth = dwolla.auth({ redirectUri: "https://myapp.com/oauth-callback", scope: "funding|transfers", state: state }); res.redirect(auth.url); }); // Step 2: Handle Dwolla callback app.get("/oauth-callback", async (req, res) => { const auth = dwolla.auth({ redirectUri: "https://myapp.com/oauth-callback", state: req.session.oauthState }); try { const token = await auth.callback({ state: req.query.state, code: req.query.code }); // Store token with user req.session.token = token; res.redirect("/dashboard"); } catch (error) { res.status(400).send("Authorization failed"); } }); ``` -------------------------------- ### Delete a Resource Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Example of deleting a resource by providing its path. This can result in a 200 OK or 204 No Content status. ```javascript const response = await dwolla.delete("/funding-sources/source-id"); console.log("Deleted successfully"); // status 200 or 204 ``` -------------------------------- ### Token Methods (GET, POST, PUT, DELETE) Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md Methods on the Token instance allow for direct API calls. These methods handle path resolution, query parameters, and include necessary authentication headers. ```APIDOC ## Token Methods ### Description Methods such as `get`, `post`, `put`, and `delete` on a `Token` instance are used to interact with the Dwolla API. These methods abstract away the complexities of authentication, path construction, and query parameter formatting. ### Method GET, POST, PUT, DELETE (supported by the underlying SDK implementation) ### Endpoint Supports relative paths, full URLs, HAL resource links, and partial URLs. ### Parameters #### Path Parameters Not explicitly defined, as paths can be relative, full, or derived from HAL resources. #### Query Parameters - **(any)** (any) - Optional - Query parameters are passed as an object. Empty values (null, undefined) are omitted. Array indices and brackets are removed. #### Request Body - **(any)** (any) - Optional - For POST and PUT requests, a request body can be provided as an object. ### Request Example ```javascript // Example using GET with query parameters await token.get("/customers", { limit: 25, offset: 50, search: null // omitted from query }); // Results in: GET /customers?limit=25&offset=50 // Example using a HAL resource object for path const customer = { _links: { self: { href: "/customers/123" } } }; await token.get(customer); // Results in: GET /customers/123 ``` ### Response #### Success Response (200) - **(any)** (object) - The API response, typically in HAL JSON format. #### Response Example ```json { "_embedded": { "customers": [ { "id": "/customers/123", "first_name": "Jane", "last_name": "Doe", "_links": { "self": { "href": "https://api-sandbox.dwolla.com/customers/123" } } } ] }, "_links": { "self": { "href": "https://api-sandbox.dwolla.com/customers?limit=25&offset=50" }, "next": { "href": "https://api-sandbox.dwolla.com/customers?limit=25&offset=75" } } } ``` ``` -------------------------------- ### Handle OAuth Callback Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Example of how to process parameters from an OAuth redirect in your callback handler. Ensure the state parameter matches the original request. ```javascript // In OAuth callback handler const token = await auth.callback({ state: req.query.state, code: req.query.code }); ``` -------------------------------- ### Perform an Idempotent POST Request Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Example of making an idempotent POST request by including an `Idempotency-Key` header. This ensures the operation is only performed once. ```javascript // POST https://api.dwolla.com/customers body={ ... } headers={ ..., Idempotency-Key=... } // This request is idempotent since `Idempotency-Key` is passed as a header const response = await dwolla.post("customers", { firstName: "Jane", lastName: "Doe", email: "jane.doe@example.com" }, { "Idempotency-Key": "[RANDOMLY_GENERATED_KEY_HERE]" }); ``` -------------------------------- ### TokenManager Internal State Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/TokenManager.md Illustrates the internal state object (`_state`) of the TokenManager, showing properties like `instance`, `expiresIn`, and `updatedAt`. This is for understanding the manager's internal workings. ```javascript const client = new Client({ key: "...", secret: "..." }); // The underlying TokenManager._state looks like: { instance: Promise, expiresIn: 3600, updatedAt: 1719613200 } // When token is stale, state.instance is set to null and refreshed ``` -------------------------------- ### Token API File Upload with FormData Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md Provides an example of uploading a file using FormData with the Token API, including setting file details and known length. ```javascript const FormData = require("form-data"); const fs = require("fs"); const formData = new FormData(); formData.append("documentType", "license"); formData.append("file", fs.createReadStream("license.jpg"), { filename: "license.jpg", contentType: "image/jpeg", knownLength: fs.statSync("license.jpg").size }); const response = await token.post( `/customers/customer-id/documents`, formData ); ``` -------------------------------- ### Dwolla OAuth Authorization Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Generate an OAuth authorization URL with specific scopes and security parameters. A random state is generated for CSRF protection. ```javascript const auth = client.auth({ redirectUri: "https://myapp.example.com/oauth-callback", scope: "funding|transfers|balance", state: crypto.randomBytes(16).toString("hex"), verifiedAccount: true }); console.log("Redirect user to:", auth.url); ``` -------------------------------- ### FormData and File Uploads Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Token.md This section explains how to handle FormData and file uploads using the Token object, including automatic header management and an example of uploading a document. ```APIDOC ## FormData and File Uploads When passing FormData as the body, the Token automatically: 1. Uses the FormData's `getHeaders()` method for proper content-type 2. Sets multipart boundary headers 3. Encodes the form data correctly **File upload example:** ```javascript const FormData = require("form-data"); const fs = require("fs"); const formData = new FormData(); formData.append("documentType", "license"); formData.append("file", fs.createReadStream("license.jpg"), { filename: "license.jpg", contentType: "image/jpeg", knownLength: fs.statSync("license.jpg").size }); const response = await token.post( `/customers/customer-id/documents`, formData ); ``` ``` -------------------------------- ### Full Dwolla Client Configuration Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/INDEX.md Initialize the client with all available options, including environment and a token grant callback. ```javascript new Client({ key: "app-key", secret: "app-secret", environment: "sandbox", onGrant: async (token) => { // Token granted callback } }); ``` -------------------------------- ### Perform GET Request Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Client.md Use the `get()` method to perform a GET request to the Dwolla API. It accepts a path, optional query parameters, and optional headers. The method returns a Promise that resolves to a Response object. ```javascript client.get(path, query, headers) ``` ```javascript try { const response = await dwolla.get("customers", { offset: 20, limit: 10 }); console.log("Total customers:", response.body.total); } catch (error) { console.error("Request failed with status", error.status); } ``` -------------------------------- ### Dwolla Client Initialization with Key Alias Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Demonstrates initializing the Dwolla client using the 'id' alias for the application key, which functions identically to 'key'. ```javascript const dwolla = new Client({ key: "jXz1234567890abcDefGhiJkLmNoPqRsTu", secret: "..." }); // Equivalent const dwolla = new Client({ id: "jXz1234567890abcDefGhiJkLmNoPqRsTu", secret: "..." }); ``` -------------------------------- ### Initialize Auth Instance Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Auth.md Create an Auth instance for initiating OAuth authorization. This is typically done via `client.auth(options)`. ```javascript const Client = require("dwolla-v2").Client; const client = new Client({ key: "...", secret: "..." }); const auth = client.auth({ redirectUri: "https://myapp.com/oauth-callback", scope: "funding|transfers", state: crypto.randomBytes(16).toString("hex"), verifiedAccount: true }); ``` -------------------------------- ### Initialize Dwolla Client with Environment, Key, and Secret Source: https://github.com/dwolla/dwolla-v2-node/blob/main/README.md Initialize the Dwolla client by providing the environment ('sandbox' or 'production') and your application's key and secret. Ensure your DWOLLA_APP_KEY and DWOLLA_APP_SECRET environment variables are set. ```javascript const Client = require("dwolla-v2").Client; const dwolla = new Client({ environment: "sandbox", // Defaults to "production" key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET }) ``` -------------------------------- ### Minimal Dwolla Client Configuration Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/INDEX.md Use this snippet for basic client initialization with only the required application key and secret. ```javascript new Client({ key: "app-key", secret: "app-secret" }); ``` -------------------------------- ### Equivalent Path Formats for HTTP Methods Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Illustrates the flexible path resolution for HTTP methods, showing equivalent ways to specify resource paths. ```javascript // All these are equivalent: await dwolla.get("/customers"); await dwolla.get("customers"); await dwolla.get("https://api-sandbox.dwolla.com/customers"); // Using HAL resource const customer = { _links: { self: { href: "/customers/123" } } }; await dwolla.get(customer); ``` -------------------------------- ### GET Request Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Performs a GET request to the Dwolla API using either a Client or Token instance. Supports path, query parameters, and custom headers. ```APIDOC ## GET Request Performs a GET request to the Dwolla API. ### Client.get() ```javascript client.get(path, query, headers) ``` ### Token.get() ```javascript token.get(path, query, headers) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | path | string \| object | Yes | — | API path, full URL, or HAL resource object | | query | object | No | undefined | Query parameters | | headers | object | No | undefined | Additional HTTP headers | ### Return Value **Returns:** `Promise` ```javascript { status: number, headers: Headers, body: any } ``` ### Throws **Promise rejection** with status >= 400 containing: - `error.status` — HTTP status code - `error.headers` — Response headers - `error.body` — Error response body - `error.message` — Original response text ### Examples **Basic GET request:** ```javascript const response = await dwolla.get("/customers"); console.log("Total customers:", response.body.total); ``` **GET with query parameters:** ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 50, search: "jane" }); ``` **GET with custom headers:** ```javascript const response = await dwolla.get("/customers", {}, { "X-Request-ID": "req-123", "X-Custom-Header": "value" }); ``` **GET using HAL resource:** ```javascript const customer = response.body._embedded.customers[0]; const details = await dwolla.get(customer); // Uses customer._links.self.href ``` **GET with full URL:** ```javascript const response = await dwolla.get("https://api-sandbox.dwolla.com/customers"); ``` ### Query Parameter Handling Query parameters are URL-encoded with special handling: - **Null/undefined values** — Omitted from query string - **Array indices** — Removed (`skipIndex: true`) - **Brackets** — Removed (`skipBracket: true`) ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 0, search: undefined, // Omitted verified: null // Omitted }); // Results in: GET /customers?limit=25&offset=0 ``` ### Headers Included Automatically - `Authorization: Bearer {access_token}` - `Accept: application/vnd.dwolla.v1.hal+json` - `User-Agent: dwolla-v2-node/VERSION` Additional headers are merged with these defaults. ``` -------------------------------- ### Initialize Dwolla Client for Sandbox Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Instantiate the Dwolla client for the sandbox environment using your application key and secret from environment variables. ```javascript const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET, environment: "sandbox" }); ``` -------------------------------- ### Get Current Token Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/TokenManager.md Gets the current token, refreshing it if necessary. This is the primary method used by the Client to ensure a fresh token is available for API requests. It transparently handles token caching and refreshing. ```javascript tokenManager.getToken() ``` ```javascript const client = new Client({ key: "...", secret: "..." }); // Internally, client.get() calls: // tokenManager.getToken().then(token => token.get(...)) const response = await client.get("/customers"); // TokenManager transparently: // 1. Checks if cached token is fresh // 2. If not, requests new token via client.auth.client() // 3. Returns the token // 4. Client uses token to make the request ``` -------------------------------- ### Resource Traversal with HAL Links Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md Demonstrates traversing the API by using HAL links to fetch related data like transfers and funding sources for each customer. ```javascript // Pattern: Use HAL links to navigate the API const customersResponse = await dwolla.get("/customers"); const customers = customersResponse.body._embedded.customers; for (const customer of customers) { // Use _links to get related data const transfersUrl = customer._links.transfers.href; const transfersResponse = await dwolla.get(transfersUrl); const fundingSourcesUrl = customer._links["funding-sources"].href; const fundingResponse = await dwolla.get(fundingSourcesUrl); } ``` -------------------------------- ### Initialize Dwolla Client Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/INDEX.md Instantiate the Dwolla client with your API key and secret. This is the main entry point for interacting with the Dwolla API. ```javascript const { Client } = require("dwolla-v2"); const client = new Client({ key: "...", secret: "..." }); ``` -------------------------------- ### Retrieve Dwolla Customers Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use the generic `get` method to retrieve a list of customers. ```javascript await dwolla.get("/customers"); ``` -------------------------------- ### Pagination with Offset/Limit Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md Demonstrates how to paginate through list endpoints using the `limit` and `offset` parameters, and how to use the `_links.next` URL for subsequent pages. ```APIDOC ## Pagination with Offset/Limit List endpoints support pagination with offset/limit parameters. ### Description This example shows how to fetch paginated results for a list endpoint, like `/customers`, by specifying `limit` and `offset` in the request parameters. It also illustrates how to retrieve the next page of results either by calculating the next offset or by using the `_links.next.href` provided in the response. ### Method `GET` ### Endpoint `/customers` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of records to return per page. - **offset** (integer) - Optional - The number of records to skip before starting to collect the result set. ### Request Example ```javascript // Get first page const page1 = await dwolla.get("/customers", { limit: 25, offset: 0 }); // Get next page const page2 = await dwolla.get("/customers", { limit: 25, offset: 25 }); // Or use the _links.next URL if (page1.body._links.next) { const page2 = await dwolla.get(page1.body._links.next.href); } ``` ### Response #### Success Response (200) - **body** (object) - Contains the response data, including `total` count and `_embedded` resources. - **body.total** (integer) - The total number of records available. - **body._embedded.customers** (array) - An array of customer objects for the current page. - **body._links.next** (object) - An object containing the URL for the next page of results, if available. - **body._links.next.href** (string) - The URL to fetch the next page. ### Response Example ```json { "total": 100, "_embedded": { "customers": [ { /* customer object */ }, { /* customer object */ } ] }, "_links": { "next": { "href": "/customers?limit=25&offset=25" } } } ``` ``` -------------------------------- ### Working with Response Headers Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md Demonstrates how to retrieve specific headers (like Location and Content-Type) and iterate over all headers from a response. ```javascript const response = await dwolla.post("/customers", customerData); // Get single header (case-insensitive) const location = response.headers.get("Location"); const contentType = response.headers.get("Content-Type"); // Iterate all headers for (const [key, value] of response.headers) { console.log(`${key}: ${value}`); } // Common headers response.headers.get("Content-Type"); // "application/vnd.dwolla.v1.hal+json" response.headers.get("Date"); // Server timestamp response.headers.get("RateLimit-Limit"); // Rate limit ceiling response.headers.get("RateLimit-Remaining"); // Requests remaining ``` -------------------------------- ### DELETE with Custom Headers Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Example of making a DELETE request with custom HTTP headers, such as an X-Request-ID. ```javascript const response = await dwolla.delete("/resource/id", {}, { "X-Request-ID": "request-123" }); ``` -------------------------------- ### client.token() Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Client.md Creates a Token instance for manual token management. This is useful if you are storing and retrieving OAuth tokens yourself. The Token instance can then be used to make API requests. ```APIDOC ## Token ### Description Creates a Token instance with the provided token data for manual token management. ### Method token(options) ### Parameters #### Options Object - **accessToken** (string) - Optional - OAuth access token - **refreshToken** (string) - Optional - OAuth refresh token - **expiresIn** (number) - Optional - Token expiration in seconds - **scope** (string) - Optional - Token scope - **accountId** (string) - Optional - Associated account ID ### Returns - **Token** - A Token instance ready to use for API requests. ### Example ```javascript const token = client.token({ accessToken: "stored-access-token", refreshToken: "stored-refresh-token", expiresIn: 3600 }); // Use token to make requests const customers = await token.get("customers"); ``` ``` -------------------------------- ### Retrieve Dwolla Webhook Subscriptions Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use the generic `get` method to retrieve a list of all webhook subscriptions. ```javascript await dwolla.get("/webhooks"); ``` -------------------------------- ### Retrieve Dwolla Document Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use the generic `get` method with a document ID to retrieve document details. ```javascript await dwolla.get(`/documents/${id}`); ``` -------------------------------- ### Create Token Instance Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Client.md The `token()` method creates a Token instance for manual token management. It accepts an options object containing access token, refresh token, expiration, scope, and account ID. ```javascript client.token(options) ``` ```javascript const token = client.token({ accessToken: "stored-access-token", refreshToken: "stored-refresh-token", expiresIn: 3600 }); // Use token to make requests const customers = await token.get("customers"); ``` -------------------------------- ### Retrieve Specific Dwolla Transfer Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use the generic `get` method with a transfer ID to retrieve transfer details. ```javascript await dwolla.get(`/transfers/${id}`); ``` -------------------------------- ### Retrieve Specific Dwolla Customer Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use the generic `get` method with a customer ID to retrieve a specific customer. ```javascript await dwolla.get(`/customers/${id}`); ``` -------------------------------- ### Accessing Resource URLs Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md Demonstrates multiple ways to obtain and use resource URLs, including from the 'Location' header after creation, from HAL links, or by constructing them manually. ```javascript // From Location header (after creation) const response = await dwolla.post("/customers", data); const url = response.headers.get("Location"); // From HAL link const customer = response.body._embedded.customers[0]; const url = customer._links.self.href; // By ID (construct manually) const url = `/customers/customer-id`; // All work equivalently: await dwolla.get(url); await dwolla.get(customer); // Uses _links.self.href ``` -------------------------------- ### Securely Configure Dwolla Client with Environment Variables Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Initialize the Dwolla client using environment variables for sensitive credentials like API keys and secrets to avoid hardcoding. ```javascript const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET }); ``` -------------------------------- ### Auth Constructor Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Auth.md Creates an Auth instance for initiating OAuth authorization. This is typically created via `client.auth(options)` rather than directly. ```APIDOC ## Auth Constructor ### Description Creates an Auth instance for initiating OAuth authorization. This is typically created via `client.auth(options)` rather than directly. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Constructor Parameters - **redirectUri** (string) - Optional - URI where the user will be redirected after authorizing - **scope** (string) - Optional - Space-separated scopes being requested - **state** (string) - Required - State parameter for CSRF protection (required for security) - **verifiedAccount** (boolean) - Optional - If true, require user to have a verified Dwolla account - **dwollaLanding** (string) - Optional - Custom landing page parameter (e.g., "register") ### Request Example ```javascript const Client = require("dwolla-v2").Client; const client = new Client({ key: "...", secret: "..." }); const auth = client.auth({ redirectUri: "https://myapp.com/oauth-callback", scope: "funding|transfers", state: crypto.randomBytes(16).toString("hex"), verifiedAccount: true }); ``` ### Response #### Success Response This constructor does not return a value directly but initializes an Auth object with properties. #### Response Example N/A ``` -------------------------------- ### POST Request with Empty Body Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/HTTP-Methods.md Makes a POST request to an endpoint that does not require a request body. This example initiates microdeposits. ```javascript // Some endpoints accept POST with no body const response = await dwolla.post("/initiate-microdeposits", { customerId: "customer-id" }); ``` -------------------------------- ### Configure Dwolla Client for Sandbox Environment Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Set up the Dwolla client to interact with the sandbox environment for testing purposes. This is crucial for development and avoiding live transactions. ```javascript // Use sandbox for testing const dwolla = new Client({ key: "...", secret: "...", environment: "sandbox" }); // Use production for live transactions const dwolla = new Client({ key: "...", secret: "...", environment: "production" }); ``` -------------------------------- ### ClientOptions Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Configuration options passed to the Client constructor. These options are used to set up your application's connection to the Dwolla API. ```APIDOC ## Client Options Configuration options passed to the Client constructor. ### Parameters #### Request Body - **key** (string) - Required - Application key (Client ID) from Dwolla dashboard. Alias: `id` - **secret** (string) - Required - Application secret from Dwolla dashboard - **environment** (string) - Optional - Either "production" or "sandbox". Defaults to "production". - **onGrant** (function) - Optional - Callback function executed when a token is obtained; receives Token object. Defaults to `undefined`. ### Example ```javascript const client = new Client({ key: process.env.DWOLLA_KEY, secret: process.env.DWOLLA_SECRET, environment: "sandbox", onGrant: async (token) => { // Save token to database await db.tokens.save(token); } }); ``` ``` -------------------------------- ### Server-to-Server Authentication Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Use this for standard API requests when server-to-server authentication is required. No explicit setup is needed as it's automatically handled by the Client. ```javascript const response = await dwolla.get("/customers"); ``` -------------------------------- ### Handle Client Constructor Errors: Missing Key Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/errors.md Catch synchronous errors when the Client constructor is called without a 'key' or 'id' option, or if the value is not a string. Proper key configuration is essential for client initialization. ```javascript try { new Client({ secret: "secret" }); // Missing key new Client({ id: 123, secret: "secret" }); // Not a string } catch (error) { console.error(error.message); // "key is required." } ``` -------------------------------- ### Get Paginated Results Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/README.md Retrieve paginated lists of resources, such as customers. Specify the 'limit' and 'offset' for pagination. The total count and results are available in the response body. ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 50 }); console.log(response.body.total); // Total count console.log(response.body._embedded.customers); // Results array ``` -------------------------------- ### Get Client Credentials Token Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Auth.md Obtain an access token for server-to-server authentication using the client credentials grant. This token can then be used for making API requests. ```javascript const token = await dwolla.auth.client(); // token now has access_token and can be used for API requests ``` -------------------------------- ### Paginated List Response Example Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Response-Handling.md List endpoints return paginated results, including the total count of resources, an embedded array of resources, and pagination links. ```javascript const response = await dwolla.get("/customers", { limit: 25, offset: 50 }); response.body = { total: 100, // Total number of resources _embedded: { customers: [ { /* resource 1 */ }, { /* resource 2 */ }, // ... up to limit (25) ] }, _links: { self: { href: "/customers?offset=50&limit=25" }, next: { href: "/customers?offset=75&limit=25" }, last: { href: "/customers?offset=75&limit=25" } } } ``` -------------------------------- ### Client Constructor Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Client.md Creates a new Client instance for interacting with the Dwolla API. It handles OAuth token management and configuration of authentication credentials. ```APIDOC ## new Client(options) ### Description Creates a new Client instance for interacting with the Dwolla API. It handles OAuth token management and configuration of authentication credentials. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | key | string | Yes | — | Application key (Client ID) from Dwolla dashboard | | secret | string | Yes | — | Application secret from Dwolla dashboard | | environment | string | No | "production" | Either "production" or "sandbox" | | onGrant | function | No | undefined | Callback function executed when a token is granted, receives Token object | ### Throws - `Error` if options is not an object - `Error` if key/id is not a string - `Error` if secret is not a string - `Error` if environment is not "production" or "sandbox" - `Error` if onGrant is provided but is not a function ### Example ```javascript const Client = require("dwolla-v2").Client; const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET, environment: "sandbox" }); ``` ``` -------------------------------- ### Get Dwolla Node User Agent String Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Utilities.md Retrieve the SDK's user agent string, which is automatically included in API requests. The format is 'dwolla-v2-node VERSION'. ```javascript const userAgent = require("dwolla-v2/src/dwolla/userAgent"); console.log(userAgent); // "dwolla-v2-node 3.4.2" ``` -------------------------------- ### Instantiate Dwolla Client Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/api-reference/Client.md Creates a new Client instance for interacting with the Dwolla API. Requires application key and secret, and optionally accepts an environment setting. The `onGrant` callback can be provided to handle token grants. ```javascript const Client = require("dwolla-v2").Client; const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET, environment: "sandbox" }); ``` -------------------------------- ### Initialize Dwolla OAuth Configuration Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Configure OAuth settings for the Dwolla client, including redirect URI, scope, and state for security. The `auth` object is created using the client instance. ```javascript const auth = client.auth({ redirectUri: string, scope?: string, state?: string, verifiedAccount?: boolean, dwollaLanding?: string }); ``` -------------------------------- ### Dwolla v2 Node.js TypeScript Definitions Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/INDEX.md Example of TypeScript type definitions for the dwolla-v2 module. These definitions provide type safety for the Client class and Response objects. ```typescript declare module "dwolla-v2" { export class Client { ... } interface Response { ... } } ``` -------------------------------- ### AuthOptions Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/types.md Configuration options for creating an Auth instance. These options customize the OAuth authorization flow. ```APIDOC ## Auth Options Configuration options for creating an Auth instance. ### Parameters #### Request Body - **redirect_uri** (string) - Optional - OAuth redirect URI where user is sent after authorization - **scope** (string) - Optional - Space-separated scopes being requested (e.g., "funding\|transfers") - **state** (string) - Optional - CSRF protection token; should be random and verified on callback - **verified_account** (boolean) - Optional - If true, require user to have verified Dwolla account - **dwolla_landing** (string) - Optional - Landing page customization (e.g., "register") ### Example ```javascript const auth = client.auth({ redirect_uri: "https://myapp.com/oauth-callback", scope: "funding|transfers", state: "random-csrf-token-1234567890", verified_account: true }); ``` ``` -------------------------------- ### Load Environment Variables for Dwolla Client Source: https://github.com/dwolla/dwolla-v2-node/blob/main/_autodocs/configuration.md Load application credentials and environment settings from .env files for development. Ensure DWOLLA_APP_KEY, DWOLLA_APP_SECRET, and DWOLLA_ENVIRONMENT are set. ```javascript require("dotenv").config(); // For development const dwolla = new Client({ key: process.env.DWOLLA_APP_KEY, secret: process.env.DWOLLA_APP_SECRET, environment: process.env.DWOLLA_ENVIRONMENT || "sandbox" }); ```