@commercetools/connect-payments-sdk 0.23.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/api/context/request-context.helper.d.ts +6 -0
  3. package/dist/api/context/request-context.helper.js +12 -0
  4. package/dist/commercetools/api/custom-type-api.d.ts +10 -0
  5. package/dist/commercetools/api/custom-type-api.js +45 -0
  6. package/dist/commercetools/api/payment-method-api.d.ts +12 -0
  7. package/dist/commercetools/api/payment-method-api.js +69 -0
  8. package/dist/commercetools/api/root-api.d.ts +3 -1
  9. package/dist/commercetools/api/root-api.js +7 -0
  10. package/dist/commercetools/index.d.ts +4 -1
  11. package/dist/commercetools/index.js +2 -1
  12. package/dist/commercetools/services/ct-custom-type.service.d.ts +34 -0
  13. package/dist/commercetools/services/ct-custom-type.service.js +91 -0
  14. package/dist/commercetools/services/ct-payment-method.service.d.ts +18 -0
  15. package/dist/commercetools/services/ct-payment-method.service.js +148 -0
  16. package/dist/commercetools/services/ct-payment.service.d.ts +16 -0
  17. package/dist/commercetools/services/ct-payment.service.js +101 -7
  18. package/dist/commercetools/types/api.type.d.ts +34 -1
  19. package/dist/commercetools/types/custom-type.type.d.ts +20 -0
  20. package/dist/commercetools/types/custom-type.type.js +2 -0
  21. package/dist/commercetools/types/payment-method.type.d.ts +109 -0
  22. package/dist/commercetools/types/payment-method.type.js +2 -0
  23. package/dist/commercetools/types/payment.type.d.ts +4 -1
  24. package/dist/custom-types/index.d.ts +4 -0
  25. package/dist/custom-types/index.js +20 -0
  26. package/dist/custom-types/payment-interface-interactions.d.ts +11 -0
  27. package/dist/custom-types/payment-interface-interactions.js +78 -0
  28. package/dist/custom-types/payment-methods/card.d.ts +12 -0
  29. package/dist/custom-types/payment-methods/card.js +75 -0
  30. package/dist/custom-types/payment-methods/sepa.d.ts +8 -0
  31. package/dist/custom-types/payment-methods/sepa.js +35 -0
  32. package/dist/custom-types/payment-methods/shared.d.ts +2 -0
  33. package/dist/custom-types/payment-methods/shared.js +13 -0
  34. package/dist/errorx/errorx.d.ts +2 -0
  35. package/dist/errorx/errorx.js +4 -0
  36. package/dist/index.d.ts +5 -0
  37. package/dist/index.js +7 -0
  38. package/dist/security/authn/types/authn.type.d.ts +4 -0
  39. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @commercetools/connect-payments-sdk
2
2
 
3
+ ## 0.25.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 511fbef: - Add new api and service for interacting with CT custom-types APIs.
8
+ - Add predefined Checkout custom-types.
9
+ - d28fe6d: support use of transaction interface id and checkoutTransactionItemsIds
10
+
11
+ ### Patch Changes
12
+
13
+ - 5d0e4c2: chore(sdk): for CT API sdk mask sensitive data in error object
14
+
15
+ ## 0.24.0
16
+
17
+ ### Minor Changes
18
+
19
+ - bdd4f33: Add a new api and service for interacting with the CT payment-methods APIs.
20
+
3
21
  ## 0.23.1
4
22
 
5
23
  ### Patch Changes
