@commercetools/connect-payments-sdk

中文文档
1.6.1发布于 2026/10/23ISCTypeScriptCommonJS近 30 天下载 5056

Payment SDK for commercetools payment connectors

原始使用文档
文档目录6 节
  1. Installation
  2. Quick start
  3. Configuration
  4. HTTP middleware configuration
  5. What setupPaymentSDK returns
  6. Custom types

@commercetools/connect-payments-sdk

The foundation library for building commercetools payment connectors. It handles all the boilerplate that every connector needs: commercetools API clients, session verification, JWT authentication, request context propagation, custom type management, and retry logic on concurrent modifications so connector authors can focus on PSP-specific business logic.

Installation

npm install @commercetools/connect-payments-sdk

Quick start

Call setupPaymentSDK once at application startup. It wires together all services and authentication hooks and returns them as a single object.

import {
  setupPaymentSDK,
  Logger,
  RequestContextData,
} from '@commercetools/connect-payments-sdk';
import { getRequestContext, updateRequestContext } from './context';
import { config } from './config';

// Adapt your application logger to the SDK Logger interface
class AppLogger implements Logger {
  debug = (obj: object, msg: string) => console.debug(msg, obj);
  info  = (obj: object, msg: string) => console.info(msg, obj);
  warn  = (obj: object, msg: string) => console.warn(msg, obj);
  error = (obj: object, msg: string) => console.error(msg, obj);
}

export const paymentSDK = setupPaymentSDK({
  apiUrl:       config.apiUrl,
  authUrl:      config.authUrl,
  clientId:     config.clientId,
  clientSecret: config.clientSecret,
  projectKey:   config.projectKey,
  sessionUrl:   config.sessionUrl,
  checkoutUrl:  config.checkoutUrl,
  jwksUrl:      config.jwksUrl,
  jwtIssuer:    config.jwtIssuer,

  // Return the current request context (called on every incoming request)
  getContextFn: (): RequestContextData => {
    const { correlationId, requestId, authentication } = getRequestContext();
    return {
      correlationId: correlationId || '',
      requestId:     requestId || '',
      authentication,
    };
  },

  // Merge updated fields back into the request context store
  updateContextFn: (context: Partial<RequestContextData>) => {
    updateRequestContext({
      ...(context.correlationId  ? { correlationId:  context.correlationId  } : {}),
      ...(context.requestId      ? { requestId:      context.requestId      } : {}),
      ...(context.authentication ? { authentication: context.authentication } : {}),
    });
  },

  logger: new AppLogger(),
});

Configuration

