@ 商业工具/ 连接- 支付- sdk
建设通商工具支付连接器的基金会图书馆. 它处理每个连接器需要的所有锅炉板:商务工具API客户端,会话验证,JWT认证,请求上下文传播,自定义类型管理,以及同时进行修改上的重试逻辑,因此连接器作者可以专注于PSP特定的业务逻辑.
安装
npm install @commercetools/connect-payments-sdk
快开始
打电话 setupPaymentSDK 应用程序启动时一次。 它将所有服务和认证钩连接在一起,并作为一个单一对象返回.
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(),
});
配置
| 选项 | 说明 |
|---|---|
apiUrl | 商务工具 REST API URL(例如:. https://api.europe-west1.gcp.commercetools.com(中文(简体) ) |
authUrl | 商务工具认证 URL( 例如). https://auth.europe-west1.gcp.commercetools.com(中文(简体) ) |
clientId | 商务工具 API 客户端标识 manage_payments, (中文(简体) ), view_sessions 财务报告和审定财务报表 introspect_oauth_tokens 范围 |
clientSecret | aPI 客户端秘密 |
projectKey | 商务工具项目密钥 |
sessionUrl | 商务工具会话 API URL( 例如). https://session.europe-west1.gcp.commercetools.com(中文(简体) ) |
checkoutUrl | 商务工具检查出 API URL(例如. https://checkout.europe-west1.gcp.commercetools.com(中文(简体) ) |
jwksUrl | JWKS端点用于验证来往的JWT(例如. https://mc-api.europe-west1.gcp.commercetools.com/.well-known/jwks.json(中文(简体) ) |
jwtIssuer | 预期 iss 商业工具(如:. https://mc-api.europe-west1.gcp.commercetools.com(中文(简体) ) |
getContextFn | 返回当前函数 RequestContextData 从您的请求范围商店 |
updateContextFn | 将部分数据合并到请求范围存储( SDK 用于传播) 的函数 correlationId (例如) |
logger | 可选的 自定义日志执行 Logger 接口。 默认内置商务工具结构的日志 . |
httpMiddlewareOptions | 可选的 商务工具 HTTP 中间软件的覆盖(参见 HTTP 中间软件配置) (中文(简体) ). |
HTTP 中间软件配置
商务工具 API 客户端与 @commercetools/ts-client。默认情况下, SDK 配置其 HTTP 中间软件如下 :
| 选项 | 默认 | 理由 |
|---|---|---|
enableRetry | true | 当商业工具返回503时进行回溯. 在中间软件默认的情况下,这意味着最多10次尝试和200ms后退. |
maskSensitiveHeaderData | true | 保留 Authorization 以及来自日志和出错有效载荷的其他敏感头. |
过 httpMiddlewareOptions 或设置其他任何 HttpMiddlewareOptions 字段 :
export const paymentSDK = setupPaymentSDK({
// ...
httpMiddlewareOptions: {
retryConfig: {
maxRetries: 3,
retryDelay: 300,
backoff: true,
},
},
});
这里提供的值优先于上面的默认值,所以 enableRetry: false 或者说 maskSensitiveHeaderData: false 很荣幸.
什麽 setupPaymentSDK 返回时
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;
自定义类型
SDK飞船预先定义了用于存储支付方法细节的自定义商务工具类型草稿. 在部署后的连接器中注册它们 :
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,
});
对于特定连接器自定义类型, 使用 createOrUpdate 直接 :
await paymentSDK.ctCustomTypeService.createOrUpdate(myConnectorTypeDraft);