@commercelayer/provisioning-sdk

中文文档
3.0.2发布于 2026/11/10MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 2073

提供 API Javascript SDK

中文使用文档
文档目录19 节
  1. 目录
  2. 开始
  3. 安装
  4. 认证
  5. 导入
  6. 选项
  7. API 版本
  8. SDK 使用情况
  9. 创建
  10. 获取/ 列表
  11. 更新
  12. 删除
  13. 逾越全权证书
  14. 处理验证错误
  15. 使用截取器
  16. 刷新访问令牌
  17. 贡献者指南
  18. 需要帮忙吗?
  19. 许可证

提供SDK

Version Downloads/week License Verify CodeQL TypeScript

一个 JavaScript 库包装器, 使其能快速且容易地与 商业层提供 API。 。 。 .

此软件包来自 commercelayer-sdk 单相并列 @commercelayer/sdk两者均由API自己出版的图案的同一发电机生产.

目录


开始

要从商业层提供SDK开始,您需要安装它,获得允许您执行API呼叫的证书,并将SDK导入您的应用程序代码. 以下各节解释了如何实现这一目标.

安装

提供SDK作为一种 无 财务报告和审定财务报表 线条 下列命令可以安装的软件包:

npm install @commercelayer/provisioning-sdk

// or

yarn add @commercelayer/provisioning-sdk

认证

所有对商业层 API 的请求必须使用 OAuth2 证书 无记名符. 因此,在开始使用SDK之前,你需要获得有效的访问符. 请检查 我们的文件 关于现有授权流量的更多信息.

随便用吧 商业层,一个 JavaScript 库,可以帮助您包装我们的认证 API.

导入

您可以像这样使用 SDK 的 ES6 默认导入 :

import CommerceLayerProvisioning from '@commercelayer/provisioning-sdk'

const clp = CommerceLayerProvisioning({
  accessToken: 'your-access-token',
  apiVersion: '2026-05'
})

选项

当即时处理一个新的 SDK 客户端时, 您可以通过一些选项来初始化它 :

{
  accessToken: string         // A valid API access token
  apiVersion: ApiVersion      // The API version to target, e.g. '2026-05' — required, see API version below
  timeout?: number            // A custom request timout (<= 15 secs [default])
  headers?: RequestHeaders    // Custom request headers
  userAgent?: string          // Custom user-agent useful in certaing contexts but often not allowed by browsers
  fetch?: Fetch               // A specific fetch implementation 
  refreshToken?: RefreshToken // A function responsible for token refresh
}

相同的选项可以在 SDK 初始化后更改或在运行时通过,同时执行 API 调用 :

  const options = { ... }

  // Instantiate the client using desired options
  const clp = CommerceLayerProvisioning(options)

  // Change configuration after client cteation
  clp.config(options)

  // Use runtime configuration without persisting settings
  clp.organizations.list({}, options)

API 版本

提供API版本,每个请求都针对一个版本. apiVersion 因此为 所需经费 当创建客户端时,并成为每个请求 URL 的一部分 - /api/2026-05/organizations。 。 。 .

只有SDK的这个发布所生成的版本被接受;任何其他值都是类型错误. 两者均导出:

import { API_SCHEMA_VERSION, API_SUPPORTED_VERSIONS } from '@commercelayer/provisioning-sdk'

API_SUPPORTED_VERSIONS // ['2026-05'] — the versions you can target
API_SCHEMA_VERSION     // '2026-05' — the version the types describe