@@ -3,7 +3,13 @@ export declare function getGiftCardPlannedAmountFromContext(context: RequestCont
3
3
  export declare function getCtSessionIdFromContext(context: RequestContextData): string | undefined;
4
4
  export declare function getCartIdFromContext(context: RequestContextData): string | undefined;
5
5
  export declare function getAllowedPaymentMethodsFromContext(context: RequestContextData): string[] | undefined;
6
+ /**
7
+ * @deprecated use getCheckoutTransactionItemIdFromContext instead
8
+ * @param context
9
+ * @returns
10
+ */
6
11
  export declare function getPaymentInterfaceFromContext(context: RequestContextData): string | undefined;
12
+ export declare function getCheckoutTransactionItemIdFromContext(context: RequestContextData): string | undefined;
7
13
  export declare function getProcessorUrlFromContext(context: RequestContextData): string | undefined;
8
14
  export declare function getMerchantReturnUrlFromContext(context: RequestContextData): string | undefined;
9
15
  export declare function getFutureOrderNumberFromContext(context: RequestContextData): string | undefined;
@@ -5,6 +5,7 @@ exports.getCtSessionIdFromContext = getCtSessionIdFromContext;
5
5
  exports.getCartIdFromContext = getCartIdFromContext;
6
6
  exports.getAllowedPaymentMethodsFromContext = getAllowedPaymentMethodsFromContext;
7
7
  exports.getPaymentInterfaceFromContext = getPaymentInterfaceFromContext;
8
+ exports.getCheckoutTransactionItemIdFromContext = getCheckoutTransactionItemIdFromContext;
8
9
  exports.getProcessorUrlFromContext = getProcessorUrlFromContext;
9
10
  exports.getMerchantReturnUrlFromContext = getMerchantReturnUrlFromContext;
10
11
  exports.getFutureOrderNumberFromContext = getFutureOrderNumberFromContext;
@@ -33,12 +34,23 @@ function getAllowedPaymentMethodsFromContext(context) {
33
34
  return authentication?.getPrincipal().allowedPaymentMethods;
34
35
  }
35
36
  }
37
+ /**
38
+ * @deprecated use getCheckoutTransactionItemIdFromContext instead
39
+ * @param context
40
+ * @returns
41
+ */
36
42
  function getPaymentInterfaceFromContext(context) {
37
43
  const authentication = context.authentication;
38
44
  if (authentication && authentication instanceof __1.SessionAuthentication) {
39
45
  return authentication?.getPrincipal().paymentInterface;
40
46
  }
41
47
  }
