### Handle INSTALL Webhook Event Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/WebhookManager.md Example handler for processing INSTALL webhook events. It logs installation details and assumes the SDK automatically stores the access token. ```typescript app.post('/webhooks/ghl', ghl.webhooks.subscribe()); app.post('/webhooks/ghl', async (req, res) => { const { body, isSignatureValid } = req as any; if (body.type === 'INSTALL' && isSignatureValid) { console.log(`App installed at location: ${body.locationId}`); console.log(`Company: ${body.companyName}`); // Token is automatically stored // You can now use ghl.contacts.getContacts({ locationId: body.locationId }) // Notify your user await notifyInstallSuccess(body.locationId); } res.json({ success: true }); }); ``` -------------------------------- ### Complete Webhook Example with SDK Middleware Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/WebhookManager.md A full TypeScript example demonstrating how to set up an Express server, initialize the HighLevel SDK, subscribe to webhooks using SDK middleware, and handle incoming webhook events including installation and uninstallation. ```typescript import express from 'express'; import bodyParser from 'body-parser'; import HighLevel, { MongoDBSessionStorage, LogLevel } from '@gohighlevel/api-client'; const app = express(); app.use(bodyParser.json()); const ghl = new HighLevel({ clientId: process.env.CLIENT_ID!, clientSecret: process.env.CLIENT_SECRET!, sessionStorage: new MongoDBSessionStorage( process.env.MONGODB_URL || 'mongodb://localhost:27017', 'ghl_sessions' ), logLevel: LogLevel.INFO }); // Webhook endpoint with SDK middleware app.post('/webhooks/ghl', ghl.webhooks.subscribe()); // Your webhook handler app.post('/webhooks/ghl', async (req, res) => { const { body, isSignatureValid } = req as any; if (!isSignatureValid) { console.warn('Webhook signature verification failed'); return res.status(401).json({ error: 'Invalid signature' }); } console.log(`Webhook ${body.type}:`, { appId: body.appId, locationId: body.locationId, companyId: body.companyId, timestamp: body.timestamp }); if (body.type === 'INSTALL') { // Token is already stored by SDK // Make a test API call to verify try { const location = await ghl.locations.getLocation( { locationId: body.locationId }, { headers: { locationId: body.locationId } } ); console.log(`Successfully installed at: ${location.location.name}`); // Track installation in your database await trackInstallation(body); } catch (error) { console.error('Failed to verify installation:', error); } } else if (body.type === 'UNINSTALL') { // Token is already deleted by SDK console.log('App uninstalled, token removed'); // Track uninstallation in your database await trackUninstallation(body); } res.json({ success: true }); }); app.listen(3000, () => { console.log('Webhook server listening on port 3000'); }); async function trackInstallation(webhook: any) { // Your tracking logic } async function trackUninstallation(webhook: any) { // Your tracking logic } ``` -------------------------------- ### Configuration Methods Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Provides examples for updating, getting, and setting SDK configuration, including API version. ```APIDOC ## Configuration Methods ### Description Methods to manage the SDK's configuration, including updating settings, retrieving current configuration, and accessing headers. ### Code Examples ```typescript // Update configuration ghl.updateConfig({ apiVersion: '2021-07-28' }); // Get current configuration const config = ghl.getConfig(); // Get current headers const headers = ghl.getHeaders(); // Set API version ghl.setApiVersion('2021-07-28'); ``` ``` -------------------------------- ### Install GoHighLevel SDK Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/README.md Install the GoHighLevel SDK using npm. Ensure your Node.js version is 18.0.0 or higher. ```bash npm install @gohighlevel/api-client ``` -------------------------------- ### INSTALL Event Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/WebhookManager.md Handles the INSTALL event, triggered when the app is installed at a location or company. The SDK automatically manages authentication tokens upon successful validation. ```APIDOC ## INSTALL Event Triggered when the app is installed at a location or company. ### Request Body Structure ```typescript interface InstallWebhookRequest { type: 'INSTALL'; appId: string; versionId: string; installType: string; // e.g., 'location' or 'company' locationId?: string; // Present for location installs companyId: string; // Always present userId?: string; companyName?: string; isWhitelabelCompany?: boolean; whitelabelDetails?: { logoUrl: string; domain: string; }; planId?: string; trial?: object; timestamp: string; // ISO timestamp webhookId: string; } ``` ### SDK Behavior If `companyId` and `locationId` are present and signature is valid: 1. Calls OAuth service to generate location access token 2. Stores token in configured sessionStorage 3. Token is available for immediate use in subsequent API calls ### Example Handler ```typescript app.post('/webhooks/ghl', ghl.webhooks.subscribe()); app.post('/webhooks/ghl', async (req, res) => { const { body, isSignatureValid } = req as any; if (body.type === 'INSTALL' && isSignatureValid) { console.log(`App installed at location: ${body.locationId}`); console.log(`Company: ${body.companyName}`); // Token is automatically stored // You can now use ghl.contacts.getContacts({ locationId: body.locationId }) // Notify your user await notifyInstallSuccess(body.locationId); } res.json({ success: true }); }); ``` ``` -------------------------------- ### Install HighLevel API SDK Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Install the SDK using npm. Requires Node.js >= 18.0.0. ```bash npm install @gohighlevel/api-client ``` -------------------------------- ### Example: Retrieve All Sessions Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Storage.md Demonstrates how to call the `getSessionsByApplication` method and log the number of sessions found. Ensure the storage provider has implemented this method. ```typescript // Retrieve all stored sessions for this app const allSessions = await storage.getSessionsByApplication(); console.log(`Found ${allSessions.length} sessions`); ``` -------------------------------- ### Service Operations Examples Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Provides examples of how to invoke various service operations offered by the SDK, such as retrieving contact details, searching locations, and accessing sales pipeline information. ```APIDOC ## Service Operations Examples ### Description This section demonstrates the usage of different service modules available within the GoHighLevel SDK to interact with various API domains. Examples include Contact Management, Location Management, Sales Pipeline, Campaigns, and Conversations. ### Language TypeScript ### Examples **Contact Management:** ```typescript // Get a specific contact await ghl.contacts.getContact({ contactId: '...' }); // Get all tasks for a contact await ghl.contacts.getAllTasks({ contactId: '...' }); ``` **Location Management:** ```typescript // Get a specific location await ghl.locations.getLocation({ locationId: '...' }); // Search for locations await ghl.locations.searchLocations(); ``` **Sales Pipeline:** ```typescript // Get a sales pipeline await ghl.opportunities.getPipeline({ locationId: '...' }); ``` **Campaigns & Marketing:** ```typescript // Get campaigns for a location await ghl.campaigns.getCampaigns({ locationId: '...' }); ``` **Conversations:** ```typescript // Get a specific conversation await ghl.conversations.getConversation({ conversationId: '...' }); ``` ### See Also - [MODULES.md](./MODULES.md) for a complete list of services. ``` -------------------------------- ### OAuth Setup with MongoDB Session Storage Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Initialize the GoHighLevel SDK for OAuth 2.0 authentication, utilizing MongoDB for session storage. This setup is for multi-tenant applications. ```typescript import HighLevel, { MongoDBSessionStorage } from '@gohighlevel/api-client'; const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new MongoDBSessionStorage( 'mongodb://localhost:27017', 'ghl_sessions' ), logLevel: 'info' }); ``` -------------------------------- ### Working with Contacts Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Examples demonstrating how to fetch single and multiple contacts using the HighLevel API SDK. ```APIDOC ## Usage Examples **NOTE**: If companyId or locationId is part of query, body or header parameter then you don't need to pass it specifically. But if it is not, then you need to pass it in headers as shown below. ### Working with Contacts #### Get a Single Contact ```typescript try { const contact = await ghl.contacts.getContact({ contactId: 'contact-uuid-here' }, { headers: { locationId // need to pass locationId here so that SDK can fetch the token for the location (as it is not part of body or query parameter) }, }); console.log('Contact details:', contact); console.log('Contact name:', contact.contact.name); } catch (error) { console.error('Error fetching contact:', error.message); } ``` #### Get Multiple Contacts ```typescript try { const contactsList = await ghl.contacts.getContacts({ locationId: 'your-location-id', limit: 20, startAfter: 1634567890000 // Unix timestamp }); console.log(`Found ${contactsList.contacts.length} contacts`); contactsList.contacts.forEach(contact => { console.log(`${contact.name} - ${contact.email}`); }); } catch (error) { console.error('Error fetching contacts:', error.message); } ``` ``` -------------------------------- ### INSTALL Webhook Request Interface Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/WebhookManager.md Defines the structure for an INSTALL webhook request. This event is triggered when the app is installed at a location or company. ```typescript interface InstallWebhookRequest { type: 'INSTALL'; appId: string; versionId: string; installType: string; // e.g., 'location' or 'company' locationId?: string; // Present for location installs companyId: string; // Always present userId?: string; companyName?: string; isWhitelabelCompany?: boolean; whitelabelDetails?: { logoUrl: string; domain: string; }; planId?: string; trial?: object; timestamp: string; // ISO timestamp webhookId: string; } ``` -------------------------------- ### Webhook Handling Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md This section details how to set up and handle HighLevel webhooks using the SDK, including automatic signature verification for INSTALL and UNINSTALL events. ```APIDOC ## Webhooks Handle HighLevel webhooks with built-in signature verification and handles INSTALL and UNINSTALL events for your application. - INSTALL: In case of bulk installation, it will generate and store the token for all the locations for which installation was triggered - UNINSTALL: If your app is uninstalled at any location or company, it will remove token for that from the storage which is used by SDK. **NOTE**: The endpoint which you use should be the one which is configured in `Default Webhook URL` for your application in marketplace. We send INSTALL and UNINSTALL events to default url only. ```typescript import express from 'express'; import bodyParser from 'body-parser'; // Assuming bodyParser is used const app = express(); // SDK middleware processes webhook app.use(bodyParser.json()); // This is required to parse the request body properly app.use('/webhooks/ghl', ghl.webhooks.subscribe()); // Your handler runs after SDK processing app.post('/webhooks/ghl', async (req, res) => { console.log(req.isSignatureValid); // your logic for webhook goes here res.json({ success: true }); }); // you can also use SDK to verify signature ghl.webhooks.verifySignature(payload, signature, ghlPublicKey) ghl.webhooks.verifyEd25519Signature(payload, signature, newGhlPublicKey) ``` The SDK automatically handles signature verification, if it is valid then you will get the flag `isSignatureValid` as true. Use these environment variables for webhook signature verification in your application: - `x-ghl-signature` (Ed25519, preferred): set `WEBHOOK_SIGNATURE_PUBLIC_KEY` in environment variable - `x-wh-signature` (legacy fallback): set `WEBHOOK_PUBLIC_KEY` in environment variable Verification order is: 1. If `x-ghl-signature` is present, SDK validates it using `WEBHOOK_SIGNATURE_PUBLIC_KEY` and does not fall back to `x-wh-signature`. 2. If `x-ghl-signature` is absent, SDK checks `x-wh-signature` using `WEBHOOK_PUBLIC_KEY`. For `INSTALL` and `UNINSTALL` webhooks, if the required signature header or corresponding public key is missing, SDK skips processing those events. ``` -------------------------------- ### Working with Other Services Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Examples for interacting with locations and campaigns using the SDK. ```APIDOC ### Working with Other Services #### Locations ```typescript // Get all locations const locations = await ghl.locations.searchLocations(); // As getLocation supports both agency and location token, you can pass which token you want to use using preferredTokenType const location = await ghl.locations.getLocation( { locationId }, { preferredTokenType: 'location' } ) ``` #### Campaigns ```typescript // Get campaigns const campaigns = await ghl.campaigns.getCampaigns({ locationId: 'location-id' }); ``` ``` -------------------------------- ### Environment Setup for HighLevel API SDK Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/README.md Configure necessary environment variables for authentication, MongoDB, webhooks, and logging before running the SDK. Ensure you replace placeholder values with your actual credentials and keys. ```bash # Authentication export CLIENT_ID=your-client-id export CLIENT_SECRET=your-client-secret # MongoDB (for OAuth token storage) export MONGODB_URL=mongodb://localhost:27017 export MONGODB_DATABASE=ghl_sessions # Webhooks export WEBHOOK_SIGNATURE_PUBLIC_KEY=your-ed25519-key export WEBHOOK_PUBLIC_KEY=your-sha256-key # Logging export LOG_LEVEL=warn ``` -------------------------------- ### Fetch Installed Locations Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/OAuth.md Retrieve a list of locations where your application is installed. Supports filtering by trial status, specific location ID, and pagination. Requires an agency access token. ```typescript async getInstalledLocation( params: { skip?: string; limit?: string; query?: string; isInstalled?: boolean; companyId: string; appId: string; versionId?: string; onTrial?: boolean; planId?: string; locationId?: string; }, options?: AxiosRequestConfig ): Promise ``` ```typescript // Get all locations where app is installed const installed = await ghl.oauth.getInstalledLocation({ companyId: 'com-123', appId: 'my-app-id', limit: '50', skip: '0' }); console.log(`App installed at ${installed.locations.length} locations`); installed.locations.forEach(loc => { console.log(`- ${loc.name} (${loc.locationId})`); }); // Filter by trial status const trials = await ghl.oauth.getInstalledLocation({ companyId: 'com-123', appId: 'my-app-id', onTrial: true }); console.log(`${trials.locations.length} trial installations`); // Search specific location const specific = await ghl.oauth.getInstalledLocation({ companyId: 'com-123', appId: 'my-app-id', locationId: 'loc-456' }); ``` -------------------------------- ### Add Request Interceptor Example Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/types.md Example of how to create and add a request interceptor to modify headers. The returned ID can be used to remove the interceptor later. ```typescript const interceptor: RequestInterceptor = { onFulfilled: (config) => { config.headers['X-Custom-Header'] = 'value'; return config; }, onRejected: (error) => { console.error('Request error:', error); return Promise.reject(error); } }; const id = ghl.addRequestInterceptor(interceptor); ``` -------------------------------- ### Handle UNINSTALL Webhook Event Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/WebhookManager.md Example handler for processing UNINSTALL webhook events. It logs uninstallation details and assumes the SDK automatically removes the access token. ```typescript app.post('/webhooks/ghl', ghl.webhooks.subscribe()); app.post('/webhooks/ghl', async (req, res) => { const { body, isSignatureValid } = req as any; if (body.type === 'UNINSTALL' && isSignatureValid) { console.log(`App uninstalled`); if (body.locationId) { console.log(`Location: ${body.locationId}`); } console.log(`Company: ${body.companyId}`); // Token is automatically removed // Notify your user await notifyUninstallSuccess(body.locationId || body.companyId); } res.json({ success: true }); }); ``` -------------------------------- ### Add Response Interceptor Example Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/types.md Example of how to create and add a response interceptor to log response status or handle specific errors like rate limiting. The returned ID can be used to remove the interceptor later. ```typescript const interceptor: ResponseInterceptor = { onFulfilled: (response) => { console.log(`${response.status} response from ${response.config.url}`); return response; }, onRejected: (error) => { if (error.response?.status === 429) { console.warn('Rate limited'); } return Promise.reject(error); } }; const id = ghl.addResponseInterceptor(interceptor); ``` -------------------------------- ### Error Handling Example Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/HighLevel.md Demonstrates how to use a try-catch block to handle potential GHLError exceptions when making API calls with the SDK. ```APIDOC ## Error Handling Example ### Description This code snippet shows how to gracefully handle API errors that may occur when interacting with the GoHighLevel API using the SDK. It specifically catches `GHLError` instances, allowing for detailed inspection of the error status code, message, and response. ### Method ```typescript try { const contacts = await ghl.contacts.getContacts({ locationId: 'loc-123' }); } catch (error) { if (error instanceof GHLError) { console.error(`API Error (${error.statusCode}): ${error.message}`); console.error('Response:', error.response); } else { console.error('Unexpected error:', error); } } ``` ``` -------------------------------- ### Import Core Types from HighLevel SDK Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/README.md Imports all essential types from the main '@gohighlevel/api-client' package. Ensure this package is installed to use these types. ```typescript import { HighLevel, HighLevelConfig, ValidConfig, GHLError, SessionStorage, MongoDBSessionStorage, MemorySessionStorage, ISessionData, Logger, LogLevel, LogLevelType, WebhookManager, UserType, RequestInterceptor, ResponseInterceptor } from '@gohighlevel/api-client'; ``` -------------------------------- ### Webhook Manager Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/HighLevel.md Provides express middleware for handling incoming GoHighLevel webhooks, including automatic handling of INSTALL and UNINSTALL events. ```APIDOC ### Webhook Manager ```typescript public webhooks: WebhookManager; ``` Express middleware for handling incoming GoHighLevel webhooks. Automatically handles INSTALL and UNINSTALL events. See [WebhookManager](./WebhookManager.md). ``` -------------------------------- ### Initialize with OAuth and MongoDB Session Storage Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/configuration.md This example shows how to initialize the client for OAuth authentication using MongoDB for session storage. This is suitable for production environments. Replace placeholders with your actual credentials and MongoDB connection string. ```typescript import HighLevel, { MongoDBSessionStorage, LogLevel } from '@gohighlevel/api-client'; // OAuth with MongoDB storage (production) const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new MongoDBSessionStorage( 'mongodb://localhost:27017', 'ghl_database' ), logLevel: LogLevel.DEBUG }); ``` -------------------------------- ### Log Output Examples for Different Levels Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Logging.md Observe how log messages vary based on the configured log level. The SDK prefixes messages with '[GHL SDK]'. ```typescript logger.error('Authentication failed', { code: 401 }); logger.warn('Token will expire in 30 seconds'); logger.info('Token refreshed successfully'); logger.debug('Request sent', { method: 'GET', url: '/contacts' }); ``` ```text (no output) ``` ```text [GHL SDK] ERROR: Authentication failed { code: 401 } ``` ```text [GHL SDK] ERROR: Authentication failed { code: 401 } [GHL SDK] WARN: Token will expire in 30 seconds ``` ```text [GHL SDK] ERROR: Authentication failed { code: 401 } [GHL SDK] WARN: Token will expire in 30 seconds [GHL SDK] INFO: Token refreshed successfully ``` ```text [GHL SDK] ERROR: Authentication failed { code: 401 } [GHL SDK] WARN: Token will expire in 30 seconds [GHL SDK] INFO: Token refreshed successfully [GHL SDK] DEBUG: Request sent { method: 'GET', url: '/contacts' } ``` -------------------------------- ### Log Levels Configuration Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Explains the different log levels available (`none`, `error`, `warn`, `info`, `debug`) and provides an example of how to dynamically set the log level based on the environment. ```APIDOC ## Log Levels Configuration ### Description This section details the available log levels for the GoHighLevel SDK and provides a practical example of how to set the log level conditionally based on the application's environment. This allows for more verbose logging during development and more restricted logging in production. ### Log Levels Table | Level | Messages Included | |-------|-------------------| | `none` | — | | `error` | Errors only | | `warn` | Errors, warnings | | `info` | Errors, warnings, info | | `debug` | All messages | ### Example Usage ```typescript const ghl = new HighLevel({ logLevel: process.env.NODE_ENV === 'production' ? 'warn' : 'debug' }); ``` ``` -------------------------------- ### Setup Express Server for HighLevel Webhooks Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Configure an Express.js server to handle HighLevel webhook events, including signature verification. Ensure `bodyParser.json()` is used before the SDK middleware. ```typescript import express from 'express'; const app = express(); // SDK middleware processes webhook app.use(bodyParser.json()) // This is required to parse the request body properly app.use('/webhooks/ghl', ghl.webhooks.subscribe()); // Your handler runs after SDK processing app.post('/webhooks/ghl', async (req, res) => { console.log(req.isSignatureValid) // your logic for webhook goes here res.json({ success: true }); }); // you can also use SDK to verify signature ghl.webhooks.verifySignature(payload, signature, ghlPublicKey) ghl.webhooks.verifyEd25519Signature(payload, signature, newGhlPublicKey) ``` -------------------------------- ### Error Handling Example Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Demonstrates how to handle potential errors when making API calls using the SDK. It shows how to catch `GHLError` instances and inspect their properties like `statusCode` and `message` for specific error handling. ```APIDOC ## Error Handling Example ### Description This code snippet illustrates how to gracefully handle errors that may occur during API interactions with the GoHighLevel SDK. It specifically shows how to catch `GHLError` exceptions, check the status code for common issues like authentication failures (401), not found errors (404), and rate limiting (429), and provides a fallback for other API errors. ### Language TypeScript ### Code ```typescript import { GHLError } from '@gohighlevel/api-client'; try { const contact = await ghl.contacts.getContact({ contactId: 'invalid-id' }); } catch (error) { if (error instanceof GHLError) { console.error(`Error ${error.statusCode}: ${error.message}`); switch (error.statusCode) { case 401: console.error('Authentication failed'); break; case 404: console.error('Contact not found'); break; case 429: console.error('Rate limited, retry later'); break; default: console.error('API error:', error.response); } } else { console.error('Unexpected error:', error); } } ``` ### See Also - [Error Reference](./errors.md) ``` -------------------------------- ### Implement Custom Session Storage (TypeScript) Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Implement a custom session storage by extending the `SessionStorage` class. Requires methods for initialization, disconnection, setting, getting, and deleting sessions. ```typescript import { SessionStorage, ISessionData } from '@gohighlevel/api-client'; class RedisSessionStorage extends SessionStorage { async init(): Promise { // Initialize your storage connection } async disconnect(): Promise { // Close your storage connection } async setSession(key: string, data: ISessionData, ttl?: number): Promise { // Implement session storage logic } async getSession(key: string): Promise { // Implement session retrieval logic return null; } async deleteSession(key: string): Promise { // Implement session deletion logic return true; } } // Use your custom storage const ghl = new HighLevel({ sessionStorage: new RedisSessionStorage({ // your custom config }) }); ``` -------------------------------- ### Initialize HighLevel SDK with Location Access Token (JavaScript ES Modules) Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Initialize the SDK using ES Modules format with a location access token. ```javascript import HighLevel from '@gohighlevel/api-client'; const ghl = new HighLevel({ locationAccessToken: 'your-location-access-token' }); ``` -------------------------------- ### Implement Backoff and Retry for Rate Limiting Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Handle 429 Rate Limited errors by implementing a backoff strategy. This example waits for 5 seconds before retrying the API call to get contacts. ```typescript // Implement backoff and retry await new Promise(resolve => setTimeout(resolve, 5000)); const result = await ghl.contacts.getContacts({ locationId: 'loc-123' }); ``` -------------------------------- ### Fallback Chain for Not Found Errors Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/errors.md Implement a fallback mechanism to try an alternative lookup method when a primary API call fails with a 'Not Found' error (404). This example first tries to get a contact by ID and, if not found, attempts to search for it using advanced filters. ```typescript async function getContactSafe(contactId: string) { try { return await ghl.contacts.getContact({ contactId }); } catch (error) { if (error instanceof GHLError && error.statusCode === 404) { console.log('Contact not found, checking by email...'); // Try alternative lookup const results = await ghl.contacts.searchContactsAdvanced({ locationId: 'loc-123', filters: { id: contactId } }); return results.contacts[0] || null; } throw error; } } ``` -------------------------------- ### Initialize HighLevel SDK with Private Integration Token (JavaScript CommonJS) Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Initialize the SDK using CommonJS module format with a private integration token. ```javascript const HighLevel = require('@gohighlevel/api-client').default; // or const { HighLevel } = require('@gohighlevel/api-client'); const ghl = new HighLevel({ privateIntegrationToken: 'your-private-integration-token' }); ``` -------------------------------- ### Basic SDK Initialization Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Initialize the GoHighLevel SDK with a private integration token for direct API access. This is suitable for scripts and server-to-server communication. ```typescript import HighLevel from '@gohighlevel/api-client'; const ghl = new HighLevel({ privateIntegrationToken: 'your-private-integration-token' }); // Use services const contacts = await ghl.contacts.getContacts({ locationId: 'your-location-id' }); ``` -------------------------------- ### getInstalledLocation Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/OAuth.md Fetch locations where your app is installed. This endpoint allows filtering by various criteria such as installation status, trial status, and specific company or location IDs. ```APIDOC ## GET /oauth/installedLocations ### Description Fetch locations where your app is installed. ### Method GET ### Endpoint /oauth/installedLocations ### Parameters #### Query Parameters - **skip** (string) - Optional - Pagination offset - **limit** (string) - Optional - Maximum results per page - **query** (string) - Optional - Search query for location names - **isInstalled** (boolean) - Optional - Filter by installation status - **companyId** (string) - Required - Company ID to query - **appId** (string) - Required - Your app ID - **versionId** (string) - Optional - Specific app version to filter - **onTrial** (boolean) - Optional - Filter trial installations - **planId** (string) - Optional - Filter by subscription plan - **locationId** (string) - Optional - Specific location ID ### Response #### Success Response (200) - **locations** (array) - List of installed locations. Each location object may contain fields like `name`, `locationId`, etc. ### Response Example ```json { "locations": [ { "name": "Example Location", "locationId": "loc-123" } ] } ``` ### Authentication Agency-Access-Only token (required) ``` -------------------------------- ### Initialize HighLevel SDK and Access Services Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/INDEX.md Instantiate the HighLevel SDK with configuration and access various service instances like contacts, locations, and oauth. ```typescript const ghl = new HighLevel(config); ghl.contacts // Service instance ghl.locations ghl.oauth // ... 38+ more services ``` -------------------------------- ### SDK Initialization and Contact Retrieval Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Demonstrates how to initialize the SDK with configuration and retrieve a contact using type-safe methods. TypeScript helps catch errors at compile time. ```APIDOC ## SDK Initialization and Contact Retrieval ### Description Initialize the SDK with your configuration and demonstrate retrieving a contact. The SDK leverages TypeScript for type safety, catching parameter errors during compilation. ### Code Example ```typescript import HighLevel, { HighLevelConfig, GHLError, RequestInterceptor, ResponseInterceptor } from '@gohighlevel/api-client'; // Type-safe configuration const config: HighLevelConfig = { privateIntegrationToken: 'your-token', apiVersion: '2021-07-28' }; const ghl = new HighLevel(config); // All methods return properly typed responses const contact = await ghl.contacts.getContact({ contactId: 'contact-id' }); // TypeScript will catch parameter errors at compile time // ghl.contacts.getContact({}); // ✗ Error: missing contactId // ghl.contacts.getContact({ contactId: 123 }); // ✗ Error: contactId must be string ``` ``` -------------------------------- ### HighLevel Constructor Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/HighLevel.md Initializes the SDK client with authentication and configuration. Requires either a privateIntegrationToken or both clientId and clientSecret. ```APIDOC ## Constructor ```typescript constructor(config: ValidConfig) ``` Initializes the SDK client with authentication and configuration. **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | config | ValidConfig | Yes | SDK configuration object. Must provide either privateIntegrationToken OR both clientId and clientSecret. See [Configuration Reference](../configuration.md). | **Throws:** - `GHLError` if configuration is invalid (missing required authentication) **Example:** ```typescript import HighLevel from '@gohighlevel/api-client'; // Initialize with private integration token const ghl = new HighLevel({ privateIntegrationToken: 'your-private-token', logLevel: 'info' }); // Initialize with OAuth credentials const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new MongoDBSessionStorage( 'mongodb://localhost:27017', 'ghl_db' ), logLevel: 'warn' }); ``` ``` -------------------------------- ### Get Location Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Locations.md Retrieves details for a specific location by its ID. ```APIDOC ## Get Location ### Description Retrieves details for a specific location by its ID. ### Method GET ### Endpoint `/locations/{locationId}` ### Parameters #### Path Parameters - **locationId** (string) - Required - The ID of the location to retrieve. ### Request Example ```typescript await ghl.locations.getLocation({ locationId: 'loc-123' }); ``` ### Response #### Success Response (200) - **location** (object) - The details of the requested location. - **location.id** (string) - The unique identifier for the location. - **location.name** (string) - The name of the location. #### Response Example ```json { "location": { "id": "loc-123", "name": "Example Location" } } ``` ``` -------------------------------- ### Initialize SDK with Missing Authentication Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/errors.md SDK initialization fails if neither a private integration token nor both clientId and clientSecret are provided. Ensure one of these authentication methods is configured. ```typescript const ghl = new HighLevel({ // Missing both privateIntegrationToken and clientId/clientSecret }); // Throws: GHLError // Message: "Invalid configuration: Either provide privateIntegrationToken OR both clientId and clientSecret are required." ``` -------------------------------- ### Get Contact Task Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Contacts.md Retrieves the details of a specific task associated with a contact. ```APIDOC ## GET /contacts/{contactId}/tasks/{taskId} ### Description Get details of a specific contact task. ### Method GET ### Endpoint `/contacts/{contactId}/tasks/{taskId}` ### Parameters #### Path Parameters - **contactId** (string) - Required - Contact ID - **taskId** (string) - Required - Task ID #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **title** (string) - The title of the task. - **status** (string) - The current status of the task (e.g., 'pending', 'completed'). - **dueDate** (string) - The due date of the task. #### Response Example ```json { "title": "Follow up with client", "status": "pending", "dueDate": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Initialize SDK with OAuth 2.0 Credentials Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Initialize the GoHighLevel SDK for OAuth 2.0 authentication, suitable for multi-tenant applications. It uses environment variables for sensitive credentials and session storage. ```typescript const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new MongoDBSessionStorage( process.env.MONGODB_URL!, 'ghl_sessions' ), logLevel: 'warn' }); ``` -------------------------------- ### Get Current Log Level Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Logging.md Retrieves the current logging level set for the logger instance. ```typescript const currentLevel = logger.getLevel(); console.log(`Current log level: ${currentLevel}`); ``` -------------------------------- ### Initialize SDK with Private Integration Token Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/README.md Initialize the HighLevel client using a private integration token. This is suitable for server-to-server interactions. ```typescript import HighLevel from '@gohighlevel/api-client'; const ghl = new HighLevel({ privateIntegrationToken: 'your-token' }); const contacts = await ghl.contacts.getContacts({ locationId: 'your-location-id' }); ``` -------------------------------- ### Initialize HighLevel SDK with TypeScript Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Demonstrates how to initialize the HighLevel SDK with type-safe configuration in TypeScript. Ensure correct types are used for configuration parameters like privateIntegrationToken and apiVersion. ```typescript import HighLevel, { HighLevelConfig, GHLError, RequestInterceptor, ResponseInterceptor } from '@gohighlevel/api-client'; // Type-safe configuration const config: HighLevelConfig = { privateIntegrationToken: 'your-token', apiVersion: '2021-07-28' }; const ghl = new HighLevel(config); // All methods return properly typed responses const contact: ContactsByIdSuccessfulResponseDto = await ghl.contacts.getContact({ contactId: 'contact-id' }); // TypeScript will catch parameter errors at compile time // ghl.contacts.getContact({}); // ✗ Error: missing contactId // ghl.contacts.getContact({ contactId: 123 }); // ✗ Error: contactId must be string ``` -------------------------------- ### Get a Contact Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Retrieves a specific contact using their ID. You can then access properties like name and email. ```APIDOC ## Get a Contact ### Description Retrieves a specific contact using their ID. ### Method ```typescript await ghl.contacts.getContact({ contactId: 'contact-id-here' }) ``` ### Parameters #### Path Parameters - **contactId** (string) - Required - The ID of the contact to retrieve. ``` -------------------------------- ### Get a Contact Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/GETTING_STARTED.md Retrieve a specific contact's details using their ID. Ensure you have the correct contact ID. ```typescript const contact = await ghl.contacts.getContact({ contactId: 'contact-id-here' }); console.log(contact.name); console.log(contact.email); ``` -------------------------------- ### Get Task with Location ID Header Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Contacts.md Use this method when the locationId is not part of the request parameters, but needs to be provided in the headers. ```typescript await ghl.contacts.getTask( { contactId: 'contact-123', taskId: 'task-456' }, { headers: { locationId: 'loc-123' } } ); ``` -------------------------------- ### Initialize HighLevel SDK with OAuth Credentials and MongoDB Storage (TypeScript) Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Initialize the SDK using OAuth client ID and secret, with MongoDB for session storage. Recommended for production. ```typescript const ghl = new HighLevel({ clientId: 'your-oauth-client-id', clientSecret: 'your-oauth-client-secret', sessionStorage: new MongoDBSessionStorage({ dbUrl: 'mongodb://localhost:27017', dbName: 'ghl_sessions' }), logLevel: LogLevel.WARN }); ``` -------------------------------- ### Set up Webhook Middleware Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/README.md Configure an Express.js application to handle GoHighLevel webhooks. This includes parsing JSON bodies and mounting the webhook subscription middleware. ```typescript import express from 'express'; import bodyParser from 'body-parser'; const app = express(); app.use(bodyParser.json()); // Mount webhook middleware app.post('/webhooks/ghl', ghl.webhooks.subscribe()); // Handle webhooks app.post('/webhooks/ghl', async (req, res) => { const { body, isSignatureValid } = req as any; if (!isSignatureValid) { return res.status(401).json({ error: 'Invalid signature' }); } console.log(`Webhook: ${body.type}`); res.json({ success: true }); }); ``` -------------------------------- ### Get Current SDK Configuration Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/HighLevel.md Retrieve the current configuration object of the SDK. This can be used to inspect settings like the API version. ```typescript const config = ghl.getConfig(); console.log(config.apiVersion); ``` -------------------------------- ### Get Duplicate Contact with Location ID Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Contacts.md Use this method when the locationId is part of the query or body parameters to check for duplicate contacts. ```typescript await ghl.contacts.getDuplicateContact({ locationId: 'loc-123', email: 'test@example.com' }); ``` -------------------------------- ### Initialize HighLevel SDK with Private Integration Token (TypeScript) Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Initialize the SDK with a private integration token for private integrations. Supports logging levels. ```typescript import HighLevel, { MongoDBSessionStorage, LogLevel } from '@gohighlevel/api-client'; // or import { HighLevel } from '@gohighlevel/api-client'; // Initialize with private integration token const ghl = new HighLevel({ privateIntegrationToken: 'your-private-integration-token', logLevel: LogLevel.INFO }); ``` -------------------------------- ### init Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Storage.md Initializes the storage connection. This method is called automatically during HighLevel initialization. ```APIDOC ## init ### Description Initializes the storage connection. This method is called automatically during HighLevel initialization. ### Returns - **Promise** - A promise that resolves when the connection is established. ### Throws - Error if the connection fails. ``` -------------------------------- ### Get Campaigns using HighLevel SDK Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/README.md Retrieve a list of campaigns associated with a specific `locationId`. Ensure the `locationId` is correctly provided. ```typescript // Get campaigns const campaigns = await ghl.campaigns.getCampaigns({ locationId: 'location-id' }); ``` -------------------------------- ### Initialize with OAuth and Custom Redis Session Storage Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/configuration.md Demonstrates initializing the client for OAuth with a custom Redis session storage implementation. You need to provide your client ID, client secret, and ensure your Redis server is accessible. The RedisSessionStorage class needs to be fully implemented with your Redis logic. ```typescript import { SessionStorage, ISessionData } from '@gohighlevel/api-client'; class RedisSessionStorage extends SessionStorage { async init(): Promise { /* ... */ } async disconnect(): Promise { /* ... */ } async setSession(resourceId: string, sessionData: ISessionData): Promise { /* ... */ } async getSession(resourceId: string): Promise { /* ... */ } async deleteSession(resourceId: string): Promise { /* ... */ } async getAccessToken(resourceId: string): Promise { /* ... */ } async getRefreshToken(resourceId: string): Promise { /* ... */ } async createCollection(collectionName: string): Promise { /* ... */ } async getCollection(collectionName: string): Promise { /* ... */ } setClientId(clientId: string): void { /* ... */ } } const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new RedisSessionStorage(), logLevel: LogLevel.WARN }); ``` -------------------------------- ### Get Sessions by Application Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Storage.md Retrieves all sessions associated with the current application. This is an optional method that may be overridden by specific storage provider implementations. ```typescript async getSessionsByApplication(): Promise ``` -------------------------------- ### Initialize SDK with OAuth 2.0 Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/README.md Initialize the HighLevel client for OAuth 2.0 authentication. Requires client ID, client secret, and session storage configuration, such as MongoDB. ```typescript import HighLevel, { MongoDBSessionStorage } from '@gohighlevel/api-client'; const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new MongoDBSessionStorage( 'mongodb://localhost:27017', 'ghl_sessions' ) }); ``` -------------------------------- ### Configure HighLevel SDK with Logging Levels Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Logging.md Initialize the HighLevel client with a specific log level. Use `LogLevel.DEBUG` for verbose development logging or a string like 'warn' for production. ```typescript import HighLevel, { LogLevel } from '@gohighlevel/api-client'; // Development: verbose logging const ghl = new HighLevel({ privateIntegrationToken: 'token', logLevel: LogLevel.DEBUG }); // Production: warnings only const ghl = new HighLevel({ clientId: 'id', clientSecret: 'secret', logLevel: 'warn' // or LogLevel.WARN }); ``` -------------------------------- ### GHLError Class Details Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/HighLevel.md Provides details about the custom GHLError class used by the SDK for API error reporting, including its properties and an example of its usage. ```APIDOC ## GHLError Class ### Description The `GHLError` class is a custom error type provided by the SDK to encapsulate details about API-related errors. It extends the standard JavaScript `Error` class and includes additional properties for HTTP status codes, API responses, and request configurations. ### Properties | Property | Type | Description | |--------------|------|----------------------------------------------| | `message` | string | The error message | | `statusCode` | number | The HTTP status code of the API error (optional) | | `response` | any | The full API response object (optional) | | `request` | any | The original request configuration (optional) | ### Example Usage ```typescript try { await ghl.contacts.getContact({ contactId: 'invalid' }); } catch (error) { if (error instanceof GHLError) { switch (error.statusCode) { case 400: console.log('Invalid request:', error.response?.error); break; case 401: console.log('Authentication failed'); break; case 404: console.log('Resource not found'); break; case 429: console.log('Rate limited - retry after delay'); break; default: console.log('API error:', error.message); } } } ``` ``` -------------------------------- ### Get Location with Custom Headers Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/Locations.md Retrieves a specific location's details. The location ID can be passed in the query parameters or explicitly in the request headers. ```typescript // Pass locationId in headers if not in query parameters const location = await ghl.locations.getLocation( { locationId: 'loc-123' }, { headers: { locationId: 'loc-123' } } ); ``` -------------------------------- ### Initialize SDK with Storage Connection Error Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/errors.md SDK initialization can fail if the provided MongoDB connection details are invalid or the server is unreachable. Verify connection string and server status. ```typescript const storage = new MongoDBSessionStorage( 'mongodb://invalid-host:27017', 'ghl_db' ); const ghl = new HighLevel({ clientId: 'id', clientSecret: 'secret', sessionStorage: storage }); // Error: MongoNetworkError or connection timeout ``` -------------------------------- ### Initialize HighLevel Client with OAuth Credentials Source: https://github.com/gohighlevel/highlevel-api-sdk/blob/main/_autodocs/api-reference/HighLevel.md Use this snippet to initialize the SDK client with OAuth credentials, including client ID, client secret, and session storage configuration. This is suitable for applications requiring user authorization. ```typescript import HighLevel from '@gohighlevel/api-client'; import { MongoDBSessionStorage } from '@gohighlevel/api-client/dist/storage'; // Initialize with OAuth credentials const ghl = new HighLevel({ clientId: 'your-client-id', clientSecret: 'your-client-secret', sessionStorage: new MongoDBSessionStorage( 'mongodb://localhost:27017', 'ghl_db' ), logLevel: 'warn' }); ```