@unchainedshop/plugins 2.0.0-beta6 → 2.0.0-beta8

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 (116) hide show
  1. package/lib/delivery/pick-mup.d.ts +1 -0
  2. package/lib/delivery/pick-mup.js +1 -1
  3. package/lib/delivery/pick-mup.js.map +1 -1
  4. package/lib/files/gridfs/gridfs-adapter.d.ts +1 -0
  5. package/lib/files/gridfs/gridfs-adapter.js +0 -1
  6. package/lib/files/gridfs/gridfs-adapter.js.map +1 -1
  7. package/lib/files/gridfs/gridfs-webhook.d.ts +1 -2
  8. package/lib/files/gridfs/gridfs-webhook.js +2 -6
  9. package/lib/files/gridfs/gridfs-webhook.js.map +1 -1
  10. package/lib/files/minio/minio-adapter.d.ts +2 -1
  11. package/lib/files/minio/minio-adapter.js +13 -7
  12. package/lib/files/minio/minio-adapter.js.map +1 -1
  13. package/lib/files/minio/minio-webhook.d.ts +1 -2
  14. package/lib/files/minio/minio-webhook.js +24 -37
  15. package/lib/files/minio/minio-webhook.js.map +1 -1
  16. package/lib/payment/apple-iap/adapter.d.ts +2 -2
  17. package/lib/payment/apple-iap/adapter.js +89 -97
  18. package/lib/payment/apple-iap/adapter.js.map +1 -1
  19. package/lib/payment/apple-iap/db/AppleTransactionsCollection.d.ts +1 -1
  20. package/lib/payment/apple-iap/index.d.ts +2 -3
  21. package/lib/payment/apple-iap/index.js +2 -3
  22. package/lib/payment/apple-iap/index.js.map +1 -1
  23. package/lib/payment/braintree.js +14 -12
  24. package/lib/payment/braintree.js.map +1 -1
  25. package/lib/payment/cryptopay/db/CryptopayTransactions.d.ts +1 -1
  26. package/lib/payment/cryptopay/index.d.ts +2 -3
  27. package/lib/payment/cryptopay/index.js +2 -3
  28. package/lib/payment/cryptopay/index.js.map +1 -1
  29. package/lib/payment/cryptopay/middleware.d.ts +1 -2
  30. package/lib/payment/cryptopay/middleware.js +64 -69
  31. package/lib/payment/cryptopay/middleware.js.map +1 -1
  32. package/lib/payment/datatrans-v2/api/makeFetcher.d.ts +1 -1
  33. package/lib/payment/datatrans-v2/api/makeFetcher.js +1 -1
  34. package/lib/payment/datatrans-v2/api/makeFetcher.js.map +1 -1
  35. package/lib/payment/datatrans-v2/getPaths.d.ts +2 -2
  36. package/lib/payment/datatrans-v2/getPaths.js +7 -7
  37. package/lib/payment/datatrans-v2/getPaths.js.map +1 -1
  38. package/lib/payment/datatrans-v2/index.d.ts +1 -2
  39. package/lib/payment/datatrans-v2/index.js +1 -2
  40. package/lib/payment/datatrans-v2/index.js.map +1 -1
  41. package/lib/payment/datatrans-v2/middleware.d.ts +1 -2
  42. package/lib/payment/datatrans-v2/middleware.js +54 -102
  43. package/lib/payment/datatrans-v2/middleware.js.map +1 -1
  44. package/lib/payment/postfinance-checkout/index.d.ts +1 -2
  45. package/lib/payment/postfinance-checkout/index.js +1 -2
  46. package/lib/payment/postfinance-checkout/index.js.map +1 -1
  47. package/lib/payment/postfinance-checkout/middleware.d.ts +1 -2
  48. package/lib/payment/postfinance-checkout/middleware.js +31 -37
  49. package/lib/payment/postfinance-checkout/middleware.js.map +1 -1
  50. package/lib/payment/postfinance-checkout/types.d.ts +3 -3
  51. package/lib/payment/stripe.d.ts +1 -2
  52. package/lib/payment/stripe.js +55 -60
  53. package/lib/payment/stripe.js.map +1 -1
  54. package/lib/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.d.ts +1 -0
  55. package/lib/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.js +4 -3
  56. package/lib/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.js.map +1 -1
  57. package/lib/payment/worldline-saferpay/worldline-saferpay-client/models/PaymentMethods.d.ts +1 -1
  58. package/lib/payment/worldline-saferpay/worldline-saferpay-client/models/Transaction.d.ts +2 -2
  59. package/lib/plugins-index.d.ts +64 -0
  60. package/lib/plugins-index.js +100 -0
  61. package/lib/plugins-index.js.map +1 -1
  62. package/lib/warehousing/eth-minter.js +27 -40
  63. package/lib/warehousing/eth-minter.js.map +1 -1
  64. package/lib/worker/http-request.d.ts +1 -0
  65. package/lib/worker/http-request.js +0 -1
  66. package/lib/worker/http-request.js.map +1 -1
  67. package/lib/worker/update-coinbase-rates.d.ts +1 -0
  68. package/lib/worker/update-coinbase-rates.js +0 -1
  69. package/lib/worker/update-coinbase-rates.js.map +1 -1
  70. package/lib/worker/update-ecb-rates.d.ts +1 -0
  71. package/lib/worker/update-ecb-rates.js +0 -1
  72. package/lib/worker/update-ecb-rates.js.map +1 -1
  73. package/lib/worker/zombie-killer.js +13 -28
  74. package/lib/worker/zombie-killer.js.map +1 -1
  75. package/package.json +27 -26
  76. package/src/delivery/pick-mup.ts +1 -1
  77. package/src/files/gridfs/gridfs-adapter.ts +3 -2
  78. package/src/files/gridfs/gridfs-webhook.ts +40 -46
  79. package/src/files/minio/minio-adapter.ts +13 -8
  80. package/src/files/minio/minio-webhook.ts +35 -0
  81. package/src/payment/apple-iap/adapter.ts +104 -120
  82. package/src/payment/apple-iap/index.ts +2 -4
  83. package/src/payment/braintree.ts +14 -12
  84. package/src/payment/cryptopay/index.ts +2 -4
  85. package/src/payment/cryptopay/middleware.ts +65 -74
  86. package/src/payment/datatrans-v2/api/makeFetcher.ts +1 -1
  87. package/src/payment/datatrans-v2/getPaths.ts +12 -11
  88. package/src/payment/datatrans-v2/index.ts +2 -3
  89. package/src/payment/datatrans-v2/middleware.ts +66 -133
  90. package/src/payment/postfinance-checkout/index.ts +2 -3
  91. package/src/payment/postfinance-checkout/middleware.ts +37 -45
  92. package/src/payment/stripe.ts +68 -83
  93. package/src/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.ts +4 -4
  94. package/src/plugins-index.ts +151 -0
  95. package/src/warehousing/eth-minter.ts +32 -48
  96. package/src/worker/http-request.ts +1 -1
  97. package/src/worker/update-coinbase-rates.ts +1 -1
  98. package/src/worker/update-ecb-rates.ts +1 -1
  99. package/src/worker/zombie-killer.ts +33 -30
  100. package/lib/payment/bity/adapter.d.ts +0 -2
  101. package/lib/payment/bity/adapter.js +0 -320
  102. package/lib/payment/bity/adapter.js.map +0 -1
  103. package/lib/payment/bity/db/BityCredentialsCollection.d.ts +0 -11
  104. package/lib/payment/bity/db/BityCredentialsCollection.js +0 -5
  105. package/lib/payment/bity/db/BityCredentialsCollection.js.map +0 -1
  106. package/lib/payment/bity/index.d.ts +0 -3
  107. package/lib/payment/bity/index.js +0 -4
  108. package/lib/payment/bity/index.js.map +0 -1
  109. package/lib/payment/bity/module/configureBityModule.d.ts +0 -11
  110. package/lib/payment/bity/module/configureBityModule.js +0 -33
  111. package/lib/payment/bity/module/configureBityModule.js.map +0 -1
  112. package/src/files/minio/minio-webhook.js +0 -54
  113. package/src/payment/bity/adapter.ts +0 -421
  114. package/src/payment/bity/db/BityCredentialsCollection.ts +0 -17
  115. package/src/payment/bity/index.ts +0 -4
  116. package/src/payment/bity/module/configureBityModule.ts +0 -46
