# @commercetools/ts-client 中文文档

规范地址：https://npmcn.com/package/%40commercetools/ts-client/

版本：5\.2\.0
npm 元数据更新时间：2026-11-02T10:57:52.502Z
中文译文更新时间：2026-11-10T12:10:53.529Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：369 kB，49 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：1 个
- 首次发布：2022-12-15T07:32:47.120Z
- 最新版本发布：2026-11-02T10:57:52.101Z
- 近 30 天下载量：657977（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：68（近 12 个月 14 个）

## 中文简介

商务工具 TypeScript SDK 客户端.

## 安装

```sh
npm install @commercetools/ts-client
```

也可以使用：`pnpm add @commercetools/ts-client`、`yarn add @commercetools/ts-client`、`bun add @commercetools/ts-client`

## README

# 商务工具( 改进后) TypeScript SDK 客户端

这是新改进的Typescript SDK客户端.

## 用法实例

```bash
npm install --save @commercetools/ts-client
npm install --save @commercetools/platform-sdk

or

yarn add @commercetools/ts-client
yarn add @commercetools/platform-sdk
```

```ts
import {
  type Next,
  type HttpMiddlewareOptions,
  type AuthMiddlewareBaseOptions,
  type ClientRequest,
  type MiddlewareRequest,
  type MiddlewareResponse,
  type Client,
  createHttpMiddleware,
  createConcurrentModificationMiddleware,
  createAuthMiddlewareForClientCredentialsFlow,
  ClientBuilder,
} from '@commercetools/ts-client'
import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk'

const projectKey = 'mc-project-key'
const authMiddlewareOptions = {
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey,
  credentials: {
    clientId: 'mc-client-id',
    clientSecret: 'mc-client-secrets',
  },
  oauthUri: '/oauth/token', // - optional: custom oauthUri
  scopes: [`manage_project:${projectKey}`],
  httpClient: fetch,
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const retryOptions = {
  maxRetries: 3,
  retryDelay: 200,
  backoff: true,
  retryCodes: [503],
}

const loggerFn = (response) => {
  // log response object
  console.log(response)
}

// custom middleware
function middleware(options) {
  return (next: Next) =>
    async (request: MiddlewareRequest): Promise<MiddlewareResponse> => {
      const { response, ...rest } = request

      // other actions can also be carried out here e.g logging,
      // error handling, injecting custom headers to http requests etc.
      console.log({ response, rest })
      return next({ ...request })
    }
}

const client: Client = new ClientBuilder()
  .withPasswordFlow(authMiddlewareOptions)
  .withLoggerMiddleware({ loggerFn })
  .withCorrelationIdMiddleware({
    generate: () => 'fake-correlation-id' + Math.floor(Math.random() + 2),
  })
  .withHttpMiddleware(httpMiddlewareOptions)
  .withMiddleware(middleware({})) // <<<------------------- add the custom middleware here
  .build()

const apiRoot = createApiBuilderFromCtpClient(client)

// calling the commercetools `api` functions
// get project details
apiRoot
  .withProjectKey({ projectKey })
  .get()
  .execute()
  .then((x) => {
    /*...*/
  })

// create a productType
apiRoot
  .withProjectKey({ projectKey })
  .productTypes()
  .post({
    body: { name: 'product-type-name', description: 'some description' },
  })
  .execute()
  .then((x) => {
    /*...*/
  })

// create a product
apiRoot
  .withProjectKey({ projectKey })
  .products()
  .post({
    body: {
      name: { en: 'our-great-product-name' },
      productType: {
        typeId: 'product-type',
        id: 'some-product-type-id',
      },
      slug: { en: 'some-slug' },
    },
  })
  .execute()
  .then((x) => {
    /*...*/
  })
```

## 创建客户端

要创建客户端,请使用 `ClientBuilder` 课。 这个 `ClientBuilder` 类提供了流利的 API 配置客户端.

```ts
const authMiddlewareOptions = {
  credentials: {
    clientId: 'xxx',
    clientSecret: 'xxx',
  },
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey: 'xxx',
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const client = new ClientBuilder()
  .withHttpMiddleware(httpMiddlewareOptions)
  .withConcurrentModificationMiddleware()
  .withClientCredentialsFlow(authMiddlewareOptions)
  .build()
```

这个 `withMiddleware` 方法可以用于以有序的方式添加中件功能(内置和自定义中件).

```ts
// Example
const authMiddlewareOptions = {
  credentials: {
    clientId: 'xxx',
    clientSecret: 'xxx',
  },
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey: 'xxx',
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const logger = () => {
  return (next) => async (request) => {
    // log request object
    console.log('Request:', request)
    const response = await next(request)

    // log response object
    console.log('Response', response)
    return response
  }
}

const client = new ClientBuilder()
  .withMiddleware(
    createAuthMiddlewareForClientCredentialsFlow(authMiddlewareOptions)
  )
  .withMiddleware(createHttpMiddleware(httpMiddlewareOptions))
  .withMiddleware(createConcurrentModificationMiddleware())
  .withMiddleware(logger())
  .build()
```

这将以命令的方式添加中间软件,首先是:

1.  创建 AuthMiddle 软件用于认证证书
2.  创建 HttpMiddle 软件
3.  创建同步移动中端软件
4.  日志

注意当使用 `withMiddleware` 函数可以将自定义的中间软件与已建的中间软件函数相并列,它将将自定义的中间软件添加到执行链的启动中.

```ts
// Example
const authMiddlewareOptions = {
  credentials: {
    clientId: 'xxx',
    clientSecret: 'xxx',
  },
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey: 'xxx',
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const logger = () => {
  return (next) => async (request) => {
    // log request object
    console.log('Request:', request)
    const response = await next(request)

    // log response object
    console.log('Response', response)
    return response
  }
}

const client = new ClientBuilder()
  .withClientCredentialsFlow(authMiddlewareOptions)
  .withHttpMiddleware(httpMiddlewareOptions)
  .withConcurrentModificationMiddleware()
  .withMiddleware(logger())
  .build()
```

执行顺序如下:

1.  使用Middleware < -- -- -- 自定义中间软件
2.  带有 client 证书
3.  使用 HttpMiddle 软件
4.  与同时期的移动中件

## 常见问题

### @commercetools/ts-client 是什么？

商务工具 TypeScript SDK 客户端\.

### 如何安装 @commercetools/ts-client？

在项目目录运行 npm install @commercetools/ts-client，或使用 pnpm add / yarn add / bun add。

### @commercetools/ts-client 支持 TypeScript 吗？

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

### @commercetools/ts-client 支持 ESM 还是 CommonJS？

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

### @commercetools/ts-client 需要什么版本的 Node\.js？

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

### @commercetools/ts-client 可以商用吗？

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

### @commercetools/ts-client 的下载量有多少？

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

### @commercetools/ts-client 还在维护吗？

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

