@unchainedshop/plugins 4.7.2 → 4.8.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 (184) hide show
  1. package/README.md +2 -0
  2. package/lib/delivery/post.d.ts +1 -0
  3. package/lib/delivery/post.js +23 -0
  4. package/lib/delivery/send-message.d.ts +1 -0
  5. package/lib/delivery/send-message.js +40 -0
  6. package/lib/delivery/stores.d.ts +1 -0
  7. package/lib/delivery/stores.js +43 -0
  8. package/lib/enrollments/licensed.d.ts +4 -0
  9. package/lib/enrollments/licensed.js +52 -0
  10. package/lib/events/node-event-emitter.d.ts +1 -3
  11. package/lib/events/node-event-emitter.js +3 -3
  12. package/lib/files/gridfs/adapter.d.ts +2 -2
  13. package/lib/files/gridfs/adapter.js +5 -2
  14. package/lib/files/gridfs/handler-express.d.ts +9 -0
  15. package/lib/files/gridfs/handler-express.js +110 -0
  16. package/lib/files/gridfs/handler-fastify.d.ts +3 -0
  17. package/lib/files/gridfs/handler-fastify.js +138 -0
  18. package/lib/files/gridfs/index.d.ts +4 -5
  19. package/lib/files/gridfs/index.js +3 -30
  20. package/lib/files/minio/handler-express.d.ts +2 -0
  21. package/lib/files/minio/handler-express.js +36 -0
  22. package/lib/files/minio/handler-fastify.d.ts +3 -0
  23. package/lib/files/minio/handler-fastify.js +40 -0
  24. package/lib/files/minio/index.d.ts +5 -4
  25. package/lib/files/minio/index.js +157 -18
  26. package/lib/filters/local-search.d.ts +3 -0
  27. package/lib/filters/local-search.js +66 -0
  28. package/lib/filters/strict-equal.d.ts +1 -0
  29. package/lib/filters/strict-equal.js +24 -0
  30. package/lib/payment/apple-iap/adapter.d.ts +1 -2
  31. package/lib/payment/apple-iap/adapter.js +3 -2
  32. package/lib/payment/apple-iap/handler-express.d.ts +2 -0
  33. package/lib/payment/apple-iap/handler-express.js +103 -0
  34. package/lib/payment/apple-iap/handler-fastify.d.ts +3 -0
  35. package/lib/payment/apple-iap/handler-fastify.js +102 -0
  36. package/lib/payment/apple-iap/index.d.ts +4 -6
  37. package/lib/payment/apple-iap/index.js +3 -28
  38. package/lib/payment/braintree.d.ts +1 -0
  39. package/lib/payment/braintree.js +138 -0
  40. package/lib/payment/cryptopay/handler-express.d.ts +2 -0
  41. package/lib/payment/cryptopay/handler-express.js +19 -0
  42. package/lib/payment/cryptopay/handler-fastify.d.ts +3 -0
  43. package/lib/payment/cryptopay/handler-fastify.js +17 -0
  44. package/lib/payment/cryptopay/index.d.ts +4 -5
  45. package/lib/payment/cryptopay/index.js +3 -31
  46. package/lib/payment/cryptopay/plugin.d.ts +3 -0
  47. package/lib/payment/cryptopay/plugin.js +159 -0
  48. package/lib/payment/datatrans-v2/handler-express.d.ts +1 -0
  49. package/lib/payment/datatrans-v2/handler-express.js +71 -0
  50. package/lib/payment/datatrans-v2/handler-fastify.d.ts +2 -0
  51. package/lib/payment/datatrans-v2/handler-fastify.js +71 -0
  52. package/lib/payment/datatrans-v2/index.d.ts +1 -4
  53. package/lib/payment/datatrans-v2/index.js +400 -17
  54. package/lib/payment/invoice-prepaid.d.ts +1 -0
  55. package/lib/payment/invoice-prepaid.js +30 -0
  56. package/lib/payment/invoice.d.ts +1 -0
  57. package/lib/payment/invoice.js +27 -0
  58. package/lib/payment/paypal-checkout.d.ts +1 -0
  59. package/lib/payment/paypal-checkout.js +87 -0
  60. package/lib/payment/payrexx/handler-express.d.ts +1 -0
  61. package/lib/payment/payrexx/handler-express.js +85 -0
  62. package/lib/payment/payrexx/handler-fastify.d.ts +2 -0
  63. package/lib/payment/payrexx/handler-fastify.js +91 -0
  64. package/lib/payment/payrexx/index.d.ts +1 -4
  65. package/lib/payment/payrexx/index.js +158 -19
  66. package/lib/payment/postfinance-checkout/handler-express.d.ts +1 -0
  67. package/lib/payment/postfinance-checkout/handler-express.js +37 -0
  68. package/lib/payment/postfinance-checkout/handler-fastify.d.ts +2 -0
  69. package/lib/payment/postfinance-checkout/handler-fastify.js +40 -0
  70. package/lib/payment/postfinance-checkout/index.d.ts +0 -5
  71. package/lib/payment/postfinance-checkout/index.js +186 -25
  72. package/lib/payment/saferpay/adapter.js +2 -1
  73. package/lib/payment/saferpay/handler-express.d.ts +1 -0
  74. package/lib/payment/saferpay/handler-express.js +59 -0
  75. package/lib/payment/saferpay/handler-fastify.d.ts +2 -0
  76. package/lib/payment/saferpay/handler-fastify.js +62 -0
  77. package/lib/payment/saferpay/index.d.ts +4 -5
  78. package/lib/payment/saferpay/index.js +3 -29
  79. package/lib/payment/stripe/handler-express.d.ts +5 -0
  80. package/lib/payment/stripe/handler-express.js +121 -0
  81. package/lib/payment/stripe/handler-fastify.d.ts +6 -0
  82. package/lib/payment/stripe/handler-fastify.js +131 -0
  83. package/lib/payment/stripe/index.d.ts +1 -4
  84. package/lib/payment/stripe/index.js +116 -22
  85. package/lib/payment/stripe/stripe.js +4 -1
  86. package/lib/presets/all-express.d.ts +6 -0
  87. package/lib/presets/all-express.js +26 -0
  88. package/lib/presets/all-fastify.d.ts +6 -0
  89. package/lib/presets/all-fastify.js +49 -0
  90. package/lib/presets/all.d.ts +70 -1
  91. package/lib/presets/all.js +27 -41
  92. package/lib/presets/base-express.d.ts +2 -0
  93. package/lib/presets/base-express.js +5 -0
  94. package/lib/presets/base-fastify.d.ts +3 -0
  95. package/lib/presets/base-fastify.js +16 -0
  96. package/lib/presets/base.d.ts +25 -1
  97. package/lib/presets/base.js +25 -56
  98. package/lib/presets/countries/ch.d.ts +2 -1
  99. package/lib/presets/countries/ch.js +2 -7
  100. package/lib/presets/crypto-express.d.ts +3 -0
  101. package/lib/presets/crypto-express.js +8 -0
  102. package/lib/presets/crypto-fastify.d.ts +3 -0
  103. package/lib/presets/crypto-fastify.js +11 -0
  104. package/lib/presets/crypto.d.ts +7 -3
  105. package/lib/presets/crypto.js +7 -18
  106. package/lib/pricing/delivery-swiss-tax.d.ts +2 -0
  107. package/lib/pricing/delivery-swiss-tax.js +62 -0
  108. package/lib/pricing/discount-100-off.d.ts +2 -0
  109. package/lib/pricing/discount-100-off.js +30 -0
  110. package/lib/pricing/discount-half-price-manual.d.ts +2 -0
  111. package/lib/pricing/discount-half-price-manual.js +30 -0
  112. package/lib/pricing/discount-half-price.d.ts +2 -0
  113. package/lib/pricing/discount-half-price.js +33 -0
  114. package/lib/pricing/free-delivery.d.ts +2 -0
  115. package/lib/pricing/free-delivery.js +27 -0
  116. package/lib/pricing/free-payment.d.ts +2 -0
  117. package/lib/pricing/free-payment.js +27 -0
  118. package/lib/pricing/order-delivery.d.ts +2 -0
  119. package/lib/pricing/order-delivery.js +33 -0
  120. package/lib/pricing/order-discount.d.ts +2 -0
  121. package/lib/pricing/order-discount.js +74 -0
  122. package/lib/pricing/order-items-discount.d.ts +2 -0
  123. package/lib/pricing/order-items-discount.js +50 -0
  124. package/lib/pricing/order-items.d.ts +2 -0
  125. package/lib/pricing/order-items.js +43 -0
  126. package/lib/pricing/order-payment.d.ts +2 -0
  127. package/lib/pricing/order-payment.js +33 -0
  128. package/lib/pricing/order-round.d.ts +10 -0
  129. package/lib/pricing/order-round.js +135 -0
  130. package/lib/pricing/product-catalog-price-options.d.ts +2 -0
  131. package/lib/pricing/product-catalog-price-options.js +51 -0
  132. package/lib/pricing/product-catalog-price.d.ts +2 -0
  133. package/lib/pricing/product-catalog-price.js +60 -0
  134. package/lib/pricing/product-discount.d.ts +2 -0
  135. package/lib/pricing/product-discount.js +69 -0
  136. package/lib/pricing/product-price-rateconversion.d.ts +2 -0
  137. package/lib/pricing/product-price-rateconversion.js +53 -0
  138. package/lib/pricing/product-round.d.ts +10 -0
  139. package/lib/pricing/product-round.js +44 -0
  140. package/lib/pricing/product-swiss-tax.d.ts +2 -0
  141. package/lib/pricing/product-swiss-tax.js +76 -0
  142. package/lib/quotations/manual.d.ts +1 -0
  143. package/lib/quotations/manual.js +20 -0
  144. package/lib/warehousing/eth-minter.d.ts +1 -0
  145. package/lib/warehousing/eth-minter.js +120 -0
  146. package/lib/warehousing/store.d.ts +1 -0
  147. package/lib/warehousing/store.js +34 -0
  148. package/lib/worker/budgetsms.d.ts +9 -0
  149. package/lib/worker/budgetsms.js +169 -0
  150. package/lib/worker/bulk-export.d.ts +2 -0
  151. package/lib/worker/bulk-export.js +64 -0
  152. package/lib/worker/bulk-import.d.ts +2 -0
  153. package/lib/worker/bulk-import.js +65 -0
  154. package/lib/worker/bulkgate.d.ts +1 -0
  155. package/lib/worker/bulkgate.js +91 -0
  156. package/lib/worker/email.d.ts +1 -0
  157. package/lib/worker/email.js +136 -0
  158. package/lib/worker/enrollment-order-generator.d.ts +1 -0
  159. package/lib/worker/enrollment-order-generator.js +77 -0
  160. package/lib/worker/error-notifications.d.ts +9 -0
  161. package/lib/worker/error-notifications.js +61 -0
  162. package/lib/worker/export-token.d.ts +4 -0
  163. package/lib/worker/export-token.js +26 -0
  164. package/lib/worker/external.d.ts +2 -0
  165. package/lib/worker/external.js +13 -0
  166. package/lib/worker/heartbeat.d.ts +1 -0
  167. package/lib/worker/heartbeat.js +26 -0
  168. package/lib/worker/http-request.d.ts +8 -0
  169. package/lib/worker/http-request.js +56 -0
  170. package/lib/worker/message.d.ts +10 -0
  171. package/lib/worker/message.js +42 -0
  172. package/lib/worker/push-notification.d.ts +1 -0
  173. package/lib/worker/push-notification.js +87 -0
  174. package/lib/worker/twilio.d.ts +1 -0
  175. package/lib/worker/twilio.js +59 -0
  176. package/lib/worker/update-coinbase-rates.d.ts +1 -0
  177. package/lib/worker/update-coinbase-rates.js +59 -0
  178. package/lib/worker/update-ecb-rates.d.ts +1 -0
  179. package/lib/worker/update-ecb-rates.js +92 -0
  180. package/lib/worker/update-token-ownership.d.ts +3 -0
  181. package/lib/worker/update-token-ownership.js +57 -0
  182. package/lib/worker/zombie-killer.d.ts +13 -0
  183. package/lib/worker/zombie-killer.js +91 -0
  184. package/package.json +9 -14
