高级API SDK
官方 TypeScript/JavaScript SDK 高级(GoHighlevel)API. 这个SDK提供了一个全面的接口,可以与所有高级API端点进行内置认证,错误处理,以及自动令牌刷新等交互.
目录
安装
npm install @gohighlevel/api-client
所需资源
- 节点.js 18.0.0
- TypeScript QQ 4. 0 (如果使用 TypeScript ) (中文(简体) )
认证
高级API支持三种具有不同访问级别的认证符:
1. 私人融合
- 最高优先事项 - 用于私人融合
- 完全访问所有 API 端点
- 通过您的高级应用程序设置管理
2. 机构出入托肯
- 用于机构一级的业务
- 获取机构和分账户数据
- 通过 OAuth 2.0 流量获取
3. 访问托肯的地点
- 用于特定地点的业务
- 获取单一位置数据
- 通过 OAuth 2.0 流量获取
开始
基本设置
类型脚本
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
});
// Initialize with clientId, clientSecret, and MongoDB storage (recommended)
const ghl = new HighLevel({
clientId: 'your-oauth-client-id',
clientSecret: 'your-oauth-client-secret',
sessionStorage: new MongoDBSessionStorage(
'mongodb://localhost:27017', // connection string
'ghl_sessions', // database name
'application_sessions' // collection name (optional, this is the default)
),
logLevel: LogLevel.WARN,
rateLimitRetry: true // retry requests rejected by the burst rate limit, see Rate Limit Retry
});
Java 脚本 (CommonJS)
const HighLevel = require('@gohighlevel/api-client').default;
// or
const { HighLevel } = require('@gohighlevel/api-client');
const ghl = new HighLevel({
privateIntegrationToken: 'your-private-integration-token'
});
Java脚本( ES 模块)
import HighLevel from '@gohighlevel/api-client';
const ghl = new HighLevel({
locationAccessToken: 'your-location-access-token'
});
托肯管理
MongoDB 存储器
配置 MongoDB 存储以存储令牌数据, 并在进行 API 调用时自动获取 :
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',
'application_sessions' // optional collection name
)
});
这个 mongodb 驱动程序仅在 MongoDBSessionStorage ,所以带有自定义存储的应用程序在启动时不支付.
ưμ㼯A:没有MongoDB存储,数据默认会被存储在内存中(MemorySessionStorage),并在应用程序重新启动时丢失。 不建议生产。 如果你使用它, 盖住它的大小, 所以它不能生长无约束:
import { HighLevel, MemorySessionStorage } from '@gohighlevel/api-client';
const ghl = new HighLevel({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
sessionStorage: new MemorySessionStorage(undefined, { maxEntries: 1000 }) // least recently used sessions are evicted first
});
自定义存储执行
您也可以通过扩展 : SessionStorage 类 :
import { SessionStorage, ISessionData } from '@gohighlevel/api-client';
class RedisSessionStorage extends SessionStorage {
async init(): Promise<void> {
// Initialize your storage connection
}
async disconnect(): Promise<void> {
// Close your storage connection
}
async setSession(key: string, data: ISessionData, ttl?: number): Promise<void> {
// Implement session storage logic
}
async getSession(key: string): Promise<ISessionData | null> {
// Implement session retrieval logic
return null;
}
async deleteSession(key: string): Promise<boolean> {
// Implement session deletion logic
return true;
}
}
// Use your custom storage
const ghl = new HighLevel({
sessionStorage: new RedisSessionStorage({
// your custom config
})
});
自动刷新
SDK 当 :
- 收到401(未经授权)的答复
- 可用的有效刷新令牌
- OAuth 客户端证书配置
失败的请求用新符牌重审一次 。 同一地点或公司收到401的并发请求共享一次刷新呼叫,因此突起的请求永远不会触发同一资源的平行刷新.
速率限制重试
API执行一个爆破限制(每个短间隔的最大请求数量)和每日限制,并报告每个回复的当前状态:
| 页眉 | 含义 |
|---|---|
X-RateLimit-Max | 允许每个破裂间隔的请求 |
X-RateLimit-Interval-Milliseconds | 破裂间隔的长度 |
X-RateLimit-Remaining | 当前间隔中遗留的请求 |
X-RateLimit-Limit-Daily | 每天允许的请求 |
X-RateLimit-Daily-Remaining | 请求今天离开 |
当超过限制时, API 响应 429 Too Many Requests。重试是默认的选入和关闭,所以现有的应用程序保持其当前的行为。 启用它 rateLimitRetry数字 :
// Defaults: up to 3 retries, never wait more than 30 seconds for a single retry
const ghl = new HighLevel({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
sessionStorage,
rateLimitRetry: true
});
// Or tune it
const ghl = new HighLevel({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
sessionStorage,
rateLimitRetry: {
maxRetries: 3, // retries after the first 429 (default 3)
maxDelayMs: 10000, // upper bound for a single wait in ms (default 30000)
baseDelayMs: 1000 // starting delay in ms when the response has no rate limit headers (default 1000)
}
});
在429上会发生什么:
- 达到球壳极限 (单位:千美元)
X-RateLimit-Daily-Remaining大于 0 : SDK 等待间隔X-RateLimit-Interval-Milliseconds,封顶maxDelayMs,并再次发出同样的请求,直到maxRetries时间. - 日限已用尽 (单位:千美元)
X-RateLimit-Daily-Remaining实值0:重试不能成功,所以错误立即被抛出. - 无费率限制信头 sDK回落到指数回落中
baseDelayMs时,盖入maxDelayMs。 。 。 .
每次重试记录在 WARN 与解析页眉相连接。 当复试用完或复试被禁用时,拨打时会用 GHLRateLimitError 谁 rateLimit 字段持有解析页眉 :
import { GHLRateLimitError } from '@gohighlevel/api-client';
try {
await ghl.contacts.getContact({ contactId }, { headers: { locationId } });
} catch (error) {
if (error instanceof GHLRateLimitError) {
console.log(error.rateLimit);
// {
// scope: 'burst', // 'burst' | 'daily' | 'unknown'
// intervalMs: 10000,
// max: 100,
// remaining: 0,
// dailyLimit: 200000,
// dailyRemaining: 199642,
// dailyResetMs: 84322000 // only when the API reports it
// }
if (error.rateLimit?.scope === 'daily') {
// stop sending requests until the daily limit resets
}
}
}
示例:125 getContact 在每10秒100个请求的限制下,立即发出电话。 超过限量的呼叫收到429次
const results = await Promise.allSettled(
Array.from({ length: 125 }, () =>
ghl.contacts.getContact({ contactId }, { headers: { locationId } })
)
);
// [GHL SDK] WARN: 429 Too Many Requests - burst limit reached, retrying in 10000ms (attempt 1 of 3) { scope: 'burst', intervalMs: 10000, max: 100, remaining: 0, ... }
// results: 125 fulfilled, 0 rejected, in about 11.5 seconds
网络呼号
处理带有内置签名验证的高级网络用户。 中间软件还处理用于您的应用程序的INSTALL和UNINSTALL事件:
- 在大宗安装的情况下,它将为启动安装的所有地点生成并储存代号
- UNINSTALL: 如果您的应用程序未在任何地点或公司安装, 它将会从 SDK 使用的存储中移除该资源的符号
页:1: 您使用的终点应该是配置为 Default Webhook URL 在市场申请。 INSTALL和UNINSTALL事件仅被发送到默认的URL.
中间软件与Express合作 以及任何称之为Express的框架 (req, res, next) 与 req.headers 财务报告和审定财务报表 req.body. Express不是SDK的属地.
import express from 'express';
const app = express();
// Keep the raw body so the signature is checked against the exact bytes HighLevel signed
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));
// SDK middleware processes the webhook first
app.use('/webhooks/ghl', ghl.webhooks.subscribe());
// Your handler runs after SDK processing
app.post('/webhooks/ghl', async (req, res) => {
if (req.skippedSignatureVerification) {
// no x-ghl-signature header on the request, or no public key configured
}
if (req.isSignatureValid === false && !req.skippedSignatureVerification) {
return res.status(401).json({ success: false }); // signature present but invalid
}
if (req.installTokenError) {
// INSTALL webhook was verified but the location token could not be generated
}
// your logic for the webhook goes here
res.json({ success: true });
});
签字核查
高层用 Ed25519 标记每个网页并发送签名 x-ghl-signature 头曰. 提供来自建筑商或通过建筑商市场的公用钥匙 WEBHOOK_SIGNATURE_PUBLIC_KEY 环境变量。 PEM,生基64和六分位编码被接受:
const ghl = new HighLevel({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
sessionStorage,
webhookPublicKey: process.env.WEBHOOK_SIGNATURE_PUBLIC_KEY
});
中间软件在您的处理器请求上设置了这些标记 :
| 旗帜 | 含义 |
|---|---|
isSignatureValid | true 何时 x-ghl-signature 根据配置的公钥校验 |
skippedSignatureVerification | true 当信头或公用密钥缺失时, 没有被证实 |
installTokenError | 设定一个 INSTALL webhook 已验证但生成位置符失败时 |
INSTALL和UNINSTAL只有在签名有效时才进行处理. 网络用户 appId 不属于你的 clientId 未经处理即可通过。 中间的软件永远不会结束反应,所以你的处理器总是运行并决定返回什么.
为了验证签名:
const isValid = ghl.webhooks.verifyEd25519Signature(rawBody, req.headers['x-ghl-signature'] as string, publicKey);
遗产 x-wh-signature 页眉(RSA)不再由高端发送,也不由中端软件检查. 这个 WEBHOOK_PUBLIC_KEY 环境变量不再读取,并且 verifySignature() ,并仅用于后向相容性.
日志
logLevel 控制SDK日志的多少(LogLevel.ERROR, (中文(简体) ), LogLevel.WARN, (中文(简体) ), LogLevel.INFO, (中文(简体) ), LogLevel.DEBUG) (中文(简体) ). 时 DEBUG 每一个请求、响应和网络记录的有效载荷都记录下来.
授权信头、令牌、客户机密和类似值被替换为 [REDACTED] 在这些日志和 request 附加在抛出的错误上。 要看到真实值, 例如在本地调试认证时, 选择使用 logSensitiveData数字 :
const ghl = new HighLevel({
privateIntegrationToken: 'your-token',
logLevel: LogLevel.DEBUG,
logSensitiveData: true // default false. Do not enable in production
});
用法实例
页:1:如果companyId或locationId是查询,正文或标题参数的一部分,那么就不需要具体通过. 但如果不是,那么你需要通过它 在信头如下所示.
与联系人合作
获得单一联系人
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);
}
获取多个联系人
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);
}
与其他服务部门合作
地点
// 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'
}
)
运动
// Get campaigns
const campaigns = await ghl.campaigns.getCampaigns({
locationId: 'location-id'
});
处理错误
SDK的每个错误都是 GHLError 与 message, (中文(简体) ), statusCode时,API response被消毒的动物 request 和一个机器可读 codeHTTP 失败被抛出作为子类,这样您就可以与 instanceof数字 :
| 类 | code | 丢弃 |
|---|---|---|
GHLAuthenticationError | AUTHENTICATION | 401 当令牌无效且无法刷新时 |
GHLForbiddenError | FORBIDDEN | 403 (韩语) |
GHLNotFoundError | NOT_FOUND | 404 (韩语) |
GHLValidationError | VALIDATION | 400和422个 |
GHLRateLimitError | RATE_LIMIT | 429, 解析页眉为 rateLimit (见 速率限制重试(中文(简体) ) |
GHLServerError | SERVER | 5 (简体中文) |
GHLNetworkError | NETWORK | 未收到回复( 超时、 DNS 故障、 连接被拒绝) |
GHLError | REQUEST, (中文(简体) ), UNKNOWN | 无法发送请求, 或任何其他状态代码 |
import {
GHLError,
GHLAuthenticationError,
GHLNotFoundError,
GHLRateLimitError,
GHLNetworkError
} from '@gohighlevel/api-client';
try {
const contact = await ghl.contacts.getContact({
contactId: 'invalid-contact-id'
});
} catch (error) {
if (error instanceof GHLNotFoundError) {
console.log('Contact not found');
} else if (error instanceof GHLAuthenticationError) {
console.log('Authentication failed - check your tokens');
} else if (error instanceof GHLRateLimitError) {
console.log('Rate limited', error.rateLimit);
} else if (error instanceof GHLNetworkError) {
console.log('Could not reach the API', error.message);
} else if (error instanceof GHLError) {
console.error('GHL API Error:', {
code: error.code,
message: error.message,
statusCode: error.statusCode,
response: error.response,
request: error.request
});
} else {
console.error('Unexpected error:', error);
}
}
针对先前版本所写的代码继续工作: 每个子类扩展 GHLError报告 name === 'GHLError' 却依然暴露 statusCode这样 switch (error.statusCode) 样式处理不变.
授权信头和其他机密从 error.request 除非 logSensitiveData 已启用(参见 日志) (中文(简体) ).
类型脚本支持
SDK是用 TypeScript 构建的,提供了完整的类型定义 :
import HighLevel, {
HighLevelConfig,
ValidConfig,
RateLimitRetryConfig,
RateLimitInfo,
GHLError,
GHLErrorCode,
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
API 参考
SDK提供所有高级API服务. 每一个都作为财产存在 HighLevel 实例:
- 广告管理员 - 广告出版和报告
- 附属经理 - 附属经理
- 代理服务器 - 工作室探员
- 协会 - 联系协会
- 博客 - 博客管理
- 品牌董事会 - 品牌董事会
- 商业 - 业务
- 日历 - 日历和任命管理
- 运动 - 营销活动
- 聊天窗口 - 聊天部件管理
- 企业 - 公司/机构管理
- 联系人 - 联系管理
- 对话 - 对话AI
- 对话 - 谈话和通讯
- 课程 - 课程管理
- 自定义字段 - 自定义字段
- 自定义菜单 - 自定义菜单管理
- 电子邮件Isv - 电子邮件核查
- 电子邮件 - 电子邮件模板和活动
- 文件 - 文件访问
- 表单 - 表格管理
- 漏斗 - 漏斗操作
- 发票 - 发票管理
- 知识库 - 知识基础
- 链接 - 链接管理
- 地点 - 地点管理
- 市场 - 采购网业务
- 媒体 - 媒体文件管理
- 欧斯 - OAuth 2.0操作
- 对象 - 自定义对象管理
- 机会 - 管道和机会管理
- 付款 - 付款处理
- 电话系统 - 电话号码和电话池
- 产品 - 产品管理
- 建议 - 提案和概算
- 萨斯阿皮 - SaaS管理
- 快照 - 快照操作
- 社交媒体 - 社会规划员
- 存储 - 在线商店设置
- 调查 - 调查管理
- 用户 - 用户管理
- 语音Ai - 语音AI
- 工作流程 - 工作流程自动化
网络锁定中间软件作为 ghl.webhooks (见 网络呼号) (中文(简体) ).
配置方法
// 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');
高级使用
自定义拦截器
// Add request interceptor
const requestInterceptorId = ghl.addRequestInterceptor({
onFulfilled: (config) => {
console.log('Making request to:', config.url);
return config;
},
onRejected: (error) => {
console.error('Request error:', error);
return Promise.reject(error);
}
});
// Add response interceptor
const responseInterceptorId = ghl.addResponseInterceptor({
onFulfilled: (response) => {
console.log('Received response:', response.status);
return response;
},
onRejected: (error) => {
console.error('Response error:', error);
return Promise.reject(error);
}
});
// Remove interceptors when done
ghl.removeRequestInterceptor(requestInterceptorId);
ghl.removeResponseInterceptor(responseInterceptorId);
原始 HTTP 请求
// Make custom HTTP requests using the configured client
const response = await ghl.request({
method: 'GET',
url: '/custom-endpoint',
params: { locationId: 'location-id' }
});
// Get underlying Axios instance for advanced usage
const httpClient = ghl.getHttpClient();
支助
许可证
麻省理工学院的执照 - 看 自由主义 详细文件.