高级API SDK
TypeScript SDK用于与高级API v1和v2端点合作. 与任何服务器侧JS运行时间合作,包括Node.js, Bun, Cloudflare工人等.
为什么要用这个SDK?
高级API经常有变化. 每周都会有一个GitHub Action检查 官方高级 API 文件库它使用 openapi 类型标记 生成端点类型.
当计划改变时,动作检查包. 如果检查通过,它会发布一个新的小版本到npm,并创建一个GitHub发行. 动作运行摘要并发布注释列表添加,更改,并去除操作和计划. 此放行后可提供新类型.
特征
- 对OAuth和 私人融入
- 完全输入的客户端 SDK( 使用本地
fetch与 openapi 牵引 - OAuth2 协助执行高级OAuth2
- 在您的应用程序中方便添加相应范围的范围构建器
- 使用输入事件处理器的 Webhooks 客户端
- 支持 v1( legacy API 密钥) 和 v2( OAuth 和私人 集成)
资源
安装
bun add @gnosticdev/highlevel-sdk
# or
pnpm add @gnosticdev/highlevel-sdk
# or
npm add @gnosticdev/highlevel-sdk
使用量
使用高级客户端
高端客户端默认使用v2 API(见下文v1客户端). 它可以通过不同的配置来创建:
-
基本客户端: 通过一个
openapi-fetch客户端配置作为第一个参数。 设置客户端默认发送的基准 URL 和信头 .import { createHighLevelClient } from '@gnosticdev/highlevel-sdk' const client = createHighLevelClient({ baseUrl: 'https://services.leadconnectorhq.com', headers: { Authorization: `Bearer ${process.env.HIGHLEVEL_API_TOKEN!}`, Version: '2021-07-28', }, }) -
OAuth 客户端: 需要 OAuth 配置.
// The first argument is the openapi-fetch client config. const client = createHighLevelClient({ baseUrl: 'https://services.leadconnectorhq.com', }, 'oauth', { clientId: 'your-client-id', clientSecret: 'your-client-secret', redirectUri: 'http://localhost:3000/callback', accessType: 'Sub-Account', scopes: ['contacts.readonly'], }) -
有私人融合的客户端:需要私人集成配置.
const client = createHighLevelClient({ baseUrl: 'https://services.leadconnectorhq.com', }, 'integration', { privateToken: process.env.HIGHLEVEL_PRIVATE_TOKEN!, accessType: 'Agency', })
选择认证方法
使用一个自定义集成系统( PIT) 来运行一个高级机构或子账户 。 一个管理员在高级设置中创建了符并在那里选择其范围. 把信物放在服务器上 这个SDK添加了 Authorization 财务报告和审定财务报表 Version 每个请求的页眉。 您不需要在每次通话中添加这些信头 .
HighLevel目前的文档显示在账户设置中如何创建 PIT 。 它们不记录创建 PIT 的 API 。 SDK不能为每个客户创建一个. 高层将PIT描述为固定符号,并建议您每90天旋转一次. 见 私人融入。 。 。 .
在构建用户安装和批准的应用程序时使用 OAuth 。 Highlevel在用户批准应用程序后发布指使. 这对双方都有用 私人应用程序 财务报告和审定财务报表 公共应用程序. Private App 是 OAuth 应用程序类型. 这不是私人一体化。 当每个客户必须批准进入自己的账户时,OAuth是正确的选择。 每个新刷新令牌在刷新后保存 。 见 OAuth 2.0 数据。 。 。 .
Highlevel的docs没有说PIT是每个应用程序的首选. 选择符合应用程序如何访问的符号类型 .
处理错误
SDK使用过 openapi-fetch 在引擎盖下,它返回两个 data 财务报告和审定财务报表 error 用于类型安全错误处理的属性.
import { createHighLevelClient } from '@gnosticdev/highlevel-sdk'
// Create client with OAuth2 support
const client = createHighLevelClient({
baseUrl: 'https://services.leadconnectorhq.com',
}, 'oauth', {
clientId: process.env.HIGHLEVEL_CLIENT_ID!,
clientSecret: process.env.HIGHLEVEL_CLIENT_SECRET!,
redirectUri: 'http://localhost:3000/oauth/callback',
accessType: 'Sub-Account',
scopes: ['contacts.readonly'],
// Optional: store tokens in your database
storageFunction: async (tokenData) => {
await db.saveTokenResponse({
access_token: tokenData.access_token,
expiresAt: tokenData.expiresAt,
refresh_token: tokenData.refresh_token,
locationId: tokenData.locationId,
userId: tokenData.userId,
})
return tokenData
},
})
async function handleOAuthCallback(request: Request) {
const authCode = new URL(request.url).searchParams.get('code')
if (!authCode) {
throw new Error('HighLevel did not return an auth code')
}
// Exchange the code and store the token data.
const accessToken = await client.oauth.getAccessToken(authCode)
if (!accessToken) {
throw new Error('HighLevel did not return an access token')
}
// OAuth endpoint calls need the current access token and API version.
const { data, error } = await client.contacts.GET('/contacts/', {
params: {
header: {
Authorization: `Bearer ${accessToken}`,
Version: '2021-07-28',
},
query: {
locationId: '1234567890',
query: 'John Doe',
limit: 10,
},
},
})
if (error) {
console.error('Error fetching contacts:', error.message)
return
}
console.log(data.contacts)
}
OAuth2 辅助
OAuth 客户端在使用 OAuth 配置创建时, 可以在高级客户端实例中获取 :
// Generate authorization URL
const authUrl = client.oauth.getAuthorizationUrl()
// Exchange the auth code and store the token data
const accessToken = await client.oauth.getAccessToken(authCode)
// Later calls refresh the access token when needed
const currentAccessToken = await client.oauth.getAccessToken()
传出访问符 Authorization 每个 OAuth API 调用的标题 。 OAuth 客户端默认情况下存储符以内存. 使用 storageFunction 在数据库中保存符号。 当您创建新客户端时, 请从您的数据库中装入保存的符号数据并将其传递给 client.oauth.storeTokenData() 在你打电话之前 getAccessToken()。每次刷新后保存新的刷新令牌.
使用 v1 客户端
V1客户端需要API密钥,并自动在所有请求中添加授权头.
import { createHighLevelV1Client } from '@gnosticdev/highlevel-sdk/v1'
const v1Client = createHighLevelV1Client({
apiKey: process.env.HIGHLEVEL_API_KEY!,
})
const { data, error } = await v1Client.GET('/v1/contacts', {
params: {
query: {
locationId: '1234567890',
},
// No need to add Authorization header - it's added automatically
},
})
if (error) {
console.error('Error fetching contacts:', error)
return
}
console.log(data.contacts)
使用 Webhooks 客户端
Webhooks客户端允许您用打出的有效载荷注册处理器:
import { createWebhooksClient } from '@gnosticdev/highlevel-sdk/webhooks'
const webhooks = createWebhooksClient()
webhooks.on('ContactCreate', async (payload) => {
// TypeScript knows the fields in this ContactCreate payload.
console.log('Contact created:', payload.firstName, payload.lastName)
})
在您的 HTTP 路由中, 验证签名并解析请求正文 。 检查事件名称, 然后打电话 webhooks.handle('ContactCreate', payload) 与事件的有效载荷。 SDK检查该有效载荷是否为物体并存在处理器. 它不核查签名或验证每个有效载荷场.
Highlevel 的当前 Webhook 指南使用 X-GHL-Signature 头与Ed25519. 客户端将当前公钥曝光为 webhooks.WEBHOOK_GHL_PUBLIC_KEY_PEM老年人 webhooks.WEBHOOK_PUBLIC_KEY_PEM 属性是遗留的 RSA 密钥。 见 webhook 签名指南。 。 。 .
Webhook 签名验证
关于Webhook签名验证和有效载荷解析的节点,请参见 Webhook 签名验证和有效载荷分析指南。签名验证码不包含在 SDK 中,因此它可以支持使用不同加密API的运行时间.
端点类型
如果您想要为 API 端点获得类型, 您可以像这样使用 :
import type * as Locations from '@gnosticdev/highlevel-sdk/types/locations'
// Example: the response type for `GET /locations/{locationId}/customValues`
type LocationCustomValues = NonNullable<
Locations.operations['get-custom-values']['responses']['200']['content']['application/json']['customValues']
>
const customValues: LocationCustomValues = [{
fieldKey: 'contact.lead_source',
id: 'lead_source_id',
locationId: 'my_location_id',
name: 'Lead Source',
value: 'Google',
}]
创建自定义客户端
您可以使用 createClient 函数从 openapi-fetch 带有此软件包中的特定端点类型。 当您只需要 API 端点的子集或想要创建更集中的客户端时,此功能是有用的 .
import { createClient } from '@gnosticdev/highlevel-sdk'
import type * as CustomMenus from '@gnosticdev/highlevel-sdk/types/custom-menus'
// Create a client with only custom menu endpoints
type CustomMenuPaths = CustomMenus.paths
const client = createClient<CustomMenuPaths>({
headers: {
Authorization: `Bearer ${process.env.HIGHLEVEL_API_TOKEN!}`,
Version: '2021-07-28',
},
})
// Use the client with full type safety
const { data, error } = await client.GET('/custom-menus/', {
params: {
header: {
Version: '2021-07-28',
},
query: {
locationId: '1234567890',
},
},
})
if (error) {
console.error('Error:', error)
return
}
console.log(data)
您也可以结合多个端点类型,用自定义的端点集创建客户端:
import { createClient } from '@gnosticdev/highlevel-sdk'
import type * as CustomMenus from '@gnosticdev/highlevel-sdk/types/custom-menus'
import type * as Contacts from '@gnosticdev/highlevel-sdk/types/contacts'
// Combine multiple endpoint types
type CustomMenuPaths = CustomMenus.paths & Contacts.paths
const client = createClient<CustomMenuPaths>({
headers: {
Authorization: `Bearer ${process.env.HIGHLEVEL_API_TOKEN!}`,
Version: '2021-07-28',
},
})
说明: 这个 createClient 函数从此软件包导出, 并且是相同的 openapi-fetch 客户端。 配置中通过的信头是请求默认值 。 一个操作仍然需要一个标题 params.header 用于TypeScript,如上所示。 您可以在此覆盖默认信头 .
模块导出
SDK提供多个模块输出,以更好地组织并震动树:
// Main client
import { createHighLevelClient } from '@gnosticdev/highlevel-sdk'
// OAuth client implementation
import { OauthClientImpl } from '@gnosticdev/highlevel-sdk/oauth'
// Scopes builder
import { ScopesBuilder } from '@gnosticdev/highlevel-sdk/scopes'
// V1 API client
import { createHighLevelV1Client } from '@gnosticdev/highlevel-sdk/v1'
// Webhooks client
import { createWebhooksClient } from '@gnosticdev/highlevel-sdk/webhooks'
// Types
import type * as Locations from '@gnosticdev/highlevel-sdk/types/locations'
范围
对于OAuth,请在高级市场里将范围添加到您的应用程序中. 使用 ScopesBuilder 收集对机构或子账户应用有效的范围:
import { createHighLevelClient } from '@gnosticdev/highlevel-sdk'
import { ScopesBuilder } from '@gnosticdev/highlevel-sdk/scopes'
const scopeBuilder = new ScopesBuilder('Sub-Account')
scopeBuilder.add(['contacts.readonly', 'locations.readonly'])
const client = createHighLevelClient({
baseUrl: 'https://services.leadconnectorhq.com',
}, 'oauth', {
clientId: process.env.HIGHLEVEL_CLIENT_ID!,
clientSecret: process.env.HIGHLEVEL_CLIENT_SECRET!,
redirectUri: 'http://localhost:3000/callback',
accessType: 'Sub-Account',
scopes: [...scopeBuilder.collection],
})
TypeScript 对照选定的访问类型检查范围名称 。 构建者不会在您的高端应用中添加范围或授予访问权限 。 高层设置了当管理员创建指针时的私有集成托肯范围.
实例
请检查date=中的日期值 (帮助) 示例目录数字 :
examples/bun-auth: OAuth2 使用 Bun 和 Hono 认证流程示例- 很快会有更多例子出现!
捐款
欢迎捐款! 请随意提交拉力请求.
许可证
这个项目根据麻省理工学院许可证颁发——见 自由主义 详细文件.