@commercetools/connect-payments-sdk
v1.2.0
Published
Payment SDK for commercetools payment connectors
Downloads
3,800
Readme
@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-sdkQuick 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
| Option | Description |
|---|---|
| apiUrl | commercetools REST API URL (e.g. https://api.europe-west1.gcp.commercetools.com) |
| authUrl | commercetools auth URL (e.g. https://auth.europe-west1.gcp.commercetools.com) |
| clientId | commercetools API client ID with manage_payments, view_sessions and introspect_oauth_tokens scopes |
| clientSecret | commercetools API client secret |
| projectKey | commercetools project key |
| sessionUrl | commercetools Session API URL (e.g. https://session.europe-west1.gcp.commercetools.com) |
| checkoutUrl | commercetools Checkout API URL (e.g. https://checkout.europe-west1.gcp.commercetools.com) |
| jwksUrl | JWKS endpoint used to verify incoming JWTs (e.g. https://mc-api.europe-west1.gcp.commercetools.com/.well-known/jwks.json) |
| jwtIssuer | Expected iss claim in JWTs issued by commercetools (e.g. https://mc-api.europe-west1.gcp.commercetools.com) |
| getContextFn | Function that returns the current RequestContextData from your request-scoped store |
| updateContextFn | Function that merges partial data into your request-scoped store (used by the SDK to propagate correlationId etc.) |
| logger | Optional. Custom logger implementing the Logger interface. Defaults to the built-in commercetools structured logger. |
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);