@commercetools/connect-payments-sdk 0.0.1

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 (68) hide show
  1. package/.github/workflows/ci.yml +34 -0
  2. package/.github/workflows/release.yml +46 -0
  3. package/.husky/pre-commit +4 -0
  4. package/CHANGELOG.md +7 -0
  5. package/README.md +19 -0
  6. package/dist/api/context/request-context.provider.d.ts +14 -0
  7. package/dist/api/context/request-context.provider.js +21 -0
  8. package/dist/api/context/types/request-context.type.d.ts +16 -0
  9. package/dist/api/context/types/request-context.type.js +2 -0
  10. package/dist/api/handlers/config.handler.d.ts +4 -0
  11. package/dist/api/handlers/config.handler.js +10 -0
  12. package/dist/api/handlers/status.handler.d.ts +25 -0
  13. package/dist/api/handlers/status.handler.js +73 -0
  14. package/dist/api/handlers/types/handler.type.d.ts +5 -0
  15. package/dist/api/handlers/types/handler.type.js +2 -0
  16. package/dist/api/hooks/session-auth.hook.d.ts +15 -0
  17. package/dist/api/hooks/session-auth.hook.js +31 -0
  18. package/dist/api/index.d.ts +5 -0
  19. package/dist/api/index.js +21 -0
  20. package/dist/commercetools/api/base-api.d.ts +7 -0
  21. package/dist/commercetools/api/base-api.js +22 -0
  22. package/dist/commercetools/api/cart-api.d.ts +8 -0
  23. package/dist/commercetools/api/cart-api.js +34 -0
  24. package/dist/commercetools/api/payment-api.d.ts +10 -0
  25. package/dist/commercetools/api/payment-api.js +40 -0
  26. package/dist/commercetools/api/root-api.d.ts +15 -0
  27. package/dist/commercetools/api/root-api.js +45 -0
  28. package/dist/commercetools/errors/ct-api.error.d.ts +13 -0
  29. package/dist/commercetools/errors/ct-api.error.js +17 -0
  30. package/dist/commercetools/index.d.ts +2 -0
  31. package/dist/commercetools/index.js +2 -0
  32. package/dist/commercetools/services/ct-cart.service.d.ts +14 -0
  33. package/dist/commercetools/services/ct-cart.service.js +54 -0
  34. package/dist/commercetools/services/ct-payment.service.d.ts +20 -0
  35. package/dist/commercetools/services/ct-payment.service.js +129 -0
  36. package/dist/commercetools/types/api.type.d.ts +32 -0
  37. package/dist/commercetools/types/api.type.js +2 -0
  38. package/dist/commercetools/types/cart.type.d.ts +21 -0
  39. package/dist/commercetools/types/cart.type.js +2 -0
  40. package/dist/commercetools/types/payment.type.d.ts +38 -0
  41. package/dist/commercetools/types/payment.type.js +2 -0
  42. package/dist/errorx/errorx.d.ts +150 -0
  43. package/dist/errorx/errorx.js +326 -0
  44. package/dist/errorx/index.d.ts +1 -0
  45. package/dist/errorx/index.js +17 -0
  46. package/dist/fetch/decorators/base.decorator.d.ts +9 -0
  47. package/dist/fetch/decorators/base.decorator.js +12 -0
  48. package/dist/fetch/decorators/monitoring.decorator.d.ts +13 -0
  49. package/dist/fetch/decorators/monitoring.decorator.js +32 -0
  50. package/dist/fetch/types/fetch.type.d.ts +6 -0
  51. package/dist/fetch/types/fetch.type.js +2 -0
  52. package/dist/index.d.ts +33 -0
  53. package/dist/index.js +74 -0
  54. package/dist/logger/index.d.ts +1 -0
  55. package/dist/logger/index.js +17 -0
  56. package/dist/logger/logger.d.ts +6 -0
  57. package/dist/logger/logger.js +2 -0
  58. package/dist/security/auth/session.auth.d.ts +20 -0
  59. package/dist/security/auth/session.auth.js +54 -0
  60. package/dist/security/index.d.ts +3 -0
  61. package/dist/security/index.js +19 -0
  62. package/dist/security/services/oauth2.service.d.ts +16 -0
  63. package/dist/security/services/oauth2.service.js +53 -0
  64. package/dist/security/types/oauth2.type.d.ts +13 -0
  65. package/dist/security/types/oauth2.type.js +2 -0
  66. package/dist/security/types/session.type.d.ts +10 -0
  67. package/dist/security/types/session.type.js +2 -0
  68. package/package.json +21 -0
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultCartService = void 0;
4
+ const ct_api_error_1 = require("../errors/ct-api.error");
5
+ /**
6
+ * Default implementation of the CartService interface.
7
+ */
8
+ class DefaultCartService {
9
+ ctAPI;
10
+ constructor(opts) {
11
+ this.ctAPI = opts.ctAPI;
12
+ }
13
+ async getCart(opts) {
14
+ return await this.ctAPI.cart.getCartById(opts.id);
15
+ }
16
+ getPaymentAmount(opts) {
17
+ if (opts.cart.taxedPrice) {
18
+ return {
19
+ currencyCode: opts.cart.taxedPrice.totalGross.currencyCode,
20
+ centAmount: opts.cart.taxedPrice.totalGross.centAmount,
21
+ };
22
+ }
23
+ return {
24
+ currencyCode: opts.cart.totalPrice.currencyCode,
25
+ centAmount: opts.cart.totalPrice.centAmount,
26
+ };
27
+ }
28
+ async addPayment(opts) {
29
+ const maxRetries = 6;
30
+ let cartVersion = opts.resource.version;
31
+ let err;
32
+ for (let retries = 0; retries < maxRetries; retries++) {
33
+ try {
34
+ return await this.ctAPI.cart.addPayment({
35
+ resource: { id: opts.resource.id, version: cartVersion },
36
+ paymentId: opts.paymentId,
37
+ });
38
+ }
39
+ catch (e) {
40
+ err = e;
41
+ if (e instanceof ct_api_error_1.CommercetoolsAPIError && e.httpErrorStatus === 409) {
42
+ const cart = await this.getCart({ id: opts.resource.id });
43
+ cartVersion = cart.version;
44
+ retries++;
45
+ }
46
+ else {
47
+ throw e;
48
+ }
49
+ }
50
+ }
51
+ throw err;
52
+ }
53
+ }
54
+ exports.DefaultCartService = DefaultCartService;
@@ -0,0 +1,20 @@
1
+ import { Payment, PaymentDraft } from '@commercetools/platform-sdk';
2
+ import { GetPayment, PaymentService, PaymentServiceOptions, UpdatePayment } from '../types/payment.type';
3
+ /**
4
+ * This is the default implementation of the PaymentService interface.
5
+ */
6
+ export declare class DefaultPaymentService implements PaymentService {
7
+ private ctAPI;
8
+ constructor(opts: PaymentServiceOptions);
9
+ getPayment(opts: GetPayment): Promise<Payment>;
10
+ createPayment(draft: PaymentDraft): Promise<Payment>;
11
+ updatePayment(opts: UpdatePayment): Promise<Payment>;
12
+ private consolidateUpdateActions;
13
+ private populateSetInterfaceIdAction;
14
+ private populateChangeTransactionInteractionId;
15
+ private populateAddTransactionAction;
16
+ private populateChangeTransactionState;
17
+ private populateSetPaymentMethod;
18
+ private findMatchingTransactions;
19
+ private consolidateTransactionChanges;
20
+ }
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultPaymentService = void 0;
4
+ const ct_api_error_1 = require("../errors/ct-api.error");
5
+ /**
6
+ * This is the default implementation of the PaymentService interface.
7
+ */
8
+ class DefaultPaymentService {
9
+ ctAPI;
10
+ constructor(opts) {
11
+ this.ctAPI = opts.ctAPI;
12
+ }
13
+ async getPayment(opts) {
14
+ return await this.ctAPI.payment.getPaymentById(opts.id);
15
+ }
16
+ async createPayment(draft) {
17
+ return await this.ctAPI.payment.createPayment(draft);
18
+ }
19
+ async updatePayment(opts) {
20
+ const maxRetries = 3;
21
+ let err;
22
+ for (let retries = 0; retries < maxRetries; retries++) {
23
+ const payment = await this.getPayment({ id: opts.id });
24
+ const actions = this.consolidateUpdateActions(payment, opts);
25
+ try {
26
+ const updatedPayment = await this.ctAPI.payment.updatePayment({
27
+ resource: {
28
+ id: payment.id,
29
+ version: payment.version,
30
+ },
31
+ actions,
32
+ });
33
+ return updatedPayment;
34
+ }
35
+ catch (e) {
36
+ err = e;
37
+ if (e instanceof ct_api_error_1.CommercetoolsAPIError && e.httpErrorStatus === 409) {
38
+ retries++;
39
+ }
40
+ else {
41
+ throw e;
42
+ }
43
+ }
44
+ }
45
+ throw err;
46
+ }
47
+ consolidateUpdateActions(payment, updateInfo) {
48
+ const actions = [];
49
+ if (!payment.interfaceId && updateInfo.pspReference) {
50
+ actions.push(this.populateSetInterfaceIdAction(updateInfo.pspReference));
51
+ }
52
+ if (!payment.paymentMethodInfo.method && updateInfo.paymentMethod) {
53
+ actions.push(this.populateSetPaymentMethod(updateInfo.paymentMethod));
54
+ }
55
+ if (updateInfo.transaction) {
56
+ actions.push(...this.consolidateTransactionChanges(payment, updateInfo.transaction));
57
+ }
58
+ return actions;
59
+ }
60
+ populateSetInterfaceIdAction(interfaceId) {
61
+ return {
62
+ action: 'setInterfaceId',
63
+ interfaceId,
64
+ };
65
+ }
66
+ populateChangeTransactionInteractionId(txId, interactionId) {
67
+ return {
68
+ action: 'changeTransactionInteractionId',
69
+ transactionId: txId,
70
+ interactionId,
71
+ };
72
+ }
73
+ populateAddTransactionAction(draft) {
74
+ return {
75
+ action: 'addTransaction',
76
+ transaction: {
77
+ ...draft,
78
+ timestamp: new Date().toISOString(),
79
+ },
80
+ };
81
+ }
82
+ populateChangeTransactionState(txId, state) {
83
+ return {
84
+ action: 'changeTransactionState',
85
+ transactionId: txId,
86
+ state,
87
+ };
88
+ }
89
+ populateSetPaymentMethod(paymentMethod) {
90
+ return {
91
+ action: 'setMethodInfoMethod',
92
+ method: paymentMethod,
93
+ };
94
+ }
95
+ findMatchingTransactions(payment, transaction) {
96
+ return payment.transactions.filter((tx) => {
97
+ return (tx.type === transaction.type &&
98
+ tx.amount.centAmount === transaction.amount.centAmount &&
99
+ tx.amount.currencyCode === transaction.amount.currencyCode &&
100
+ transaction.interactionId &&
101
+ ((tx.interactionId && tx.interactionId === transaction.interactionId) ||
102
+ (!tx.interactionId && tx.state === 'Initial')));
103
+ });
104
+ }
105
+ consolidateTransactionChanges(payment, transaction) {
106
+ const actions = [];
107
+ const matchingTxs = this.findMatchingTransactions(payment, transaction);
108
+ if (matchingTxs.length === 0) {
109
+ actions.push(this.populateAddTransactionAction(transaction));
110
+ }
111
+ else {
112
+ if (matchingTxs.length === 1) {
113
+ const tx = matchingTxs[0];
114
+ if ((tx.state !== transaction.state && tx.state === 'Initial') ||
115
+ (tx.state === 'Pending' && (transaction.state === 'Success' || transaction.state === 'Failure'))) {
116
+ actions.push(this.populateChangeTransactionState(tx.id, transaction.state));
117
+ if (!tx.interactionId && transaction.interactionId) {
118
+ actions.push(this.populateChangeTransactionInteractionId(tx.id, transaction.interactionId));
119
+ }
120
+ }
121
+ }
122
+ else {
123
+ throw new Error('Multiple transactions found');
124
+ }
125
+ }
126
+ return actions;
127
+ }
128
+ }
129
+ exports.DefaultPaymentService = DefaultPaymentService;
@@ -0,0 +1,32 @@
1
+ import { Cart, Payment, PaymentDraft, PaymentPagedQueryResponse, PaymentUpdateAction } from '@commercetools/platform-sdk';
2
+ import { ByProjectKeyRequestBuilder } from '@commercetools/platform-sdk/dist/declarations/src/generated/client/by-project-key-request-builder';
3
+ export type CommercetoolsClient = ByProjectKeyRequestBuilder;
4
+ export interface APIOpts {
5
+ client: CommercetoolsClient;
6
+ }
7
+ export type UpdateResource = {
8
+ id: string;
9
+ version: number;
10
+ };
11
+ export type AddPayment = {
12
+ resource: UpdateResource;
13
+ paymentId: string;
14
+ };
15
+ export type UpdatePayment = {
16
+ resource: UpdateResource;
17
+ actions: PaymentUpdateAction[];
18
+ };
19
+ export interface CartAPI {
20
+ getCartById(id: string): Promise<Cart>;
21
+ addPayment(opts: AddPayment): Promise<Cart>;
22
+ }
23
+ export interface PaymentAPI {
24
+ getPaymentById(id: string): Promise<Payment>;
25
+ find(queryPredicate: string): Promise<PaymentPagedQueryResponse>;
26
+ createPayment(paymentDraft: PaymentDraft): Promise<Payment>;
27
+ updatePayment(opts: UpdatePayment): Promise<Payment>;
28
+ }
29
+ export interface CommercetoolsAPI {
30
+ cart: CartAPI;
31
+ payment: PaymentAPI;
32
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,21 @@
1
+ import { Cart } from '@commercetools/platform-sdk';
2
+ import { AddPayment, CommercetoolsAPI } from './api.type';
3
+ import { PaymentAmount } from './payment.type';
4
+ export type GetCart = {
5
+ id: string;
6
+ version?: number;
7
+ };
8
+ export type GetPaymentAmount = {
9
+ cart: Cart;
10
+ };
11
+ export type CartServiceOptions = {
12
+ ctAPI: CommercetoolsAPI;
13
+ };
14
+ /**
15
+ * Cart service interface exposes methods to interact with the commercetools platform API.
16
+ */
17
+ export interface CartService {
18
+ getCart(opts: GetCart): Promise<Cart>;
19
+ getPaymentAmount(opts: GetPaymentAmount): PaymentAmount;
20
+ addPayment(opts: AddPayment): Promise<Cart>;
21
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,38 @@
1
+ import { Money, Payment, PaymentDraft, TransactionState, TransactionType } from '@commercetools/platform-sdk';
2
+ import { CommercetoolsAPI } from './api.type';
3
+ export type PaymentAmount = {
4
+ centAmount: number;
5
+ currencyCode: string;
6
+ };
7
+ export type PaymentServiceOptions = {
8
+ ctAPI: CommercetoolsAPI;
9
+ };
10
+ export type GetPayment = {
11
+ id: string;
12
+ version?: number;
13
+ };
14
+ export type PSPInteraction = {
15
+ request?: string;
16
+ response?: string;
17
+ };
18
+ export type TransactionData = {
19
+ type: TransactionType;
20
+ amount: Money;
21
+ interactionId?: string;
22
+ state: TransactionState;
23
+ };
24
+ export type UpdatePayment = {
25
+ id: string;
26
+ pspReference?: string;
27
+ pspInteraction?: PSPInteraction;
28
+ transaction?: TransactionData;
29
+ paymentMethod?: string;
30
+ };
31
+ /**
32
+ * Payment service interface exposes methods to interact with the commercetools platform API.
33
+ */
34
+ export interface PaymentService {
35
+ getPayment(opts: GetPayment): Promise<Payment>;
36
+ createPayment(draft: PaymentDraft): Promise<Payment>;
37
+ updatePayment(opts: UpdatePayment): Promise<Payment>;
38
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,150 @@
1
+ export type ErrorxAdditionalOpts = {
2
+ privateFields?: object;
3
+ privateMessage?: string;
4
+ fields?: object;
5
+ skipLog?: boolean;
6
+ cause?: Error | unknown;
7
+ };
8
+ export type ErrorxBaseOpts = {
9
+ message: string;
10
+ code: string;
11
+ httpErrorStatus: number;
12
+ };
13
+ export type ErrorxOpts = ErrorxBaseOpts & ErrorxAdditionalOpts;
14
+ /**
15
+ * Errorx is a custom error class that extends the native Error class.
16
+ */
17
+ export declare class Errorx extends Error {
18
+ code: string;
19
+ httpErrorStatus: number;
20
+ cause?: Error | unknown;
21
+ privateFields?: object;
22
+ privateMessage?: string;
23
+ fields?: object;
24
+ skipLog?: boolean;
25
+ constructor(opts: ErrorxOpts);
26
+ }
27
+ export declare class MultiErrorx extends Error {
28
+ errors: Errorx[];
29
+ constructor(errors: Errorx[]);
30
+ }
31
+ /**
32
+ * AuthErrorResponse (https://docs.commercetools.com/api/errors#autherrorresponse)
33
+ * Represents errors related to authentication and authorization in a format conforming to the OAuth 2.0 specification.
34
+ * {
35
+ * "statusCode": 401,
36
+ * "message": "invalid_token",
37
+ * "errors": [
38
+ * {
39
+ * "code": "invalid_token",
40
+ * "message": "invalid_token"
41
+ * }
42
+ * ],
43
+ * "error": "invalid_token"
44
+ * }
45
+ */
46
+ export declare class ErrorAuthErrorResponse extends Errorx {
47
+ constructor(additionalOpts?: ErrorxAdditionalOpts);
48
+ }
49
+ /**
50
+ * General (https://docs.commercetools.com/api/errors#general)
51
+ * Returned when a server-side problem occurs.
52
+ */
53
+ export declare class ErrorGeneral extends Errorx {
54
+ constructor(msg?: string, additionalOpts?: ErrorxAdditionalOpts);
55
+ }
56
+ /**
57
+ * MissingProjectKey
58
+ * Missing the project key in the path.
59
+ */
60
+ export declare class ErrorMissingProjectKey extends Errorx {
61
+ constructor(additionalOpts?: ErrorxAdditionalOpts);
62
+ }
63
+ /**
64
+ * InvalidJsonInput (https://docs.commercetools.com/api/errors#invalidjsoninput)
65
+ * Returned when an invalid JSON input has been sent. Either the JSON is syntactically incorrect or does not conform to the expected shape (for example is missing a required field).
66
+ *
67
+ * The client application should validate the input according to the constraints described in the error message before sending the request.
68
+ */
69
+ export declare class ErrorInvalidJsonInput extends Errorx {
70
+ constructor(detailedErrorMessage?: string, additionalOpts?: ErrorxAdditionalOpts);
71
+ }
72
+ /**
73
+ * InvalidOperation (https://docs.commercetools.com/api/errors#invalidoperation)
74
+ * Returned when the resources involved in the request are not in a valid state for the operation.
75
+ *
76
+ * The client application should validate the constraints described in the error message before sending the request.
77
+ */
78
+ export declare class ErrorInvalidOperation extends Errorx {
79
+ constructor(message: string, additionalOpts?: ErrorxAdditionalOpts);
80
+ }
81
+ /**
82
+ * InvalidField (https://docs.commercetools.com/api/errors#invalidfield)
83
+ * Returned when a field has an invalid value.
84
+ */
85
+ export declare class ErrorInvalidField extends Errorx {
86
+ constructor(field: string, invalidValue: string, allowedValues: string, additionalOpts?: ErrorxAdditionalOpts);
87
+ }
88
+ /**
89
+ * InternalConstraintViolated (https://docs.commercetools.com/api/errors#internalconstraintviolated)
90
+ * Returned when certain API-specific constraints were not met. For example, the specified Discount Code was never applied and cannot be updated.
91
+ */
92
+ export declare class ErrorInternalConstraintViolated extends Errorx {
93
+ constructor(message: string, additionalOpts?: ErrorxAdditionalOpts);
94
+ }
95
+ /**
96
+ * MoneyOverflow (https://docs.commercetools.com/api/errors#moneyoverflow)
97
+ * Returned when a Money operation overflows the 64-bit integer range. See Money usage for more information.
98
+ */
99
+ export declare class ErrorMoneyOverflow extends Errorx {
100
+ constructor(limit: number, resourceTypeId: string, additionalOpts?: ErrorxAdditionalOpts);
101
+ }
102
+ /**
103
+ * ObjectNotFound (https://docs.commercetools.com/api/errors#objectnotfound)
104
+ * Returned when the requested resource was not found.
105
+ */
106
+ export declare class ErrorObjectNotFound extends Errorx {
107
+ constructor(resourceTypeId: string, id: string, additionalOpts?: ErrorxAdditionalOpts);
108
+ }
109
+ /**
110
+ * InvalidField (https://docs.commercetools.com/api/errors#invalidfield)
111
+ * Returned when a field has an invalid value.
112
+ */
113
+ export declare class ErrorReferenceExists extends Errorx {
114
+ constructor(resource: string, referencedBy?: string, additionalOpts?: ErrorxAdditionalOpts);
115
+ }
116
+ /**
117
+ * ReferencedResourceNotFound (https://docs.commercetools.com/api/errors#referencedresourcenotfound)
118
+ * Returned when a resource referenced by a Reference or a ResourceIdentifier could not be found.
119
+ */
120
+ export declare class ErrorReferencedResourceNotFound extends Errorx {
121
+ constructor(typeId: string, id?: string, key?: string, additionalOpts?: ErrorxAdditionalOpts);
122
+ }
123
+ /**
124
+ * ReferencedResourceNotFound (https://docs.commercetools.com/api/errors#referencedresourcenotfound)
125
+ * Returned when a resource referenced by a Reference or a ResourceIdentifier could not be found.
126
+ */
127
+ export declare class ErrorRequiredField extends Errorx {
128
+ constructor(field: string, additionalOpts?: ErrorxAdditionalOpts);
129
+ }
130
+ /**
131
+ * SyntaxError (https://docs.commercetools.com/api/errors#syntaxerror)
132
+ * Returned when a Discount predicate, API Extension predicate, or search query does not have the correct syntax.
133
+ */
134
+ export declare class ErrorSyntaxError extends Errorx {
135
+ constructor(fieldDefinition: string, additionalOpts?: ErrorxAdditionalOpts);
136
+ }
137
+ /**
138
+ * ResourceNotFound (https://docs.commercetools.com/api/errors#resourcenotfound)
139
+ * Returned when the resource addressed by the request URL does not exist.
140
+ */
141
+ export declare class ErrorResourceNotFound extends Errorx {
142
+ constructor(resourceId: string, additionalOpts?: ErrorxAdditionalOpts);
143
+ }
144
+ /**
145
+ * ConcurrentModification (https://docs.commercetools.com/api/errors#concurrentmodification)
146
+ * Returned when the request conflicts with the current state of the involved resources. Typically, the request attempts to modify a resource that is out of date (that is modified by another client since it was last retrieved). The client application should resolve the conflict (with or without involving the end-user) before retrying the request.
147
+ */
148
+ export declare class ErrorConcurrentModification extends Errorx {
149
+ constructor(resourceId: string, expectedVersion: number, currentVersion: number, additionalOpts?: ErrorxAdditionalOpts);
150
+ }