@@ -1,8 +1,5 @@
1
- import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
2
- import bodyParser from 'body-parser';
3
1
  import { createLogger } from '@unchainedshop/logger';
4
2
  import { Context } from '@unchainedshop/types/api';
5
- import getPaths from './getPaths';
6
3
  import generateSignature, { Security } from './generateSignature';
7
4
 
8
5
  import type { StatusResponseSuccess } from './api/types';
@@ -15,139 +12,75 @@ const {
15
12
 
16
13
  const logger = createLogger('unchained:core-payment:datatrans');
17
14
 
18
- const { postUrl, cancelUrl, errorUrl, successUrl, returnUrl } = getPaths(true);
19
-
20
- export default (app: any) => {
21
- useMiddlewareWithCurrentContext(
22
- app,
23
- postUrl,
24
- bodyParser.text({
25
- type: 'application/json',
26
- }),
27
- );
28
-
29
- useMiddlewareWithCurrentContext(app, cancelUrl, bodyParser.urlencoded({ extended: false }));
30
-
31
- useMiddlewareWithCurrentContext(app, errorUrl, bodyParser.urlencoded({ extended: false }));
32
-
33
- useMiddlewareWithCurrentContext(app, successUrl, bodyParser.urlencoded({ extended: false }));
34
-
35
- useMiddlewareWithCurrentContext(app, returnUrl, bodyParser.urlencoded({ extended: false }));
36
-
37
- useMiddlewareWithCurrentContext(app, postUrl, async (req, res) => {
38
- const resolvedContext = req.unchainedContext as Context;
39
- const { services, modules } = resolvedContext;
40
- const signature = req.headers['datatrans-signature'];
41
- if (req.method === 'POST' && signature) {
42
- const [rawTimestamp, rawHash] = signature.split(',');
43
- const [, hash] = rawHash.split('=');
44
- const [, timestamp] = rawTimestamp.split('=');
45
-
46
- const comparableSignature = generateSignature({
47
- security: DATATRANS_SECURITY as any,
48
- signKey: DATATRANS_SIGN2_KEY || DATATRANS_SIGN_KEY,
49
- })(timestamp, req.body);
50
-
51
- if (hash !== comparableSignature) {
52
- logger.error(`Datatrans Plugin: Hash mismatch: ${signature} / ${comparableSignature}`, req.body);
53
- res.writeHead(403);
54
- res.end('Hash mismatch');
55
- return;
56
- }
57
-
58
- const transaction: StatusResponseSuccess = JSON.parse(req.body) as StatusResponseSuccess;
59
-
60
- if (transaction.status === 'authorized') {
61
- const userId = transaction.refno2;
62
- const referenceId = Buffer.from(transaction.refno, 'base64').toString('hex');
63
-
64
- try {
65
- if (transaction.type === 'card_check') {
66
- const paymentProviderId = referenceId;
67
- const paymentCredentials = await services.payment.registerPaymentCredentials(
68
- paymentProviderId,
69
- { transactionContext: { transactionId: transaction.transactionId } },
70
- { ...resolvedContext, userId },
71
- );
72
- logger.info(`Datatrans Webhook: Unchained registered payment credentials for ${userId}`, {
73
- userId,
74
- });
75
- res.writeHead(200);
76
- res.end(JSON.stringify(paymentCredentials));
77
- return;
78
- }
79
- if (transaction.type === 'payment') {
80
- const orderPaymentId = referenceId;
81
- const orderPayment = await modules.orders.payments.findOrderPayment({
82
- orderPaymentId,
83
- });
84
- if (!orderPayment) throw new Error(`Order Payment with id ${orderPaymentId} not found`);
15
+ export const datatransHandler = async (req, res) => {
16
+ const resolvedContext = req.unchainedContext as Context;
17
+ const { services, modules } = resolvedContext;
18
+ const signature = req.headers['datatrans-signature'];
19
+ if (req.method === 'POST' && signature) {
20
+ const [rawTimestamp, rawHash] = signature.split(',');
21
+ const [, hash] = rawHash.split('=');
22
+ const [, timestamp] = rawTimestamp.split('=');
23
+
24
+ const comparableSignature = generateSignature({
25
+ security: DATATRANS_SECURITY as any,
26
+ signKey: DATATRANS_SIGN2_KEY || DATATRANS_SIGN_KEY,
27
+ })(timestamp, req.body);
28
+
29
+ if (hash !== comparableSignature) {
30
+ logger.error(`Datatrans Plugin: Hash mismatch: ${signature} / ${comparableSignature}`, req.body);
31
+ res.writeHead(403);
32
+ res.end('Hash mismatch');
33
+ return;
34
+ }
85
35
 
86
- const order = await modules.orders.checkout(
87
- orderPayment.orderId,
88
- { paymentContext: { transactionId: transaction.transactionId } },
89
- { ...resolvedContext, userId },
90
- );
91
- res.writeHead(200);
92
- logger.info(
93
- `Datatrans Webhook: Unchained confirmed checkout for order ${order.orderNumber}`,
94
- {
95
- orderId: order._id,
96
- },
97
- );
98
- res.end(JSON.stringify(order));
99
- return;
100
- }
101
- } catch (e) {
102
- logger.error(`Datatrans Webhook: Unchained rejected to checkout with message`, e);
103
- res.writeHead(500);
104
- res.end(JSON.stringify({ name: e.name, code: e.code, message: e.message }));
36
+ const transaction: StatusResponseSuccess = JSON.parse(req.body) as StatusResponseSuccess;
37
+
38
+ if (transaction.status === 'authorized') {
39
+ const userId = transaction.refno2;
40
+ const referenceId = Buffer.from(transaction.refno, 'base64').toString('hex');
41
+
42
+ try {
43
+ if (transaction.type === 'card_check') {
44
+ const paymentProviderId = referenceId;
45
+ const paymentCredentials = await services.payment.registerPaymentCredentials(
46
+ paymentProviderId,
47
+ { transactionContext: { transactionId: transaction.transactionId } },
48
+ { ...resolvedContext, userId },
49
+ );
50
+ logger.info(`Datatrans Webhook: Unchained registered payment credentials for ${userId}`, {
51
+ userId,
52
+ });
53
+ res.writeHead(200);
54
+ res.end(JSON.stringify(paymentCredentials));
105
55
  return;
106
56
  }
57
+ if (transaction.type === 'payment') {
58
+ const orderPaymentId = referenceId;
59
+ const orderPayment = await modules.orders.payments.findOrderPayment({
60
+ orderPaymentId,
61
+ });
62
+ if (!orderPayment) throw new Error(`Order Payment with id ${orderPaymentId} not found`);
63
+
64
+ const order = await modules.orders.checkout(
65
+ orderPayment.orderId,
66
+ { paymentContext: { transactionId: transaction.transactionId } },
67
+ { ...resolvedContext, userId },
68
+ );
69
+ res.writeHead(200);
70
+ logger.info(`Datatrans Webhook: Unchained confirmed checkout for order ${order.orderNumber}`, {
71
+ orderId: order._id,
72
+ });
73
+ res.end(JSON.stringify(order));
74
+ return;
75
+ }
76
+ } catch (e) {
77
+ logger.error(`Datatrans Webhook: Unchained rejected to checkout with message`, e);
78
+ res.writeHead(500);
79
+ res.end(JSON.stringify({ name: e.name, code: e.code, message: e.message }));
80
+ return;
107
81
  }
108
82
  }
109
- res.writeHead(404);
110
- res.end();
111
- });
112
-
113
- useMiddlewareWithCurrentContext(app, successUrl, async (req, res) => {
114
- if (req.method === 'GET') {
115
- const { datatransTrxId } = req.query;
116
- res.end(`Payment successful\nTransaction ID: ${datatransTrxId}`);
117
- return;
118
- }
119
- res.writeHead(404);
120
- res.end();
121
- });
122
-
123
- useMiddlewareWithCurrentContext(app, errorUrl, async (req, res) => {
124
- if (req.method === 'GET') {
125
- const { datatransTrxId } = req.query;
126
- res.end(`Payment error\nTransaction ID: ${datatransTrxId}`);
127
- return;
128
- }
129
- res.writeHead(404);
130
- res.end();
131
- });
132
-
133
- useMiddlewareWithCurrentContext(app, cancelUrl, async (req, res) => {
134
- if (req.method === 'GET') {
135
- const { datatransTrxId } = req.query;
136
- res.end(`Payment cancelled\nTransaction ID: ${datatransTrxId}`);
137
- return;
138
- }
139
- res.writeHead(404);
140
- res.end();
141
- });
142
-
143
- useMiddlewareWithCurrentContext(app, returnUrl, async (req, res) => {
144
- if (req.method === 'GET') {
145
- const { datatransTrxId } = req.query;
146
- res.end(
147
- `Secure Fields Payment authenticated\nTransaction ID: ${datatransTrxId}\nNeeds authorization`,
148
- );
149
- }
150
- res.writeHead(404);
151
- res.end();
152
- });
83
+ }
84
+ res.writeHead(404);
85
+ res.end();
153
86
  };
@@ -19,12 +19,11 @@ import {
19
19
  voidTransaction,
20
20
  } from './api';
21
21
  import { orderIsPaid } from './utils';
22
- import setupPostfinance from './middleware';
23
22
  import { CompletionModes, IntegrationModes, SignResponse } from './types';
24
23
 
25
- const { PostFinanceCheckout } = pf;
24
+ export * from './middleware';
26
25
 
27
- export default setupPostfinance;
26
+ const { PostFinanceCheckout } = pf;
28
27
 
29
28
  const {
30
29
  PFCHECKOUT_SPACE_ID,
@@ -1,56 +1,48 @@
1
- import bodyParser from 'body-parser';
2
- import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
3
1
  import { Context } from '@unchainedshop/types/api';
4
2
  import { createLogger } from '@unchainedshop/logger';
5
3
  import { WebhookData } from './types';
6
4
  import { getTransaction, getTransactionCompletion } from './api';
7
5
 
8
- const { PFCHECKOUT_WEBHOOK_PATH = '/payment/postfinance-checkout' } = process.env;
9
-
10
6
  const logger = createLogger('unchained:core-payment:postfinance-checkout');
11
7
 
12
- export default (app) => {
13
- useMiddlewareWithCurrentContext(app, PFCHECKOUT_WEBHOOK_PATH, bodyParser.json());
14
-
15
- useMiddlewareWithCurrentContext(app, PFCHECKOUT_WEBHOOK_PATH, async (req, res) => {
16
- const context = req.unchainedContext as Context;
17
- const data = req.body as WebhookData;
18
- if (data.listenerEntityTechnicalName === 'TransactionCompletion') {
19
- try {
20
- const transactionCompletion = await getTransactionCompletion(data.entityId as unknown as string);
21
- const transaction = await getTransaction(
22
- transactionCompletion.linkedTransaction as unknown as string,
23
- );
24
- const { orderPaymentId } = transaction.metaData as { orderPaymentId: string };
25
- const orderPayment = await context.modules.orders.payments.findOrderPayment({
26
- orderPaymentId,
27
- });
28
- if (!orderPayment) throw new Error('Order Payment not found');
29
- const order = await context.modules.orders.checkout(
30
- orderPayment.orderId,
31
- {
32
- paymentContext: {
33
- transactionId: transactionCompletion.linkedTransaction,
34
- },
8
+ export const postfinanceCheckoutHandler = async (req, res) => {
9
+ const context = req.unchainedContext as Context;
10
+ const data = req.body as WebhookData;
11
+ if (data.listenerEntityTechnicalName === 'TransactionCompletion') {
12
+ try {
13
+ const transactionCompletion = await getTransactionCompletion(data.entityId as unknown as string);
14
+ const transaction = await getTransaction(
15
+ transactionCompletion.linkedTransaction as unknown as string,
16
+ );
17
+ const { orderPaymentId } = transaction.metaData as { orderPaymentId: string };
18
+ const orderPayment = await context.modules.orders.payments.findOrderPayment({
19
+ orderPaymentId,
20
+ });
21
+ if (!orderPayment) throw new Error('Order Payment not found');
22
+ const order = await context.modules.orders.checkout(
23
+ orderPayment.orderId,
24
+ {
25
+ paymentContext: {
26
+ transactionId: transactionCompletion.linkedTransaction,
35
27
  },
36
- context,
37
- );
38
- logger.info(
39
- `PostFinance Checkout Webhook: Transaction ${transactionCompletion.linkedTransaction} marked order payment ID ${transaction.metaData.orderPaymentId} as paid`,
40
- );
41
- res.writeHead(200);
42
- res.end(`Order marked as paid: ${order.orderNumber}`);
43
- } catch (e) {
44
- logger.error(`PostFinance Checkout Webhook: Unchained rejected to checkout with message`, e);
45
- res.writeHead(500);
46
- res.end(JSON.stringify({ name: e.name, code: e.code, message: e.message }));
47
- }
48
- } else {
49
- logger.error(
50
- `PostFinance Checkout Webhook: Received unknown listenerEntityTechnicalName ${data.listenerEntityTechnicalName}`,
28
+ },
29
+ context,
30
+ );
31
+ logger.info(
32
+ `PostFinance Checkout Webhook: Transaction ${transactionCompletion.linkedTransaction} marked order payment ID ${transaction.metaData.orderPaymentId} as paid`,
51
33
  );
52
- res.writeHead(404);
53
- res.end();
34
+ res.writeHead(200);
35
+ res.end(`Order marked as paid: ${order.orderNumber}`);
36
+ } catch (e) {
37
+ logger.error(`PostFinance Checkout Webhook: Unchained rejected to checkout with message`, e);
38
+ res.writeHead(500);
39
+ res.end(JSON.stringify({ name: e.name, code: e.code, message: e.message }));
54
40
  }
55
- });
41
+ } else {
42
+ logger.error(
43
+ `PostFinance Checkout Webhook: Received unknown listenerEntityTechnicalName ${data.listenerEntityTechnicalName}`,
44
+ );
45
+ res.writeHead(404);
46
+ res.end();
47
+ }
56
48
  };
@@ -1,7 +1,5 @@
1
1
  import { Context } from '@unchainedshop/types/api';
2
2
  import { IPaymentAdapter } from '@unchainedshop/types/payments';
3
- import bodyParser from 'body-parser';
4
- import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
5
3
  import { PaymentAdapter, PaymentDirector, PaymentError } from '@unchainedshop/core-payment';
6
4
  import { createLogger } from '@unchainedshop/logger';
7
5
 
@@ -18,96 +16,83 @@ import createStripeClient from 'stripe';
18
16
 
19
17
  const logger = createLogger('unchained:core-payment:stripe');
20
18
 
21
- const {
22
- STRIPE_SECRET,
23
- STRIPE_ENDPOINT_SECRET,
24
- EMAIL_WEBSITE_NAME,
25
- STRIPE_WEBHOOK_PATH = '/payment/stripe',
26
- } = process.env;
19
+ const { STRIPE_SECRET, STRIPE_ENDPOINT_SECRET, EMAIL_WEBSITE_NAME } = process.env;
27
20
 
28
21
  // eslint-disable-next-line
29
22
  // @ts-ignore
30
23
  const stripe = createStripeClient(STRIPE_SECRET);
31
24
 
32
- export default (app) => {
33
- useMiddlewareWithCurrentContext(
34
- app,
35
- STRIPE_WEBHOOK_PATH,
36
- bodyParser.raw({ type: 'application/json' }),
37
- );
38
-
39
- useMiddlewareWithCurrentContext(app, STRIPE_WEBHOOK_PATH, async (request, response) => {
40
- const sig = request.headers['stripe-signature'];
41
- const resolvedContext = request.unchainedContext as Context;
42
- const { modules, services } = resolvedContext;
43
-
44
- let event;
45
-
46
- try {
47
- event = stripe.webhooks.constructEvent(request.body, sig, STRIPE_ENDPOINT_SECRET);
48
- } catch (err) {
49
- response.writeHead(400);
50
- response.end(`Webhook Error: ${err.message}`);
51
- return;
52
- }
53
-
54
- try {
55
- if (event.type === 'payment_intent.succeeded') {
56
- const paymentIntent = event.data.object;
57
- const orderPaymentId = paymentIntent.metadata?.orderPaymentId;
58
-
59
- await modules.orders.payments.logEvent(orderPaymentId, event, resolvedContext.userId);
60
-
61
- const orderPayment = await modules.orders.payments.findOrderPayment({
62
- orderPaymentId,
63
- });
64
-
65
- const order = await modules.orders.checkout(
66
- orderPayment.orderId,
67
- {
68
- transactionContext: {
69
- paymentIntentId: paymentIntent.id,
70
- },
71
- paymentContext: {
72
- paymentIntentId: paymentIntent.id,
73
- },
25
+ export const stripeHandler = async (request, response) => {
26
+ const sig = request.headers['stripe-signature'];
27
+ const resolvedContext = request.unchainedContext as Context;
28
+ const { modules, services } = resolvedContext;
29
+
30
+ let event;
31
+
32
+ try {
33
+ event = stripe.webhooks.constructEvent(request.body, sig, STRIPE_ENDPOINT_SECRET);
34
+ } catch (err) {
35
+ response.writeHead(400);
36
+ response.end(`Webhook Error: ${err.message}`);
37
+ return;
38
+ }
39
+
40
+ try {
41
+ if (event.type === 'payment_intent.succeeded') {
42
+ const paymentIntent = event.data.object;
43
+ const orderPaymentId = paymentIntent.metadata?.orderPaymentId;
44
+
45
+ await modules.orders.payments.logEvent(orderPaymentId, event, resolvedContext.userId);
46
+
47
+ const orderPayment = await modules.orders.payments.findOrderPayment({
48
+ orderPaymentId,
49
+ });
50
+
51
+ const order = await modules.orders.checkout(
52
+ orderPayment.orderId,
53
+ {
54
+ transactionContext: {
55
+ paymentIntentId: paymentIntent.id,
74
56
  },
75
- resolvedContext,
76
- );
77
-
78
- logger.info(`Stripe Webhook: Unchained confirmed checkout for order ${order.orderNumber}`, {
79
- orderId: order._id,
80
- });
81
- } else if (event.type === 'setup_intent.succeeded') {
82
- const setupIntent = event.data.object;
83
- const { paymentProviderId, userId } = setupIntent.metadata;
84
-
85
- await services.payment.registerPaymentCredentials(
86
- paymentProviderId,
87
- {
88
- transactionContext: {
89
- setupIntentId: setupIntent.id,
90
- },
57
+ paymentContext: {
58
+ paymentIntentId: paymentIntent.id,
91
59
  },
92
- resolvedContext,
93
- );
94
-
95
- logger.info(`Stripe Webhook: Unchained registered payment credentials for ${userId}`, {
96
- userId,
97
- });
98
- } else {
99
- response.writeHead(404);
100
- response.end();
101
- return;
102
- }
103
- } catch (err) {
104
- response.writeHead(400);
105
- response.end(`Webhook Error: ${err.message}`);
60
+ },
61
+ resolvedContext,
62
+ );
63
+
64
+ logger.info(`Stripe Webhook: Unchained confirmed checkout for order ${order.orderNumber}`, {
65
+ orderId: order._id,
66
+ });
67
+ } else if (event.type === 'setup_intent.succeeded') {
68
+ const setupIntent = event.data.object;
69
+ const { paymentProviderId, userId } = setupIntent.metadata;
70
+
71
+ await services.payment.registerPaymentCredentials(
72
+ paymentProviderId,
73
+ {
74
+ transactionContext: {
75
+ setupIntentId: setupIntent.id,
76
+ },
77
+ },
78
+ resolvedContext,
79
+ );
80
+
81
+ logger.info(`Stripe Webhook: Unchained registered payment credentials for ${userId}`, {
82
+ userId,
83
+ });
84
+ } else {
85
+ response.writeHead(404);
86
+ response.end();
106
87
  return;
107
88
  }
108
- // Return a 200 response to acknowledge receipt of the event
109
- response.end(JSON.stringify({ received: true }));
110
- });
89
+ } catch (err) {
90
+ response.writeHead(400);
91
+ response.end(`Webhook Error: ${err.message}`);
92
+ return;
93
+ }
94
+ // Return a 200 response to acknowledge receipt of the event
95
+ response.end(JSON.stringify({ received: true }));
111
96
  };
112
97
 
113
98
  const createRegistrationIntent = async ({ userId, name, email, paymentProviderId }, options = {}) => {
@@ -1,5 +1,4 @@
1
- import fetch from 'node-fetch';
2
-
1
+ /// <reference lib="dom" />
3
2
  export class SaferpayConnection {
4
3
  private baseUrl: string;
5
4
 
@@ -27,10 +26,11 @@ export class SaferpayConnection {
27
26
  }
28
27
 
29
28
  public async post(uri: string, data: object): Promise<any> {
30
- return fetch(this.buildUrl(uri), {
29
+ const res = await fetch(this.buildUrl(uri), {
31
30
  method: 'POST',
32
31
  body: JSON.stringify(data),
33
32
  headers: this.getHeaders(),
34
- }).then((res: any) => res.json());
33
+ });
34
+ return res.json();
35
35
  }
36
36
  }
@@ -0,0 +1,151 @@
1
+ import { useMiddlewareWithCurrentContext } from '@unchainedshop/api/express';
2
+ import { UnchainedCore } from '@unchainedshop/types/core';
3
+ import express from 'express';
4
+
5
+ // Delivery
6
+ import './delivery/post';
7
+ import './delivery/pick-mup';
8
+ import './delivery/send-message';
9
+ import './delivery/stores';
10
+
11
+ // Payment
12
+ import './payment/invoice';
13
+ import './payment/invoice-prepaid';
14
+ import './payment/paypal-checkout';
15
+ import './payment/worldline-saferpay';
16
+ import { datatransHandler } from './payment/datatrans-v2';
17
+ import { configureCryptopayModule, cryptopayHandler } from './payment/cryptopay';
18
+ import { appleIAPHandler, configureAppleTransactionsModule } from './payment/apple-iap';
19
+ import { stripeHandler } from './payment/stripe';
20
+ import { postfinanceCheckoutHandler } from './payment/postfinance-checkout';
21
+
22
+ // Warehousing
23
+ import './warehousing/store';
24
+ import './warehousing/eth-minter';
25
+
26
+ // Pricing
27
+ import './pricing/discount-half-price-manual';
28
+ import './pricing/discount-100-off';
29
+ import './pricing/free-payment';
30
+ import './pricing/free-delivery';
31
+ import './pricing/order-items';
32
+ import './pricing/order-discount';
33
+ import './pricing/order-delivery';
34
+ import './pricing/order-payment';
35
+ import './pricing/product-catalog-price';
36
+ import './pricing/product-price-rateconversion';
37
+ import './pricing/product-discount';
38
+ import './pricing/product-swiss-tax';
39
+ import './pricing/delivery-swiss-tax';
40
+
41
+ // Filter & Search
42
+ import './filters/strict-equal';
43
+ import './filters/local-search';
44
+
45
+ // Quotations
46
+ import './quotations/manual';
47
+
48
+ // Enrollments
49
+ import './enrollments/licensed';
50
+
51
+ // Event Queue
52
+ import './events/node-event-emitter';
53
+
54
+ // Workers
55
+ import './worker/bulk-import';
56
+ import './worker/zombie-killer';
57
+ import './worker/message';
58
+ import './worker/external';
59
+ import './worker/http-request';
60
+ import './worker/heartbeat';
61
+ import './worker/email';
62
+ import './worker/sms';
63
+ import './worker/update-ecb-rates';
64
+ import './worker/update-coinbase-rates';
65
+ import { configureExportToken } from './worker/export-token';
66
+ import { configureGenerateOrderAutoscheduling } from './worker/enrollment-order-generator';
67
+ import { configureUpdateTokenOwnership } from './worker/update-token-ownership';
68
+
69
+ // Asset Management
70
+ import './files/gridfs/gridfs-adapter';
71
+ import { gridfsHandler } from './files/gridfs/gridfs-webhook';
72
+ import { configureGridFSFileUploadModule } from './files/gridfs';
73
+
74
+ const {
75
+ CRYPTOPAY_WEBHOOK_PATH = '/payment/cryptopay',
76
+ STRIPE_WEBHOOK_PATH = '/payment/stripe',
77
+ PFCHECKOUT_WEBHOOK_PATH = '/payment/postfinance-checkout',
78
+ DATATRANS_WEBHOOK_PATH = '/payment/datatrans/webhook',
79
+ APPLE_IAP_WEBHOOK_PATH = '/payment/apple-iap',
80
+ // MINIO_PUT_SERVER_PATH = '/minio',
81
+ GRIDFS_PUT_SERVER_PATH = '/gridfs',
82
+ } = process.env;
83
+
84
+ // import './files/minio/minio-adapter';
85
+ // import { minioHandler } from './files/minio/minio-webhook';
86
+
87
+ export const defaultModules = {
88
+ appleTransactions: {
89
+ configure: configureAppleTransactionsModule,
90
+ },
91
+ gridfsFileUploads: {
92
+ configure: configureGridFSFileUploadModule,
93
+ },
94
+ cryptopay: {
95
+ configure: configureCryptopayModule,
96
+ },
97
+ };
98
+
99
+ export const connectDefaultPluginsToExpress4 = (
100
+ app,
101
+ { unchainedAPI }: { unchainedAPI: UnchainedCore },
102
+ ) => {
103
+ useMiddlewareWithCurrentContext(app, GRIDFS_PUT_SERVER_PATH, gridfsHandler);
104
+
105
+ useMiddlewareWithCurrentContext(app, CRYPTOPAY_WEBHOOK_PATH, express.json(), cryptopayHandler);
106
+
107
+ useMiddlewareWithCurrentContext(
108
+ app,
109
+ STRIPE_WEBHOOK_PATH,
110
+ express.raw({ type: 'application/json' }),
111
+ stripeHandler,
112
+ );
113
+
114
+ useMiddlewareWithCurrentContext(
115
+ app,
116
+ PFCHECKOUT_WEBHOOK_PATH,
117
+ express.json(),
118
+ postfinanceCheckoutHandler,
119
+ );
120
+
121
+ useMiddlewareWithCurrentContext(
122
+ app,
123
+ DATATRANS_WEBHOOK_PATH,
124
+ express.text({
125
+ type: 'application/json',
126
+ }),
127
+ datatransHandler,
128
+ );
129
+
130
+ useMiddlewareWithCurrentContext(
131
+ app,
132
+ APPLE_IAP_WEBHOOK_PATH,
133
+ express.json({
134
+ strict: false,
135
+ }),
136
+ appleIAPHandler,
137
+ );
138
+
139
+ // useMiddlewareWithCurrentContext(
140
+ // app,
141
+ // MINIO_PUT_SERVER_PATH,
142
+ // express.json({
143
+ // strict: false,
144
+ // }),
145
+ // minioHandler
146
+ // );
147
+
148
+ configureExportToken(unchainedAPI);
149
+ configureUpdateTokenOwnership(unchainedAPI);
150
+ configureGenerateOrderAutoscheduling();
151
+ };