@@ -0,0 +1,91 @@
1
+ import { createLogger } from '@unchainedshop/logger';
2
+ const logger = createLogger('unchained:payrexx:handler');
3
+ export const payrexxHandler = async (request, reply) => {
4
+ const resolvedContext = request.unchainedContext;
5
+ const { modules, services } = resolvedContext;
6
+ const { transaction } = request.body;
7
+ if (!transaction) {
8
+ logger.info(`unhandled event type`, {
9
+ type: Object.keys(request.body).join(','),
10
+ });
11
+ reply.status(200);
12
+ return reply.send({
13
+ success: false,
14
+ ignored: true,
15
+ message: `Unhandled event type: ${Object.keys(request.body).join(',')}. Supported type: transaction`,
16
+ });
17
+ }
18
+ if (transaction.referenceId === '__IGNORE_WEBHOOK__' || transaction.status === 'waiting') {
19
+ logger.info(`unhandled transaction state: ${transaction.status}`);
20
+ reply.status(200);
21
+ return reply.send({
22
+ success: false,
23
+ ignored: true,
24
+ message: `Unhandled transaction state: ${transaction.status}`,
25
+ });
26
+ }
27
+ logger.info(`Processing event`, {
28
+ transactionId: transaction.id,
29
+ });
30
+ try {
31
+ if (transaction.preAuthorizationId) {
32
+ const { referenceId: paymentProviderId, invoice } = transaction;
33
+ const userId = '';
34
+ logger.info(`register credentials for: ${userId}`);
35
+ await services.orders.registerPaymentCredentials(paymentProviderId, {
36
+ userId,
37
+ transactionContext: { gatewayId: invoice.paymentRequestId },
38
+ });
39
+ logger.info(`registration successful`, {
40
+ paymentProviderId,
41
+ userId,
42
+ });
43
+ reply.status(200);
44
+ return reply.send({
45
+ success: true,
46
+ paymentProviderId,
47
+ userId,
48
+ });
49
+ }
50
+ else {
51
+ const { referenceId: orderPaymentId, invoice } = transaction;
52
+ logger.info(`checkout with orderPaymentId: ${orderPaymentId}`);
53
+ const orderPayment = await modules.orders.payments.findOrderPayment({
54
+ orderPaymentId,
55
+ });
56
+ if (!orderPayment) {
57
+ throw new Error(`order payment not found with orderPaymentId: ${orderPaymentId}`);
58
+ }
59
+ await modules.orders.payments.logEvent(orderPaymentId, {
60
+ transactionId: transaction.id,
61
+ });
62
+ const order = await services.orders.checkoutOrder(orderPayment.orderId, {
63
+ paymentContext: {
64
+ gatewayId: invoice.paymentRequestId,
65
+ },
66
+ });
67
+ if (!order)
68
+ throw new Error(`Order with id ${orderPayment.orderId} not found`);
69
+ logger.info(`checkout successful`, {
70
+ orderPaymentId,
71
+ orderId: order._id,
72
+ });
73
+ reply.status(200);
74
+ return reply.send({
75
+ success: true,
76
+ orderId: order._id,
77
+ });
78
+ }
79
+ }
80
+ catch (error) {
81
+ logger.error(error, {
82
+ transactionId: transaction.id,
83
+ });
84
+ reply.status(500);
85
+ return reply.send({
86
+ success: false,
87
+ message: error.message,
88
+ name: error.name,
89
+ });
90
+ }
91
+ };
@@ -1,4 +1 @@
1
- import type { IPlugin } from '@unchainedshop/core';
2
- export declare const PayrexxPlugin: IPlugin;
3
- export default PayrexxPlugin;
4
- export { Payrexx } from './adapter.ts';
1
+ export {};
@@ -1,23 +1,162 @@
1
- import { Payrexx } from "./adapter.js";
2
- import { payrexxWebhookHandler } from "./api.js";
3
- const { PAYREXX_WEBHOOK_PATH = '/payment/payrexx' } = process.env;
4
- export const PayrexxPlugin = {
1
+ import { createLogger } from '@unchainedshop/logger';
2
+ import { mapOrderDataToGatewayObject, mapUserToGatewayObject } from "./payrexx.js";
3
+ import createPayrexxAPI, { GatewayObjectStatus } from "./api/index.js";
4
+ import { OrderPricingSheet, PaymentAdapter, PaymentDirector, PaymentError, } from '@unchainedshop/core';
5
+ const logger = createLogger('unchained:payrexx');
6
+ const Payrexx = {
7
+ ...PaymentAdapter,
5
8
  key: 'shop.unchained.payment.payrexx',
6
- label: 'Payrexx Payment Plugin',
9
+ label: 'Payrexx',
7
10
  version: '1.0.0',
8
- adapters: [Payrexx],
9
- routes: [
10
- {
11
- path: PAYREXX_WEBHOOK_PATH,
12
- method: 'POST',
13
- handler: payrexxWebhookHandler,
14
- },
15
- ],
16
- onRegister: () => {
17
- if (!process.env.PAYREXX_SECRET) {
18
- throw new Error('PAYREXX_SECRET not set');
19
- }
11
+ typeSupported(type) {
12
+ return type === 'GENERIC';
13
+ },
14
+ actions: (config, context) => {
15
+ const { modules } = context;
16
+ const instance = config.find((c) => c.key === 'instance')?.value;
17
+ const adapterActions = {
18
+ ...PaymentAdapter.actions(config, context),
19
+ configurationError() {
20
+ if (!process.env.PAYREXX_SECRET) {
21
+ return PaymentError.INCOMPLETE_CONFIGURATION;
22
+ }
23
+ if (!instance) {
24
+ return PaymentError.INCOMPLETE_CONFIGURATION;
25
+ }
26
+ return null;
27
+ },
28
+ isActive: () => {
29
+ if (adapterActions.configurationError() === null)
30
+ return true;
31
+ return false;
32
+ },
33
+ isPayLaterAllowed() {
34
+ return false;
35
+ },
36
+ sign: async (transactionContext = {}) => {
37
+ const { orderPayment, userId, order } = context;
38
+ if (!order)
39
+ throw new Error('No order in context, can only sign with order context');
40
+ const api = createPayrexxAPI(instance, process.env.PAYREXX_SECRET);
41
+ if (orderPayment) {
42
+ const pricing = OrderPricingSheet({
43
+ calculation: order.calculation,
44
+ currencyCode: order.currencyCode,
45
+ });
46
+ const gatewayObject = mapOrderDataToGatewayObject({ order, orderPayment, pricing }, transactionContext);
47
+ const gateway = await api.createGateway(gatewayObject);
48
+ return JSON.stringify(gateway);
49
+ }
50
+ const user = userId && (await modules.users.findUserById(userId));
51
+ if (!user)
52
+ throw new Error('User not found, can only sign registrations with user context');
53
+ const emailAddress = modules.users.primaryEmail(user)?.address;
54
+ const gateway = await api.createGateway(mapUserToGatewayObject({
55
+ userId,
56
+ emailAddress,
57
+ currencyCode: order?.currencyCode,
58
+ }));
59
+ return JSON.stringify(gateway);
60
+ },
61
+ async register() {
62
+ throw new Error('Not implemented');
63
+ return null;
64
+ },
65
+ async confirm() {
66
+ const { orderPayment } = context;
67
+ if (!orderPayment?.transactionId) {
68
+ return false;
69
+ }
70
+ const { transactionId } = orderPayment;
71
+ const api = createPayrexxAPI(instance, process.env.PAYREXX_SECRET);
72
+ const gatewayObject = await api.getGateway(transactionId);
73
+ if (!gatewayObject) {
74
+ return false;
75
+ }
76
+ if (gatewayObject.status === GatewayObjectStatus.reserved) {
77
+ const allTransactions = gatewayObject.invoices?.flatMap((invoice) => invoice.transactions);
78
+ await Promise.all(allTransactions.map(async (transaction) => api.chargePreAuthorized(transaction.id, { referenceId: '__IGNORE_WEBHOOK__' })));
79
+ return true;
80
+ }
81
+ if (gatewayObject.status === GatewayObjectStatus.confirmed) {
82
+ return true;
83
+ }
84
+ return false;
85
+ },
86
+ async cancel() {
87
+ const { orderPayment } = context;
88
+ if (!orderPayment?.transactionId) {
89
+ return false;
90
+ }
91
+ const { transactionId } = orderPayment;
92
+ const api = createPayrexxAPI(instance, process.env.PAYREXX_SECRET);
93
+ const gatewayObject = await api.getGateway(transactionId);
94
+ if (!gatewayObject) {
95
+ return false;
96
+ }
97
+ if (gatewayObject.status === GatewayObjectStatus.reserved) {
98
+ const allTransactions = gatewayObject.invoices?.flatMap((invoice) => invoice.transactions);
99
+ await Promise.all(allTransactions.map(async (transaction) => api.deleteReservation(transaction.id)));
100
+ return true;
101
+ }
102
+ if (gatewayObject.status === GatewayObjectStatus.confirmed) {
103
+ return false;
104
+ }
105
+ return true;
106
+ },
107
+ charge: async ({ gatewayId, paymentCredentials }) => {
108
+ if (!gatewayId && !paymentCredentials) {
109
+ throw new Error('You have to provide gatewayId or paymentCredentials');
110
+ }
111
+ const { order, orderPayment } = context;
112
+ if (!order)
113
+ throw new Error('No order in context, can only charge with order context');
114
+ if (!orderPayment)
115
+ throw new Error('Order payment not found');
116
+ const api = createPayrexxAPI(instance, process.env.PAYREXX_SECRET);
117
+ const gatewayObject = await api.getGateway(gatewayId);
118
+ if (!gatewayObject) {
119
+ throw new Error('Could not load gateway from the Payrexx API');
120
+ }
121
+ const pricing = OrderPricingSheet({
122
+ calculation: order.calculation,
123
+ currencyCode: order.currencyCode,
124
+ });
125
+ const { currencyCode, amount } = pricing.total({ useNetPrice: false });
126
+ if (gatewayObject.status === 'reserved' ||
127
+ gatewayObject.status === 'confirmed') {
128
+ try {
129
+ if (gatewayObject.currency !== currencyCode.toUpperCase() ||
130
+ gatewayObject.amount !== Math.round(amount)) {
131
+ throw new Error('The price has changed since the intent has been created');
132
+ }
133
+ if (gatewayObject.referenceId !== orderPayment?._id) {
134
+ throw new Error('The order payment is different from the initiating intent');
135
+ }
136
+ logger.info(`Mark as charged, status is ${gatewayObject.status}`, {
137
+ orderPaymentId: gatewayObject.referenceId,
138
+ });
139
+ return {
140
+ transactionId: gatewayId,
141
+ gatewayObject,
142
+ };
143
+ }
144
+ catch (e) {
145
+ if (gatewayObject.status === GatewayObjectStatus.reserved) {
146
+ const allTransactions = gatewayObject.invoices?.flatMap((invoice) => invoice.transactions);
147
+ await Promise.all(allTransactions.map(async (transaction) => api.deleteReservation(transaction.id)));
148
+ }
149
+ throw e;
150
+ }
151
+ }
152
+ logger.info('Charge not possible', {
153
+ orderPaymentId: gatewayObject.referenceId,
154
+ status: gatewayObject.status,
155
+ });
156
+ throw new Error(`Gateway Status ${gatewayObject.status} does not allow checkout`);
157
+ },
158
+ };
159
+ return adapterActions;
20
160
  },
21
161
  };
22
- export default PayrexxPlugin;
23
- export { Payrexx } from "./adapter.js";
162
+ PaymentDirector.registerAdapter(Payrexx);
@@ -0,0 +1 @@
1
+ export declare const postfinanceCheckoutHandler: (req: any, res: any) => Promise<void>;
@@ -0,0 +1,37 @@
1
+ import { createLogger } from '@unchainedshop/logger';
2
+ import { getTransaction, getTransactionCompletion } from "./api.js";
3
+ const logger = createLogger('unchained:postfinance-checkout:handler');
4
+ export const postfinanceCheckoutHandler = async (req, res) => {
5
+ const context = req.unchainedContext;
6
+ const { services, modules } = context;
7
+ const data = req.body;
8
+ if (data.listenerEntityTechnicalName === 'TransactionCompletion') {
9
+ try {
10
+ const transactionCompletion = await getTransactionCompletion(data.entityId);
11
+ const transaction = await getTransaction(transactionCompletion ? transactionCompletion.linkedTransaction : data.entityId);
12
+ const { orderPaymentId } = transaction.metaData;
13
+ const orderPayment = await modules.orders.payments.findOrderPayment({
14
+ orderPaymentId,
15
+ });
16
+ if (!orderPayment)
17
+ throw new Error('Order Payment not found');
18
+ const order = await services.orders.checkoutOrder(orderPayment.orderId, {
19
+ paymentContext: {
20
+ transactionId: transactionCompletion.linkedTransaction,
21
+ },
22
+ });
23
+ if (!order)
24
+ throw new Error(`Order with id ${orderPayment.orderId} not found`);
25
+ logger.info(`Transaction ${transactionCompletion.linkedTransaction} marked order payment ID ${transaction.metaData?.orderPaymentId} as paid`);
26
+ res.status(200).send(`Order marked as paid: ${order.orderNumber}`);
27
+ }
28
+ catch (e) {
29
+ logger.error(e);
30
+ res.status(500).send({ name: e.name, code: e.code, message: e.message });
31
+ }
32
+ }
33
+ else {
34
+ logger.error(`Received unknown listenerEntityTechnicalName ${data.listenerEntityTechnicalName}`);
35
+ res.status(404).end();
36
+ }
37
+ };
@@ -0,0 +1,2 @@
1
+ import type { RouteHandlerMethod } from 'fastify';
2
+ export declare const postfinanceCheckoutHandler: RouteHandlerMethod;
@@ -0,0 +1,40 @@
1
+ import { createLogger } from '@unchainedshop/logger';
2
+ import { getTransaction, getTransactionCompletion } from "./api.js";
3
+ const logger = createLogger('unchained:postfinance-checkout:handler');
4
+ export const postfinanceCheckoutHandler = async (req, reply) => {
5
+ const context = req.unchainedContext;
6
+ const { services, modules } = context;
7
+ const data = req.body;
8
+ if (data.listenerEntityTechnicalName === 'TransactionCompletion') {
9
+ try {
10
+ const transactionCompletion = await getTransactionCompletion(data.entityId);
11
+ const transaction = await getTransaction(transactionCompletion ? transactionCompletion.linkedTransaction : data.entityId);
12
+ const { orderPaymentId } = transaction.metaData;
13
+ const orderPayment = await modules.orders.payments.findOrderPayment({
14
+ orderPaymentId,
15
+ });
16
+ if (!orderPayment)
17
+ throw new Error('Order Payment not found');
18
+ const order = await services.orders.checkoutOrder(orderPayment.orderId, {
19
+ paymentContext: {
20
+ transactionId: transaction.id,
21
+ },
22
+ });
23
+ if (!order)
24
+ throw new Error(`Order with id ${orderPayment.orderId} not found`);
25
+ logger.info(`Transaction ${transaction.id} marked order payment ID ${transaction.metaData?.orderPaymentId} as paid`);
26
+ reply.status(200);
27
+ return reply.send({ success: true, orderNumber: order.orderNumber });
28
+ }
29
+ catch (e) {
30
+ logger.error(e);
31
+ reply.status(500);
32
+ return reply.send({ success: false, name: e.name, code: e.code, message: e.message });
33
+ }
34
+ }
35
+ else {
36
+ logger.error(`Received unknown listenerEntityTechnicalName ${data.listenerEntityTechnicalName}`);
37
+ reply.status(404);
38
+ return reply.send();
39
+ }
40
+ };
@@ -1,7 +1,2 @@
1
- import type { IPlugin } from '@unchainedshop/core';
2
- export declare const PostfinanceCheckoutPlugin: IPlugin;
3
- export default PostfinanceCheckoutPlugin;
4
- export { PostfinanceCheckout } from './adapter.ts';
5
1
  export * from './types.ts';
6
2
  export * from './api-types.ts';
7
- export * from './utils.ts';
@@ -1,31 +1,192 @@
1
- import { PostfinanceCheckout } from "./adapter.js";
2
- import { postfinanceCheckoutWebhookHandler } from "./webhook.js";
3
- const { PFCHECKOUT_WEBHOOK_PATH = '/payment/postfinance-checkout' } = process.env;
4
- export const PostfinanceCheckoutPlugin = {
1
+ import { createLogger } from '@unchainedshop/logger';
2
+ import { OrderPricingSheet, PaymentAdapter, PaymentDirector, PaymentError, } from '@unchainedshop/core';
3
+ import { confirmDeferredTransaction, createTransaction, getIframeJavascriptUrl, getLightboxJavascriptUrl, getPaymentPageUrl, getToken, getTransaction, refundTransaction, voidTransaction, } from "./api.js";
4
+ import { orderIsPaid } from "./utils.js";
5
+ import { CompletionModes, IntegrationModes } from "./types.js";
6
+ import { LineItemType, TokenizationMode, TransactionCompletionBehavior, TransactionState, CreationEntityState, } from "./api-types.js";
7
+ const { PFCHECKOUT_SPACE_ID, PFCHECKOUT_USER_ID, PFCHECKOUT_SECRET, PFCHECKOUT_SUCCESS_URL, PFCHECKOUT_FAILED_URL, } = process.env;
8
+ const logger = createLogger('unchained:postfinance-checkout');
9
+ const newError = ({ code, message }) => {
10
+ const error = new Error(message);
11
+ error.name = `POSTFINANCE_${code}`;
12
+ return error;
13
+ };
14
+ const PostfinanceCheckout = {
15
+ ...PaymentAdapter,
5
16
  key: 'shop.unchained.payment.postfinance-checkout',
6
- label: 'Postfinance Checkout Payment Plugin',
17
+ label: 'Postfinance Checkout',
7
18
  version: '1.0.0',
8
- adapters: [PostfinanceCheckout],
9
- routes: [
10
- {
11
- path: PFCHECKOUT_WEBHOOK_PATH,
12
- method: 'POST',
13
- handler: postfinanceCheckoutWebhookHandler,
14
- },
15
- ],
16
- onRegister: () => {
17
- const { PFCHECKOUT_SPACE_ID, PFCHECKOUT_USER_ID, PFCHECKOUT_SECRET, PFCHECKOUT_SUCCESS_URL, PFCHECKOUT_FAILED_URL, } = process.env;
18
- if (!PFCHECKOUT_SPACE_ID ||
19
- !PFCHECKOUT_USER_ID ||
20
- !PFCHECKOUT_SECRET ||
21
- !PFCHECKOUT_SUCCESS_URL ||
22
- !PFCHECKOUT_FAILED_URL) {
23
- throw new Error('Postfinance Checkout environment variables not fully configured');
24
- }
19
+ typeSupported(type) {
20
+ return type === 'GENERIC';
21
+ },
22
+ actions: (config, context) => {
23
+ const adapter = {
24
+ ...PaymentAdapter.actions(config, context),
25
+ getCompletionMode() {
26
+ return (config.find((item) => item.key === 'completionMode')?.value ||
27
+ CompletionModes.Deferred);
28
+ },
29
+ configurationError() {
30
+ if (!PFCHECKOUT_SPACE_ID ||
31
+ !PFCHECKOUT_USER_ID ||
32
+ !PFCHECKOUT_SECRET ||
33
+ !PFCHECKOUT_SUCCESS_URL ||
34
+ !PFCHECKOUT_FAILED_URL) {
35
+ return PaymentError.INCOMPLETE_CONFIGURATION;
36
+ }
37
+ return null;
38
+ },
39
+ isActive() {
40
+ if (adapter.configurationError() === null)
41
+ return true;
42
+ return false;
43
+ },
44
+ isPayLaterAllowed() {
45
+ return false;
46
+ },
47
+ async validate(credentials) {
48
+ if (!credentials.meta)
49
+ return false;
50
+ const { linkedSpaceId } = credentials.meta;
51
+ const tokenData = await getToken(linkedSpaceId, credentials.token);
52
+ return tokenData.state === CreationEntityState.ACTIVE;
53
+ },
54
+ sign: async (transactionContext = {}) => {
55
+ const { orderPayment, order } = context;
56
+ if (!order)
57
+ throw new Error('No order in context, can only sign with order context');
58
+ if (!orderPayment)
59
+ throw new Error('No order payment in context, can only sign with order payment context');
60
+ const { integrationMode = IntegrationModes.PaymentPage } = transactionContext;
61
+ const completionMode = adapter.getCompletionMode();
62
+ const pricing = OrderPricingSheet({
63
+ calculation: order.calculation,
64
+ currencyCode: order.currencyCode,
65
+ });
66
+ const totalAmount = pricing?.total({ useNetPrice: false }).amount;
67
+ const transaction = {
68
+ currency: order.currencyCode,
69
+ metaData: {
70
+ orderPaymentId: orderPayment._id,
71
+ },
72
+ successUrl: `${transactionContext?.successUrl || PFCHECKOUT_SUCCESS_URL}?order_id=${orderPayment.orderId}`,
73
+ failedUrl: `${transactionContext?.failedUrl || PFCHECKOUT_FAILED_URL}?order_id=${orderPayment.orderId}`,
74
+ customerId: order?.userId || context?.userId,
75
+ tokenizationMode: TokenizationMode.ALLOW_ONE_CLICK_PAYMENT,
76
+ };
77
+ if (completionMode === CompletionModes.Immediate) {
78
+ transaction.completionBehavior = TransactionCompletionBehavior.COMPLETE_IMMEDIATELY;
79
+ }
80
+ else if (completionMode === CompletionModes.Deferred) {
81
+ transaction.completionBehavior = TransactionCompletionBehavior.COMPLETE_DEFERRED;
82
+ }
83
+ if (totalAmount) {
84
+ const lineItemSum = {
85
+ name: `Bestellung ${orderPayment.orderId}`,
86
+ type: LineItemType.FEE,
87
+ quantity: 1,
88
+ uniqueId: orderPayment.orderId,
89
+ amountIncludingTax: totalAmount / 100,
90
+ };
91
+ transaction.lineItems = [lineItemSum];
92
+ }
93
+ const transactionId = await createTransaction(transaction);
94
+ if (!transactionId)
95
+ throw new Error('Could not create transaction');
96
+ let location = null;
97
+ if (integrationMode === IntegrationModes.PaymentPage) {
98
+ location = await getPaymentPageUrl(transactionId);
99
+ }
100
+ else if (integrationMode === IntegrationModes.Lightbox) {
101
+ location = await getLightboxJavascriptUrl(transactionId);
102
+ }
103
+ else if (integrationMode === IntegrationModes.iFrame) {
104
+ location = await getIframeJavascriptUrl(transactionId);
105
+ }
106
+ const res = {
107
+ transactionId,
108
+ location,
109
+ };
110
+ return JSON.stringify(res);
111
+ },
112
+ charge: async ({ transactionId, paymentCredentials, }) => {
113
+ if (paymentCredentials && !transactionId) {
114
+ throw new Error('Not implemented yet');
115
+ }
116
+ if (!transactionId)
117
+ return false;
118
+ const transaction = await getTransaction(transactionId);
119
+ if (!transaction) {
120
+ logger.error(`Transaction #${transactionId}: Transaction not found`);
121
+ throw newError({
122
+ code: `TRANSACTION_NOT_FOUND`,
123
+ message: 'Payment declined',
124
+ });
125
+ }
126
+ const { order, orderPayment } = context;
127
+ if (!orderPayment)
128
+ throw new Error('No order payment in context, cannot charge payment');
129
+ if (!order)
130
+ throw new Error('No order in context, can only sign with order context');
131
+ const isPaid = await orderIsPaid(order, transaction);
132
+ if (!isPaid) {
133
+ logger.error(`Transaction #${transactionId}: Invalid state / Amount incorrect`);
134
+ throw newError({
135
+ code: `STATE_${transaction.state?.toUpperCase()}`,
136
+ message: 'Invalid state / Amount incorrect',
137
+ });
138
+ }
139
+ if (transaction.metaData?.orderPaymentId !== orderPayment._id) {
140
+ logger.error(`Transaction #${transactionId}: Invalid state / Amount incorrect`);
141
+ throw newError({
142
+ code: `TRANSACTION_ALREADY_USED`,
143
+ message: 'Transaction already used in previous checkout',
144
+ });
145
+ }
146
+ const { id, ...tokenMeta } = transaction.token || {};
147
+ return {
148
+ transaction,
149
+ transactionId,
150
+ credentials: id && {
151
+ ...tokenMeta,
152
+ token: id.toString(),
153
+ },
154
+ };
155
+ },
156
+ cancel: async () => {
157
+ const { orderPayment, order } = context;
158
+ if (!order)
159
+ throw new Error('No order in context, can only cancel with order context');
160
+ if (!orderPayment?.transactionId) {
161
+ return false;
162
+ }
163
+ const { transactionId } = orderPayment;
164
+ const transaction = await getTransaction(transactionId);
165
+ const refund = transaction.state === TransactionState.FULFILL;
166
+ const pricing = OrderPricingSheet({
167
+ calculation: order.calculation,
168
+ currencyCode: order.currencyCode,
169
+ });
170
+ const totalAmount = pricing?.total({ useNetPrice: false }).amount;
171
+ return ((refund && refundTransaction(transactionId, order._id, totalAmount / 100)) ||
172
+ voidTransaction(transactionId));
173
+ },
174
+ confirm: async () => {
175
+ const { orderPayment } = context;
176
+ if (!orderPayment?.transactionId) {
177
+ return false;
178
+ }
179
+ const { transactionId } = orderPayment;
180
+ const transaction = await getTransaction(transactionId);
181
+ if (transaction.state === TransactionState.AUTHORIZED) {
182
+ return confirmDeferredTransaction(transactionId);
183
+ }
184
+ return false;
185
+ },
186
+ };
187
+ return adapter;
25
188
  },
26
189
  };
27
- export default PostfinanceCheckoutPlugin;
28
- export { PostfinanceCheckout } from "./adapter.js";
190
+ PaymentDirector.registerAdapter(PostfinanceCheckout);
29
191
  export * from "./types.js";
30
192
  export * from "./api-types.js";
31
- export * from "./utils.js";
@@ -1,7 +1,7 @@
1
1
  import { mongodb } from '@unchainedshop/mongodb';
2
2
  import { SaferpayClient } from "./api/index.js";
3
3
  import { buildSignature } from "./buildSignature.js";
4
- import { OrderPricingSheet, PaymentAdapter, PaymentError, } from '@unchainedshop/core';
4
+ import { OrderPricingSheet, PaymentAdapter, PaymentDirector, PaymentError, } from '@unchainedshop/core';
5
5
  const newSaferpayError = ({ code, message }) => {
6
6
  const error = new Error(message || code);
7
7
  error.name = `SAFERPAY_${code}`;
@@ -187,3 +187,4 @@ export const WordlineSaferpay = {
187
187
  return adapter;
188
188
  },
189
189
  };
190
+ PaymentDirector.registerAdapter(WordlineSaferpay);
@@ -0,0 +1 @@
1
+ export declare const saferpayHandler: (request: any, response: any) => Promise<void>;