OptionDescription
apiUrlcommercetools REST API URL (e.g. https://api.europe-west1.gcp.commercetools.com)
authUrlcommercetools auth URL (e.g. https://auth.europe-west1.gcp.commercetools.com)
clientIdcommercetools API client ID with manage_payments, view_sessions and introspect_oauth_tokens scopes
clientSecretcommercetools API client secret
projectKeycommercetools project key
sessionUrlcommercetools Session API URL (e.g. https://session.europe-west1.gcp.commercetools.com)
checkoutUrlcommercetools Checkout API URL (e.g. https://checkout.europe-west1.gcp.commercetools.com)
jwksUrlJWKS endpoint used to verify incoming JWTs (e.g. https://mc-api.europe-west1.gcp.commercetools.com/.well-known/jwks.json)
jwtIssuerExpected iss claim in JWTs issued by commercetools (e.g. https://mc-api.europe-west1.gcp.commercetools.com)
getContextFnFunction that returns the current RequestContextData from your request-scoped store
updateContextFnFunction that merges partial data into your request-scoped store (used by the SDK to propagate correlationId etc.)
loggerOptional. Custom logger implementing the Logger interface. Defaults to the built-in commercetools structured logger.
httpMiddlewareOptionsOptional. Overrides for the commercetools HTTP middleware (see HTTP middleware configuration).

HTTP middleware configuration

The commercetools API client is built with @commercetools/ts-client. By default the SDK configures its HTTP middleware as follows:

OptionDefaultRationale
enableRetrytrueRetries when commercetools returns a 503. With the middleware defaults this means up to 10 attempts with a 200ms backoff.
maskSensitiveHeaderDatatrueKeeps Authorization and other sensitive headers out of logs and error payloads.

Pass httpMiddlewareOptions to override any of these or to set any other HttpMiddlewareOptions field:

export const paymentSDK = setupPaymentSDK({
  // ...
  httpMiddlewareOptions: {
    retryConfig: {
      maxRetries: 3,
      retryDelay: 300,
      backoff: true,
    },
  },
});

Values provided here take precedence over the defaults above, so enableRetry: false or maskSensitiveHeaderData: false are honoured.

What setupPaymentSDK returns

const {
  // commercetools API services
  ctCartService,           // get carts, calculate payment amounts, add payments
  ctPaymentService,        // create/update commercetools payments and transactions
  ctOrderService,          // find orders
  ctPaymentMethodService,  // manage stored payment methods (tokenization)
  ctCustomTypeService,     // create/update commercetools custom types (used in post-deploy)
  ctAuthorizationService,  // obtain OAuth2 tokens for outbound calls
  ctRecurringPaymentJobService,

  // Raw commercetools API client (escape hatch for unsupported operations)
  ctAPI,

  // Request context provider
  contextProvider,

  // Fastify hooks — register these on your routes
  sessionHeaderAuthHookFn,      // verifies the commercetools session ID from the `x-session-id` header
  sessionQueryParamAuthHookFn,  // verifies the commercetools session ID from a query parameter
  jwtAuthHookFn,                // verifies a commercetools-issued JWT
  oauth2AuthHookFn,             // verifies a connector OAuth2 token
  authorityAuthorizationHookFn, // checks the caller has the required authority
} = paymentSDK;

Custom types

The SDK ships predefined commercetools custom type drafts for storing payment method details. Register them during connector post-deploy:

import {
  GenerateCardDetailsCustomFieldsDraft,
  GenerateSepaDetailsCustomFieldsDraft,
  GenerateInterfaceInteractionCustomFieldsDraft,
} from '@commercetools/connect-payments-sdk';

// In post-deploy:
await paymentSDK.ctCustomTypeService.createOrUpdatePredefinedPaymentMethodTypes();
await paymentSDK.ctCustomTypeService.createOrUpdatePredefinedInterfaceInteractionType();

// When processing a notification for a card payment:
const customFields = GenerateCardDetailsCustomFieldsDraft({
  brand: 'Visa',
  lastFour: '4242',
  expiryMonth: 12,
  expiryYear: 2027,
});

For connector-specific custom types, use createOrUpdate directly:

await paymentSDK.ctCustomTypeService.createOrUpdate(myConnectorTypeDraft);

版本与发布记录

@commercetools/connect-payments-sdk 共发布 64 个版本,首次发布于 2024/01/09;过去 12 个月发布了 17 个版本。

版本发布日期距今
1.6.1latest2026/10/2318 天前
1.6.02026/10/051 个月前
1.5.02026/09/301 个月前
1.4.02026/09/291 个月前
1.3.02026/09/241 个月前
1.2.22026/08/312 个月前

关于 @commercetools/connect-payments-sdk 的常见问题

@commercetools/connect-payments-sdk 是什么?

Payment SDK for commercetools payment connectors

如何安装 @commercetools/connect-payments-sdk?

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

@commercetools/connect-payments-sdk 支持 TypeScript 吗?

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

@commercetools/connect-payments-sdk 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@commercetools/connect-payments-sdk 需要什么版本的 Node.js?

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

@commercetools/connect-payments-sdk 可以商用吗?

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

@commercetools/connect-payments-sdk 的下载量有多少?

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

@commercetools/connect-payments-sdk 还在维护吗?

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