[大 从 2. x 升级 : apiVersion 是新的和需要的,所以每个 CommerceLayerProvisioning(...) 电话需要它.

SDK 使用情况

JavaScript 提供 SDK 是一个围绕商业层提供 API 的包装器,这意味着您仍然会提出 API 请求,但使用不同的语法. 现在,我们没有全面的SDK文件 每一个资源,我们的API支持, 所以你需要依赖我们的全面 提供 API 参考 当你继续使用这个SDK。 例如,如果你想创造一个角色,请看看 角色对象 或 创建角色 用于查看所需属性和/或关系的文档。 所有其他支助资源也是如此.

下面的代码片段显示在进行由我们的REST API提供的标准CRUD操作时如何使用SDK. 请检查我们的 提供 API 参考 完整清单 资源 联合国 属性。 。 。 .

创建

如何创建角色
  // Select the organization (it's a required relationship for the SKU resource)
  const organizations = await clp.organizations.list({ filters: { name_eq: 'Test Org' } })

  const attributes = {
    name: 'Test Role',
    organization: clp.organizations.relationship(organizations.first().id), // assigns the relationship
  }

  const newRole = await clp.roles.create(attributes)

请检查access-date=中的日期值 (帮助) 创建角色。 。 。 .

获取/ 列表

如何找到一个单一的组织
  // Fetch the organization by ID
  const org = await clp.organizations.retrieve('BxAkSVqKEn')

  // Fetch all organizations and filter by name
  const orgs = await clp.organizations.list({ filters: { name_start: 'TestOrg_' } })

  // Fetch the first organization of the list
  const org = (await clp.organizations.list()).first()

  // Fetch the last organization of the list
  const org = (await clp.organizations.list()).last()

请检查access-date=中的日期值 (帮助) 获取组织。 。 。 .

如何收集一批组织
  // Fetch all the organizations
  const orgs = await clp.organizations.list()

获取资源时,您可以使用 meta 属性以获取 meta 此类信息:

  const orgs = await clp.organizations.list()
  const meta = orgs.meta

请检查access-date=中的日期值 (帮助) 列出全部 SKU。 。 。 .

如何收集组织资料并排序结果
  // Sort the results by creation date in ascending order (default)
  const orgs = await clp.organizations.list({ sort: { created_at: 'asc' } })

  // Sort the results by creation date in descending order
  const orgs = await clp.organizations.list({ sort: { created_at: 'desc' } })

请检查access-date=中的日期值 (帮助) 排序结果。 。 。 .

如何收集会员名单并包括协会
  // Include an association (organization)
  const mships = await clp.memberships.list({ include: [ 'organization' ] })

  // Include an association (stock role)
  const mships = await clp.memberships.list({ include: [ 'role' ] })

请检查access-date=中的日期值 (帮助) 包括协会。 。 。 .

如何获取权限集并返回特定字段( sparse 字段)
  // Request the API to return only specific fields
  const perms = await clp.permissions.list({ fields: { permissions: [ 'can_create', 'can_update' ] } })

  // Request the API to return only specific fields of the included resource
  const mships = await clp.memberships.list({ include: [ 'organization' ], fields: { organizations: [ 'name' ] } })

请检查access-date=中的日期值 (帮助) 使用稀有字段。 。 。 .

如何收集组织资料和过滤数据
  // Filter all the organizations fetching only the ones whose name starts with the string "ORG"
  const orgs = await clp.organizations .list({ filters: { name_start: 'ORG' } })

  // Filter all the organizations fetching only the ones whose name ends with the string "Brand"
  const orgs = await clp.organizations.list({ filters: { name_end: 'Brand' } })

  // Filter all the organizations fetching only the ones whose name contains the string "Test"
  const orgs = await clp.organizations.list({ filters: { name_cont: 'Test' } })

  // Filter all the organizations fetching only the ones created between two specific dates
  // (filters combined according to the AND logic)
  const orgs = await clp.organizations.list({ filters: { created_at_gt: '2018-01-01', created_at_lt: '2018-01-31'} })

  // Filters all the organizations fetching only the ones created or updated after a specific date
  // (attributes combined according to the OR logic)
  const orgs = await clp.organizations.list({ filters: { updated_at_or_created_at_gt: '2019-10-10' } })

  // Filters all the Roles fetching only the ones whose name contains the string "Admin"
  // and whose organization name starts with the string "ORG"
  const roles = await clp.roles.list({ filters: { name_cont: 'Admin', organization_name_start: 'ORG'} })

请检查access-date=中的日期值 (帮助) 过滤数据。 。 。 .

如何培养一批组织

当您获取到资源时, 就会得到标定结果 。 您可以在类似页面中请求特定的页面或项目:

  // Fetch the organizations, setting the page number to 3 and the page size to 5
  const skorgsus = await clp.organizations.list({ pageNumber: 3, pageSize: 5 })

  // Get the total number of organizations in the collection
  const orgCount = orgs.meta.recordCount

  // Get the total number of pages
  const pageCount = orgs.meta.pageCount

PS: 默认的页码是 1个,默认页面大小为 10个,允许的最大页面大小为 第25条。 。 。 .

请检查access-date=中的日期值 (帮助) 标记 工作时.

如何通过组织汇编来推展

要为收藏的每个项目执行函数,请使用 map() 这样的方法 :

  // Fetch the whole list of organizations (1st page) and print their ids and names to console
  const orgs = await clp.organizations.list()
  orgs.map(o => console.log('ID: ' + o.id + ' - Name: ' + o.name))
如何获取资源关系

许多资源与其它资源有关系,您可以直接获取,而不是将上述这些协会包括在内。 这样,对于一对一N关系,可以过滤或排序产生的集合作为标准资源.

// Fetch 1-to-1 related resource: billing address of an order
const org = await clp.memberships.organization('xYZkjABcde')

// Fetch 1-to-N related resources: orders associated to a customer
const perms = await clp.roles.permissions('XyzKjAbCDe', { fields: ['can_create', 'can_update'] })

总的来说:

  • API 等端点 /api/organizations 或者说 /api/organization/<organizationId> 翻译为 clp.organizations 或者说 clp.organizations('<organizationId>') 还有SDK.
  • 1比1关系 API 等端点 /api/roles/<roleId>/organization 翻译为 clp.roles('<roleId>', { include: ['organization'] }} 还有SDK.
  • 1-N关系 API 等 /api/roles/<roleId>?include=versions 或者说 /api/roles/<roleId>/permissions 翻译为 clp.roles.retrieve('<roleId>', { include: ['versions'] }) 或者说 clp.roles.permissions('<roleId>') 还有SDK.

请检查access-date=中的日期值 (帮助) 获取关系。 。 。 .

如何计算资源

很多次你只需要数一下有多少资源 某些特征 你可以叫特别的 count 函数通过过滤器以获取结果的总数 资源.

// Get the total number of sales_channel credentials
const credentials = await clp.api_credentials.count({ filters: { kind_eq: 'sales_channel' } })

更新

如何更新现有组织
  const org = {
    id: 'xYZkjABcde',
    reference: '<new-reference>',
    reference_origin: '<new-reference-origin>'
  }

  clp.organizations.update(org) // updates the SKU on the server

请检查access-date=中的日期值 (帮助) 更新一个组织。 。 。 .

删除

如何删除现有成员
  clp.memberships.delete('xYZkjABcde') // persisted deletion

请检查access-date=中的日期值 (帮助) 删除成员。 。 。 .

逾越全权证书

如果需要,商务层提供SDK允许您更改客户端配置并设置在请求级别. 要做到这一点,只是使用 config() 方法或通过 options 参数并认证 API 调用 :

  // Permanently change configuration at client level
  clp.config({ accessToken: 'your-access-token' })
  const roles = await clp.roles.list()

  or

  // Use configuration at request level
  clp.roles.list({}, { accessToken: 'your-access-token' })

处理验证错误

商务层提供 API 返回单个资源每个属性的具体错误(附加信息). 您可以检查它们以正确处理验证错误( 如果有的话) 。 要做到这一点,使用 errors 被捕获错误的属性 :

  // Log error messages to console:
  const attributes = { name: '' }

  const newRole = await clp.roles.create(attributes).catch(error => console.log(error.errors))

  // Logged errors
  /*
  [
    {
      title: "can't be blank",
      detail: "name - can't be blank",
      code: 'VALIDATION_ERROR',
      source: { pointer: '/data/attributes/name' },
      status: '422',
      meta: { error: 'blank' }
    },
    {
      title: "can't be blank",
      detail: "organization - can't be blank",
      code: 'VALIDATION_ERROR',
      source: { pointer: '/data/relationships/organization' },
      status: '422',
      meta: { error: 'blank' }
    }
  ]
  */

请检查access-date=中的日期值 (帮助) 错误 由API返回.

使用截取器

您可以在请求发送到API之前,或由客户端解析并返回答复之前,使用截取器来截取SDK消息并修改它们. 也可以在被 SDK 抛出之前访问错误对象.

截取器是特殊功能,能够处理SDK消息并返回一个(最终)修改后版本,供客户端使用.

  const requestInterceptor = (request: RequestObj): RequestObj => {
    console.log(request)
    return request
  }

  const responseInterceptor = (response: ResponseObj): ResponseObj => {
    console.log(response)
    return response
  }

  const errorInterceptor = (error: ErrorObj): ErrorObj => {
    console.log(error)
    return error
  }

这里有一个如何使用它们的例子:

  // Add the interceptors (only one or all if needed)
  clp.addRequestInterceptor(requestInterceptor)
  clp.addResponseInterceptor(responseInterceptor, errorInterceptor)

  const organizations = await clp.organizations.list()

  // Remove interceptors
  // Tt is possible to remove only a specific interceptor: cl.removeInterceptor('request')
  cl.removeInterceptors()

Raw 响应读取器

这个 原始响应阅读器 是一个特殊的截取器,它允许在解析并翻译为SDK对象之前,捕捉来自 API 的原始消息.

  // Add a RawResponseReader capable of capturing also response headers
  const rrr = clp.addRawResponseReader({ headers: true })
  
  const organizations = await clp.organizations.list()

  cl.removeRawResponseReader()

  console.log(rrr.rawResponse)
  console.log(rrr.headers)

刷新访问令牌

可能您正在使用一个即将过期的访问符, 特别是当它被用于许多API电话时. 在此情况下,您可以定义一个特殊功能,当一个调用因过期而失效时,该功能会负责刷新符号.

  async function myRefreshTokenFunction(espiredToken: string): Promise<string> {
    // Get a new access token using for example our js-auth library
    return (await getAccessToken()).accessToken
  }

  cl.config({ refreshToken: myRefreshTokenFunction })

  // If needed you can later retrieve the new access token
  const newToken = cl.currentAccessToken

贡献者指南

  1. 叉头 此寄存器 (学习如何做到这一点) 读取 GitHub 文档) (中文(简体) ).

  2. 像这样砍掉叉子仓库:

    git clone https://github.com/<your username>/commercelayer-sdk.git && cd commercelayer-sdk
    
  3. 从寄存器根安装工作空间 :

    pnpm install
    
  4. 做你的改变。 此软件包大多来自 API 方案—— 任何您在其中编辑的内容 gen/ 将被覆盖。 更改生成器或 sdk.config.ts 转而运行 pnpm generate 并承担结果.

  5. 创建牵引请求( E)学着怎么做) (中文(简体) ). Lint,类型,测试套件和生成输出的检查都是可自动复制的.

  6. 有人会照顾你的拉力请求 并提供一些反馈.

