# @gnosticdev/highlevel-sdk 中文文档

规范地址：https://npmcn.com/package/%40gnosticdev/highlevel-sdk/

版本：4\.4\.0
npm 元数据更新时间：2026-11-09T20:34:21.998Z
中文译文更新时间：2026-11-16T17:27:05.573Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gnosticdev/highlevel-sdk
原文对照：https://npmcn.com/package/%40gnosticdev/highlevel-sdk/?lang=original
项目主页：https://github.com/gnosticdev/highlevel-api-sdk
源码仓库：https://github.com/gnosticdev/highlevel-api-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.5 MB，145 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：openapi-fetch ^0\.13\.8
- 首次发布：2024-10-11T21:20:32.480Z
- 最新版本发布：2026-11-09T20:34:21.662Z
- 近 30 天下载量：4911（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：31（近 12 个月 8 个）

## 中文简介

高级API 的 SDK

## 安装

```sh
npm install @gnosticdev/highlevel-sdk
```

也可以使用：`pnpm add @gnosticdev/highlevel-sdk`、`yarn add @gnosticdev/highlevel-sdk`、`bun add @gnosticdev/highlevel-sdk`

## README

# 高级API SDK

[![npm version](https://badge.fury.io/js/%40gnosticdev%2Fhighlevel-sdk.svg)](https://badge.fury.io/js/%40gnosticdev%2Fhighlevel-sdk) [![npm downloads](https://img.shields.io/npm/dm/@gnosticdev/highlevel-sdk.svg)](https://www.npmjs.com/package/@gnosticdev/highlevel-sdk)

TypeScript SDK用于与高级API v1和v2端点合作. 与任何服务器侧JS运行时间合作,包括Node.js, Bun, Cloudflare工人等.

## 为什么要用这个SDK?

高级API经常有变化. 每周都会有一个GitHub Action检查 [官方高级 API 文件库](https://github.com/GoHighLevel/highlevel-api-docs)它使用 [openapi 类型标记](https://openapi-ts.dev/introduction) 生成端点类型.

当计划改变时,动作检查包. 如果检查通过,它会发布一个新的小版本到npm,并创建一个GitHub发行. 动作运行摘要并发布注释列表添加,更改,并去除操作和计划. 此放行后可提供新类型.

## 特征

-   对OAuth和 [私人融入](https://marketplace.gohighlevel.com/docs/Authorization/PrivateIntegrationsToken)
-   完全输入的客户端 SDK( 使用本地 `fetch`与 [openapi 牵引](https://openapi-ts.dev/openapi-fetch/)
-   OAuth2 协助执行高级OAuth2
-   在您的应用程序中方便添加相应范围的范围构建器
-   使用输入事件处理器的 Webhooks 客户端
-   支持 v1( legacy API 密钥) 和 v2( OAuth 和私人 集成)

## 资源

-   [API v2 文档](https://marketplace.gohighlevel.com/docs/) (Outh和Private Integrations) (英语)
-   [API v1 文档](https://public-api.gohighlevel.com/) (Legacy API键)

## 安装

```bash
bun add @gnosticdev/highlevel-sdk
# or
pnpm add @gnosticdev/highlevel-sdk
# or
npm add @gnosticdev/highlevel-sdk
```

## 使用量

### 使用高级客户端

高端客户端默认使用v2 API(见下文v1客户端). 它可以通过不同的配置来创建:

-   **基本客户端**: 通过一个 `openapi-fetch` 客户端配置作为第一个参数。 设置客户端默认发送的基准 URL 和信头 .
    
    ```ts
    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 配置.
    
    ```ts
    // 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'],
    })
    ```
    
-   **有私人融合的客户端**:需要私人集成配置.
    
    ```ts
    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天旋转一次. 见 [私人融入](https://marketplace.gohighlevel.com/docs/Authorization/PrivateIntegrationsToken)。 。 。 .

在构建用户安装和批准的应用程序时使用 OAuth 。 Highlevel在用户批准应用程序后发布指使. 这对双方都有用 **私人应用程序** 财务报告和审定财务报表 **公共应用程序**. Private App 是 OAuth 应用程序类型. 这不是私人一体化。 当每个客户必须批准进入自己的账户时,OAuth是正确的选择。 每个新刷新令牌在刷新后保存 。 见 [OAuth 2.0 数据](https://marketplace.gohighlevel.com/docs/Authorization/OAuth2.0)。 。 。 .

Highlevel的docs没有说PIT是每个应用程序的首选. 选择符合应用程序如何访问的符号类型 .

### 处理错误

SDK使用过 `openapi-fetch` 在引擎盖下,它返回两个 `data` 财务报告和审定财务报表 `error` 用于类型安全错误处理的属性.

```ts
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 配置创建时, 可以在高级客户端实例中获取 :

```ts
// 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密钥,并自动在所有请求中添加授权头.

```ts
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客户端允许您用打出的有效载荷注册处理器:

```ts
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 签名指南](https://npmcn.com/package/%40gnosticdev/highlevel-sdk/docs/decrypt-payload.md)。 。 。 .

#### Webhook 签名验证

关于Webhook签名验证和有效载荷解析的节点,请参见 [Webhook 签名验证和有效载荷分析指南](https://npmcn.com/package/%40gnosticdev/highlevel-sdk/docs/decrypt-payload.md)。签名验证码不包含在 SDK 中,因此它可以支持使用不同加密API的运行时间.

### 端点类型

如果您想要为 API 端点获得类型, 您可以像这样使用 :

```ts
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 端点的子集或想要创建更集中的客户端时,此功能是有用的 .

```ts
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)
```

您也可以结合多个端点类型,用自定义的端点集创建客户端:

```ts
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提供多个模块输出,以更好地组织并震动树:

```ts
// 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` 收集对机构或子账户应用有效的范围:

```ts
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=中的日期值 (帮助) [示例目录](https://npmcn.com/package/%40gnosticdev/highlevel-sdk/examples)数字 :

-   `examples/bun-auth`: OAuth2 使用 Bun 和 Hono 认证流程示例
-   很快会有更多例子出现!

## 捐款

欢迎捐款! 请随意提交拉力请求.

## 许可证

这个项目根据麻省理工学院许可证颁发——见 [自由主义](https://npmcn.com/package/%40gnosticdev/highlevel-sdk/LICENSE) 详细文件.

## 常见问题

### @gnosticdev/highlevel-sdk 是什么？

高级API 的 SDK

### 如何安装 @gnosticdev/highlevel-sdk？

在项目目录运行 npm install @gnosticdev/highlevel-sdk，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：openapi-fetch（^0\.13\.8）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @gnosticdev/highlevel-sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gnosticdev/highlevel-sdk 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @gnosticdev/highlevel-sdk 可以商用吗？

@gnosticdev/highlevel-sdk 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gnosticdev/highlevel-sdk 的下载量有多少？

根据 npm 官方下载统计，@gnosticdev/highlevel-sdk 在 2026/10/17 – 2026/11/15 这 30 天内被下载 4,911 次，日均约 164 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gnosticdev/highlevel-sdk 还在维护吗？

最新版本 4\.4\.0 发布于 2026/11/10（6 天前）；至今共发布 31 个版本，其中过去 12 个月发布了 8 个；首次发布于 2024/10/12。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