48
+ function getCheckoutTransactionItemIdFromContext(context) {
49
+ const authentication = context.authentication;
50
+ if (authentication && authentication instanceof __1.SessionAuthentication) {
51
+ return authentication?.getPrincipal().checkoutTransactionItemId;
52
+ }
53
+ }
42
54
  function getProcessorUrlFromContext(context) {
43
55
  const authentication = context.authentication;
44
56
  if (authentication && authentication instanceof __1.SessionAuthentication) {
@@ -0,0 +1,10 @@
1
+ import { Type, TypeDraft, TypeUpdate } from '@commercetools/platform-sdk';
2
+ import { APIOpts, CustomTypeAPI } from '../types/api.type';
3
+ import { CommercetoolsBaseAPI } from './base-api';
4
+ export declare class CommercetoolsCustomTypeAPI extends CommercetoolsBaseAPI implements CustomTypeAPI {
5
+ constructor(opts: APIOpts);
6
+ getByKey(key: string): Promise<Type>;
7
+ existsByKey(key: string): Promise<boolean>;
8
+ create(draft: TypeDraft): Promise<Type>;
9
+ update(key: string, update: TypeUpdate): Promise<Type>;
10
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommercetoolsCustomTypeAPI = void 0;
4
+ const base_api_1 = require("./base-api");
5
+ class CommercetoolsCustomTypeAPI extends base_api_1.CommercetoolsBaseAPI {
6
+ constructor(opts) {
7
+ super(opts);
8
+ Object.setPrototypeOf(this, CommercetoolsCustomTypeAPI.prototype);
9
+ }
10
+ async getByKey(key) {
11
+ return this.executeCall(this.client.types().withKey({ key }).get().execute());
12
+ }
13
+ async existsByKey(key) {
14
+ try {
15
+ await this.client.types().withKey({ key }).get().execute();
16
+ return true;
17
+ }
18
+ catch (error) {
19
+ if (error instanceof Object && 'statusCode' in error && error['statusCode'] === 404) {
20
+ return false;
21
+ }
22
+ else {
23
+ throw error;
24
+ }
25
+ }
26
+ }
27
+ async create(draft) {
28
+ return this.executeCall(this.client
29
+ .types()
30
+ .post({
31
+ body: draft,
32
+ })
33
+ .execute());
34
+ }
35
+ async update(key, update) {
36
+ return this.executeCall(this.client
37
+ .types()
38
+ .withKey({ key })
39
+ .post({
40
+ body: update,
41
+ })
42
+ .execute());
43
+ }
44
+ }
45
+ exports.CommercetoolsCustomTypeAPI = CommercetoolsCustomTypeAPI;
@@ -0,0 +1,12 @@
1
+ import { PaymentMethod, PaymentMethodDraft, PaymentMethodPagedQueryResponse } from '@commercetools/platform-sdk';
2
+ import { APIOpts, CheckIfExistsByPredicate, DeletePaymentMethod, FindPaymentMethods, GetPaymentMethod, PaymentMethodAPI, UpdatePaymentMethod } from '../types/api.type';
3
+ import { CommercetoolsBaseAPI } from './base-api';
4
+ export declare class CommercetoolsPaymentMethodAPI extends CommercetoolsBaseAPI implements PaymentMethodAPI {
5
+ constructor(opts: APIOpts);
6
+ get(opts: GetPaymentMethod): Promise<PaymentMethod>;
7
+ checkIfExistsByPredicate(opts: CheckIfExistsByPredicate): Promise<boolean>;
8
+ find(opts: FindPaymentMethods): Promise<PaymentMethodPagedQueryResponse>;
9
+ create(draft: PaymentMethodDraft): Promise<PaymentMethod>;
10
+ update(opts: UpdatePaymentMethod): Promise<PaymentMethod>;
11
+ delete(opts: DeletePaymentMethod): Promise<PaymentMethod>;
12
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommercetoolsPaymentMethodAPI = void 0;
4
+ const base_api_1 = require("./base-api");
5
+ class CommercetoolsPaymentMethodAPI extends base_api_1.CommercetoolsBaseAPI {
6
+ constructor(opts) {
7
+ super(opts);
8
+ Object.setPrototypeOf(this, CommercetoolsPaymentMethodAPI.prototype);
9
+ }
10
+ get(opts) {
11
+ return this.executeCall(this.client.paymentMethods().withId({ ID: opts.id }).get().execute());
12
+ }
13
+ async checkIfExistsByPredicate(opts) {
14
+ const result = await this.executeCall(this.client
15
+ .paymentMethods()
16
+ .get({
17
+ queryArgs: {
18
+ where: opts.queryString,
19
+ },
20
+ })
21
+ .execute());
22
+ if (result.total === 0) {
23
+ return false;
24
+ }
25
+ return true;
26
+ }
27
+ find(opts) {
28
+ return this.executeCall(this.client
29
+ .paymentMethods()
30
+ .get({
31
+ queryArgs: {
32
+ where: opts.queryString,
33
+ },
34
+ })
35
+ .execute());
36
+ }
37
+ create(draft) {
38
+ return this.executeCall(this.client
39
+ .paymentMethods()
40
+ .post({
41
+ body: draft,
42
+ })
43
+ .execute());
44
+ }
45
+ update(opts) {
46
+ return this.executeCall(this.client
47
+ .paymentMethods()
48
+ .withId({ ID: opts.resource.id })
49
+ .post({
50
+ body: {
51
+ version: opts.resource.version,
52
+ actions: opts.actions,
53
+ },
54
+ })
55
+ .execute());
56
+ }
57
+ delete(opts) {
58
+ return this.executeCall(this.client
59
+ .paymentMethods()
60
+ .withId({ ID: opts.id })
61
+ .delete({
62
+ queryArgs: {
63
+ version: opts.version,
64
+ },
65
+ })
66
+ .execute());
67
+ }
68
+ }
69
+ exports.CommercetoolsPaymentMethodAPI = CommercetoolsPaymentMethodAPI;
@@ -1,11 +1,13 @@
1
1
  import { ContextProvider, RequestContextData } from '../../api';
2
- import { CartAPI, CommercetoolsAPI, CommercetoolsClient, OrderAPI, PaymentAPI } from '../types/api.type';
2
+ import { CartAPI, CommercetoolsAPI, CommercetoolsClient, CustomTypeAPI, OrderAPI, PaymentAPI, PaymentMethodAPI } from '../types/api.type';
3
3
  import { Logger } from '../..';
4
4
  export declare class DefaultCommercetoolsAPI implements CommercetoolsAPI {
5
5
  client: CommercetoolsClient;
6
6
  cart: CartAPI;
7
7
  payment: PaymentAPI;
8
8
  order: OrderAPI;
9
+ paymentMethod: PaymentMethodAPI;
10
+ customType: CustomTypeAPI;
9
11
  private logger;
10
12
  constructor(opts: {
11
13
  clientId: string;
@@ -5,19 +5,25 @@ const platform_sdk_1 = require("@commercetools/platform-sdk");
5
5
  const ts_client_1 = require("@commercetools/ts-client");
6
6
  const cart_api_1 = require("./cart-api");
7
7
  const payment_api_1 = require("./payment-api");
8
+ const payment_method_api_1 = require("./payment-method-api");
8
9
  const order_api_1 = require("./order-api");
10
+ const custom_type_api_1 = require("./custom-type-api");
9
11
  const crypto_1 = require("crypto");
10
12
  class DefaultCommercetoolsAPI {
11
13
  client;
12
14
  cart;
13
15
  payment;
14
16
  order;
17
+ paymentMethod;
18
+ customType;
15
19
  logger;
16
20
  constructor(opts) {
17
21
  this.client = createClient(opts);
18
22
  this.cart = new cart_api_1.CommercetoolsCartAPI({ client: this.client });
19
23
  this.payment = new payment_api_1.CommercetoolsPaymentAPI({ client: this.client });
20
24
  this.order = new order_api_1.CommercetoolsOrderAPI({ client: this.client });
25
+ this.paymentMethod = new payment_method_api_1.CommercetoolsPaymentMethodAPI({ client: this.client });
26
+ this.customType = new custom_type_api_1.CommercetoolsCustomTypeAPI({ client: this.client });
21
27
  this.logger = opts.logger;
22
28
  }
23
29
  }
@@ -37,6 +43,7 @@ const createClient = (opts) => {
37
43
  //Enables SDK retries when CoCo returns a 503 error. It retries up to 10 times with an 200ms backoff.
38
44
  enableRetry: true,
39
45
  ...(opts.httpClient ? { httpClient: opts.httpClient } : {}),
46
+ maskSensitiveHeaderData: true,
40
47
  };
41
48
  const correlationIdMiddlewareOptions = {
42
49
  generate: () => {
@@ -3,7 +3,10 @@ export { PaymentService as CommercetoolsPaymentService, TransactionData, UpdateP
3
3
  export { SessionService as CommercetoolsSessionService, Session } from './types/session.type';
4
4
  export { AuthorizationService as CommercetoolsAuthorizationService } from './types/authorization.type';
5
5
  export { OrderService as CommercetoolsOrderService } from './types/order.type';
6
+ export { PaymentMethodService as CommercetoolsPaymentMethodService } from './types/payment-method.type';
7
+ export { CustomTypeService as CommercetoolsCustomTypeService } from './types/custom-type.type';
8
+ export * as CommercetoolsPaymentMethodTypes from './types/payment-method.type';
6
9
  export { CommercetoolsClient } from './types/api.type';
7
- export { CustomFieldsDraft, Cart, Order, OrderPagedQueryResponse, Payment, PaymentDraft, Money, LineItem, CustomLineItem, Address, Transaction, TransactionType, TransactionState, ShippingInfo, } from '@commercetools/platform-sdk';
10
+ export { CustomFieldsDraft, Cart, Order, OrderPagedQueryResponse, Payment, PaymentDraft, PaymentMethodInfoDraft, Money, LineItem, CustomLineItem, Address, Transaction, TransactionType, TransactionState, ShippingInfo, PaymentMethod, PaymentMethodPagedQueryResponse, PaymentMethodToken, PaymentMethodStatus, Type, TypeDraft, TypePagedQueryResponse, LocalizedString, } from '@commercetools/platform-sdk';
8
11
  export * as CurrencyConverters from './helpers/currency.converter';
9
12
  export * as TaxRateConverter from './helpers/taxrate.converter';
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.TaxRateConverter = exports.CurrencyConverters = void 0;
36
+ exports.TaxRateConverter = exports.CurrencyConverters = exports.CommercetoolsPaymentMethodTypes = void 0;
37
+ exports.CommercetoolsPaymentMethodTypes = __importStar(require("./types/payment-method.type"));
37
38
  exports.CurrencyConverters = __importStar(require("./helpers/currency.converter"));
38
39
  exports.TaxRateConverter = __importStar(require("./helpers/taxrate.converter"));
@@ -0,0 +1,34 @@
1
+ import { Type, TypeDraft } from '@commercetools/platform-sdk';
2
+ import { PaymentServiceOptions } from '../types/payment.type';
3
+ import { CustomTypeService, GetByKeyCustomType, UpdateCustomType } from '../types/custom-type.type';
4
+ /**
5
+ * This is the default implementation of the CustomTypeService interface.
6
+ */
7
+ export declare class DefaultCustomTypeService implements CustomTypeService {
8
+ private ctAPI;
9
+ private logger;
10
+ constructor(opts: PaymentServiceOptions);
11
+ getByKey(opts: GetByKeyCustomType): Promise<Type>;
12
+ existsByKey(opts: GetByKeyCustomType): Promise<boolean>;
13
+ create(draft: TypeDraft): Promise<Type>;
14
+ update(opts: UpdateCustomType): Promise<Type>;
15
+ createOrUpdatePredefinedPaymentMethodTypes(): Promise<Type[]>;
16
+ createOrUpdatePredefinedInterfaceInteractionType(): Promise<Type>;
17
+ /**
18
+ * Based on the given TypeDraft this will either create or update the custom type in CT based on the provided "key".
19
+ *
20
+ * - if a custom-type by key does not exist in CT then it will create it using the given draft
21
+ * - if a custom-type by key does exist in CT it will gather a set of update actions to try and sync up the definitions
22
+ *
23
+ * The update currently supports:
24
+ * - adding missing field definitions. If the given draft contains field definitions that the custom-type in CT does not have, it will for each missing field definition perform an "addFieldDefinition" update action. Purely by checking the "name" of the field definitions.
25
+ *
26
+ * Differences between the TypeDraft and existing custom-type in CT such as are not supported yet but could be added in the future.
27
+ * - remove field definition if they no longer exist in the TypeDraft
28
+ * - update/sync the possible enum values for a field definition
29
+ * - update/sync the actual field definition properties. Such as "localized label", "type" or "required" value
30
+ */
31
+ createOrUpdate(customTypeDraft: TypeDraft): Promise<Type>;
32
+ private consolidateUpdateActions;
33
+ private getMissingFieldDefinitionsUpdateActions;
34
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultCustomTypeService = void 0;
4
+ const custom_types_1 = require("../../custom-types");
5
+ /**
6
+ * This is the default implementation of the CustomTypeService interface.
7
+ */
8
+ class DefaultCustomTypeService {
9
+ ctAPI;
10
+ logger;
11
+ constructor(opts) {
12
+ this.ctAPI = opts.ctAPI;
13
+ this.logger = opts.logger;
14
+ }
15
+ async getByKey(opts) {
16
+ return await this.ctAPI.customType.getByKey(opts.key);
17
+ }
18
+ async existsByKey(opts) {
19
+ return await this.ctAPI.customType.existsByKey(opts.key);
20
+ }
21
+ async create(draft) {
22
+ return await this.ctAPI.customType.create(draft);
23
+ }
24
+ async update(opts) {
25
+ return await this.ctAPI.customType.update(opts.key, opts.updateActions);
26
+ }
27
+ async createOrUpdatePredefinedPaymentMethodTypes() {
28
+ const cardDetailsType = await this.createOrUpdate(custom_types_1.CardDetailsTypeDraft);
29
+ const sepaDetailsType = await this.createOrUpdate(custom_types_1.SepaDetailsTypeDraft);
30
+ return [cardDetailsType, sepaDetailsType];
31
+ }
32
+ async createOrUpdatePredefinedInterfaceInteractionType() {
33
+ return await this.createOrUpdate(custom_types_1.PaymentInterfaceInteractionTypeDraft);
34
+ }
35
+ /**
36
+ * Based on the given TypeDraft this will either create or update the custom type in CT based on the provided "key".
37
+ *
38
+ * - if a custom-type by key does not exist in CT then it will create it using the given draft
39
+ * - if a custom-type by key does exist in CT it will gather a set of update actions to try and sync up the definitions
40
+ *
41
+ * The update currently supports:
42
+ * - adding missing field definitions. If the given draft contains field definitions that the custom-type in CT does not have, it will for each missing field definition perform an "addFieldDefinition" update action. Purely by checking the "name" of the field definitions.
43
+ *
44
+ * Differences between the TypeDraft and existing custom-type in CT such as are not supported yet but could be added in the future.
45
+ * - remove field definition if they no longer exist in the TypeDraft
46
+ * - update/sync the possible enum values for a field definition
47
+ * - update/sync the actual field definition properties. Such as "localized label", "type" or "required" value
48
+ */
49
+ async createOrUpdate(customTypeDraft) {
50
+ const exists = await this.existsByKey({ key: customTypeDraft.key });
51
+ if (!exists) {
52
+ this.logger.info({ key: customTypeDraft.key }, 'Custom type by key does not exist in CT, creating it');
53
+ return await this.create(customTypeDraft);
54
+ }
55
+ const customTypeFromCT = await this.getByKey({ key: customTypeDraft.key });
56
+ const updateActions = this.consolidateUpdateActions(customTypeDraft, customTypeFromCT);
57
+ if (updateActions.actions.length > 0) {
58
+ this.logger.info({ key: customTypeDraft.key, updateActions: { total: updateActions.actions.length } }, 'Updating existing custom-type by key');
59
+ return await this.update({ key: customTypeFromCT.key, updateActions: updateActions });
60
+ }
61
+ this.logger.info({ key: customTypeDraft.key }, 'Custom type exists but no update is required, doing nothing.');
62
+ return customTypeFromCT;
63
+ }
64
+ consolidateUpdateActions(customTypeDraft, existingType) {
65
+ const updateActions = [];
66
+ updateActions.push(...this.getMissingFieldDefinitionsUpdateActions(customTypeDraft, existingType));
67
+ return {
68
+ version: existingType.version,
69
+ actions: updateActions,
70
+ };
71
+ }
72
+ getMissingFieldDefinitionsUpdateActions(customTypeDraft, existingType) {
73
+ const draftFieldDefinitions = customTypeDraft.fieldDefinitions || [];
74
+ const missingFieldDefinitions = draftFieldDefinitions.filter((fd) => !existingType.fieldDefinitions.some((existingFD) => fd.name === existingFD.name));
75
+ const addFieldDefinitionUpdateActions = missingFieldDefinitions.map((fd) => {
76
+ return {
77
+ action: 'addFieldDefinition',
78
+ fieldDefinition: fd,
79
+ };
80
+ });
81
+ if (addFieldDefinitionUpdateActions.length > 0) {
82
+ this.logger.info({
83
+ key: customTypeDraft.key,
84
+ missingFieldsCount: addFieldDefinitionUpdateActions.length,
85
+ fieldNames: missingFieldDefinitions.map((fd) => fd.name),
86
+ }, 'Custom type in CT is missing field definition from the draft, adding them');
87
+ }
88
+ return addFieldDefinitionUpdateActions;
89
+ }
90
+ }
91
+ exports.DefaultCustomTypeService = DefaultCustomTypeService;
@@ -0,0 +1,18 @@
1
+ import { FindPaymentMethod, GetPaymentMethod, DeletePaymentMethod, PaymentMethodService, PaymentMethodServiceOptions, UpdatePaymentMethod, DoesTokenBelongToCustomer, GetByTokenValuePaymentMethod, SavePaymentMethodDraft } from '../types/payment-method.type';
2
+ import { PaymentMethod, PaymentMethodPagedQueryResponse } from '@commercetools/platform-sdk';
3
+ /**
4
+ * This is the default implementation of the PamentMethodService interface.
5
+ */
6
+ export declare class DefaultPaymentMethodService implements PaymentMethodService {
7
+ private ctAPI;
8
+ private logger;
9
+ constructor(opts: PaymentMethodServiceOptions);
10
+ find(opts: FindPaymentMethod): Promise<PaymentMethodPagedQueryResponse>;
11
+ get(opts: GetPaymentMethod): Promise<PaymentMethod>;
12
+ getByTokenValue(opts: GetByTokenValuePaymentMethod): Promise<PaymentMethod>;
13
+ doesTokenBelongsToCustomer(opts: DoesTokenBelongToCustomer): Promise<boolean>;
14
+ update(opts: UpdatePaymentMethod): Promise<PaymentMethod>;
15
+ save(opts: SavePaymentMethodDraft): Promise<PaymentMethod>;
16
+ delete(opts: DeletePaymentMethod): Promise<PaymentMethod>;
17
+ private ensurePaymentMethodBelongsToGivenCustomer;
18
+ }
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultPaymentMethodService = void 0;
4
+ const errorx_1 = require("../../errorx");
5
+ /**
6
+ * This is the default implementation of the PamentMethodService interface.
7
+ */
8
+ class DefaultPaymentMethodService {
9
+ ctAPI;
10
+ logger;
11
+ constructor(opts) {
12
+ this.ctAPI = opts.ctAPI;
13
+ this.logger = opts.logger;
14
+ }
15
+ async find(opts) {
16
+ const whereFilters = [];
17
+ whereFilters.push(`customer(id="${opts.customerId}")`);
18
+ whereFilters.push(`paymentInterface="${opts.paymentInterface}"`);
19
+ if (opts.interfaceAccount) {
20
+ whereFilters.push(`interfaceAccount="${opts.interfaceAccount}"`);
21
+ }
22
+ const whereFilter = whereFilters.join(' and ');
23
+ return await this.ctAPI.paymentMethod.find({
24
+ queryString: whereFilter,
25
+ });
26
+ }
27
+ async get(opts) {
28
+ const paymentMethods = await this.find({
29
+ customerId: opts.customerId,
30
+ paymentInterface: opts.paymentInterface,
31
+ interfaceAccount: opts.interfaceAccount,
32
+ });
33
+ const paymentMethodMatchesId = paymentMethods.results.find((pm) => opts.id === pm.id);
34
+ if (!paymentMethodMatchesId) {
35
+ throw new errorx_1.ErrorResourceNotFound(opts.id);
36
+ }
37
+ return paymentMethodMatchesId;
38
+ }
39
+ async getByTokenValue(opts) {
40
+ const paymentMethods = await this.find({
41
+ customerId: opts.customerId,
42
+ paymentInterface: opts.paymentInterface,
43
+ interfaceAccount: opts.interfaceAccount,
44
+ });
45
+ const paymentMethodsMatchWithTokenValue = paymentMethods.results.filter((pm) => opts.tokenValue === pm.token?.value);
46
+ if (paymentMethodsMatchWithTokenValue.length > 1) {
47
+ throw new errorx_1.ErrorInternalConstraintViolated('Found more then one payment method with the same token value.', {
48
+ privateFields: {
49
+ customerId: opts.customerId,
50
+ paymentMethodIds: paymentMethodsMatchWithTokenValue.map((pm) => pm.id),
51
+ paymentInterface: opts.paymentInterface,
52
+ interfaceAccount: opts.interfaceAccount,
53
+ },
54
+ });
55
+ }
56
+ if (paymentMethodsMatchWithTokenValue.length === 0) {
57
+ throw new errorx_1.ErrorResourceNotFound(opts.customerId, {
58
+ privateFields: {
59
+ customerId: opts.customerId,
60
+ paymentInterface: opts.paymentInterface,
61
+ interfaceAccount: opts.interfaceAccount,
62
+ },
63
+ });
64
+ }
65
+ return paymentMethodsMatchWithTokenValue[0];
66
+ }
67
+ async doesTokenBelongsToCustomer(opts) {
68
+ try {
69
+ const paymentMethod = await this.getByTokenValue({
70
+ customerId: opts.customerId,
71
+ paymentInterface: opts.paymentInterface,
72
+ interfaceAccount: opts.interfaceAccount,
73
+ tokenValue: opts.tokenValue,
74
+ });
75
+ return paymentMethod !== undefined;
76
+ }
77
+ catch (error) {
78
+ if (error instanceof errorx_1.ErrorResourceNotFound) {
79
+ return false;
80
+ }
81
+ throw error;
82
+ }
83
+ }
84
+ async update(opts) {
85
+ await this.ensurePaymentMethodBelongsToGivenCustomer(opts.resource.id, opts.customerId);
86
+ return this.ctAPI.paymentMethod.update({
87
+ actions: opts.actions,
88
+ resource: opts.resource,
89
+ });
90
+ }
91
+ async save(opts) {
92
+ const paymentMethodExistsWithSameTokenValue = await this.doesTokenBelongsToCustomer({
93
+ customerId: opts.customerId,
94
+ paymentInterface: opts.paymentInterface,
95
+ interfaceAccount: opts.interfaceAccount,
96
+ tokenValue: opts.token,
97
+ });
98
+ if (paymentMethodExistsWithSameTokenValue) {
99
+ throw new errorx_1.ErrorInternalConstraintViolated('A payment method with the same "token.value" already exists.', {
100
+ privateFields: {
101
+ customerId: opts.customerId,
102
+ paymentInterface: opts.paymentInterface,
103
+ interfaceAccount: opts.interfaceAccount,
104
+ },
105
+ });
106
+ }
107
+ return await this.ctAPI.paymentMethod.create({
108
+ customer: {
109
+ id: opts.customerId,
110
+ typeId: 'customer',
111
+ },
112
+ paymentInterface: opts.paymentInterface,
113
+ interfaceAccount: opts.interfaceAccount,
114
+ method: opts.method,
115
+ default: false,
116
+ paymentMethodStatus: 'Active',
117
+ token: {
118
+ value: opts.token,
119
+ },
120
+ ...(opts.customFields ? { custom: opts.customFields } : {}),
121
+ });
122
+ }
123
+ async delete(opts) {
124
+ await this.ensurePaymentMethodBelongsToGivenCustomer(opts.id, opts.customerId);
125
+ return await this.ctAPI.paymentMethod.delete({
126
+ id: opts.id,
127
+ version: opts.version,
128
+ });
129
+ }
130
+ async ensurePaymentMethodBelongsToGivenCustomer(paymentMethodId, customerId) {
131
+ const predicate = `id="${paymentMethodId}" and customer(id="${customerId}")`;
132
+ const doesGivenPaymentMethodBelongToGivenCustomer = await this.ctAPI.paymentMethod.checkIfExistsByPredicate({
133
+ queryString: predicate,
134
+ });
135
+ if (!doesGivenPaymentMethodBelongToGivenCustomer) {
136
+ throw new errorx_1.ErrorInternalConstraintViolated(`The provided payment-method '${paymentMethodId}' does not have a customer '${customerId}' set`, {
137
+ fields: {
138
+ paymentMethodId: paymentMethodId,
139
+ customerId: customerId,
140
+ },
141
+ privateFields: {
142
+ predicateQueryString: predicate,
143
+ },
144
+ });
145
+ }
146
+ }
147
+ }
148
+ exports.DefaultPaymentMethodService = DefaultPaymentMethodService;
@@ -1,5 +1,13 @@
1
1
  import { Payment, PaymentDraft, PaymentUpdateAction, Transaction } from '@commercetools/platform-sdk';
2
2
  import { FindPaymentsByInterfaceId, FindTransaction, GetPayment, PaymentService, PaymentServiceOptions, TransactionData, UpdatePayment } from '../types/payment.type';
3
+ declare module '@commercetools/platform-sdk' {
4
+ interface PaymentDraft {
5
+ checkoutTransactionItemId?: string;
6
+ }
7
+ interface Payment {
8
+ checkoutTransactionItemId?: string;
9
+ }
10
+ }
3
11
  /**
4
12
  * This is the default implementation of the PaymentService interface.
5
13
  */
@@ -14,9 +22,16 @@ export declare class DefaultPaymentService implements PaymentService {
14
22
  private consolidateUpdateActions;
15
23
  private populateSetInterfaceIdAction;
16
24
  private populateChangeTransactionInteractionId;
25
+ private populateSetTransactionInterfaceId;
17
26
  private populateAddTransactionAction;
18
27
  private populateChangeTransactionState;
19
28
  private populateSetPaymentMethod;
29
+ private populateSetMethodInfoToken;
30
+ private populateSetMethodInfoInterface;
31
+ private populateSetMethodInfoName;
32
+ private populateSetMethodInfoInterfaceAccount;
33
+ private populateSetMethodInfoCustomType;
34
+ private populateSetMethodInfoCustomField;
20
35
  private populateSetCustomType;
21
36
  private populateAddInterfaceInteractions;
22
37
  findMatchingTransactions(payment: Payment, transaction: TransactionData): Transaction[];
@@ -26,5 +41,6 @@ export declare class DefaultPaymentService implements PaymentService {
26
41
  private handleTransactionUpdates;
27
42
  private shouldUpdateTransactionState;
28
43
  private shouldUpdateInteractionId;
44
+ private shouldUpdateTransactionInterfaceId;
29
45
  private throwMultipleMatchingTransactionsError;
30
46
  }