需要帮忙吗?

许可证

此寄存器在 麻省理工学院 执照.

版本与发布记录

@commercelayer/provisioning-sdk 共发布 72 个版本,首次发布于 2023/10/31;过去 12 个月发布了 12 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.2latest2026/11/104 天前
3.0.2-beta.0beta2026/11/094 天前
3.0.12026/10/071 个月前
3.0.02026/10/061 个月前
3.0.0-beta.32026/10/031 个月前
3.0.0-beta.22026/09/301 个月前

其他发布通道:prerelease → 2.0.0-rc.2,sdk1 → 1.1.0,sdk2 → 2.10.2,beta → 3.0.2-beta.0。

关于 @commercelayer/provisioning-sdk 的常见问题

@commercelayer/provisioning-sdk 是什么?

提供 API Javascript SDK

如何安装 @commercelayer/provisioning-sdk?

在项目目录运行 npm install @commercelayer/provisioning-sdk,或使用 pnpm add / yarn add / bun add。

@commercelayer/provisioning-sdk 支持 TypeScript 吗?

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

@commercelayer/provisioning-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@commercelayer/provisioning-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@commercelayer/provisioning-sdk 可以商用吗?

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

@commercelayer/provisioning-sdk 的下载量有多少?

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

@commercelayer/provisioning-sdk 还在维护吗?

最新版本 3.0.2 发布于 2026/11/10(4 天前);至今共发布 72 个版本,其中过去 12 个月发布了 12 个;首次发布于 2023/10/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。