@unchainedshop/plugins 2.0.0-beta5 → 2.0.0-beta7

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 (108) 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/index.d.ts +2 -3
  20. package/lib/payment/apple-iap/index.js +2 -3
  21. package/lib/payment/apple-iap/index.js.map +1 -1
  22. package/lib/payment/cryptopay/index.d.ts +2 -3
  23. package/lib/payment/cryptopay/index.js +2 -3
  24. package/lib/payment/cryptopay/index.js.map +1 -1
  25. package/lib/payment/cryptopay/middleware.d.ts +1 -2
  26. package/lib/payment/cryptopay/middleware.js +64 -69
  27. package/lib/payment/cryptopay/middleware.js.map +1 -1
  28. package/lib/payment/datatrans-v2/api/makeFetcher.d.ts +1 -1
  29. package/lib/payment/datatrans-v2/api/makeFetcher.js +1 -1
  30. package/lib/payment/datatrans-v2/api/makeFetcher.js.map +1 -1
  31. package/lib/payment/datatrans-v2/getPaths.d.ts +1 -1
  32. package/lib/payment/datatrans-v2/getPaths.js +7 -7
  33. package/lib/payment/datatrans-v2/getPaths.js.map +1 -1
  34. package/lib/payment/datatrans-v2/index.d.ts +1 -2
  35. package/lib/payment/datatrans-v2/index.js +1 -2
  36. package/lib/payment/datatrans-v2/index.js.map +1 -1
  37. package/lib/payment/datatrans-v2/middleware.d.ts +1 -2
  38. package/lib/payment/datatrans-v2/middleware.js +54 -102
  39. package/lib/payment/datatrans-v2/middleware.js.map +1 -1
  40. package/lib/payment/postfinance-checkout/index.d.ts +1 -2
  41. package/lib/payment/postfinance-checkout/index.js +1 -2
  42. package/lib/payment/postfinance-checkout/index.js.map +1 -1
  43. package/lib/payment/postfinance-checkout/middleware.d.ts +1 -2
  44. package/lib/payment/postfinance-checkout/middleware.js +31 -37
  45. package/lib/payment/postfinance-checkout/middleware.js.map +1 -1
  46. package/lib/payment/stripe.d.ts +1 -2
  47. package/lib/payment/stripe.js +55 -60
  48. package/lib/payment/stripe.js.map +1 -1
  49. package/lib/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.d.ts +1 -0
  50. package/lib/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.js +1 -1
  51. package/lib/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.js.map +1 -1
  52. package/lib/plugins-index.d.ts +61 -0
  53. package/lib/plugins-index.js +100 -0
  54. package/lib/plugins-index.js.map +1 -1
  55. package/lib/pricing/utils/cache.d.ts +1 -2
  56. package/lib/warehousing/eth-minter.js +30 -42
  57. package/lib/warehousing/eth-minter.js.map +1 -1
  58. package/lib/worker/http-request.d.ts +1 -0
  59. package/lib/worker/http-request.js +0 -1
  60. package/lib/worker/http-request.js.map +1 -1
  61. package/lib/worker/update-coinbase-rates.d.ts +1 -0
  62. package/lib/worker/update-coinbase-rates.js +0 -1
  63. package/lib/worker/update-coinbase-rates.js.map +1 -1
  64. package/lib/worker/update-ecb-rates.d.ts +1 -0
  65. package/lib/worker/update-ecb-rates.js +0 -1
  66. package/lib/worker/update-ecb-rates.js.map +1 -1
  67. package/lib/worker/zombie-killer.js +1 -1
  68. package/package.json +21 -23
  69. package/src/delivery/pick-mup.ts +1 -1
  70. package/src/files/gridfs/gridfs-adapter.ts +3 -2
  71. package/src/files/gridfs/gridfs-webhook.ts +40 -46
  72. package/src/files/minio/minio-adapter.ts +13 -8
  73. package/src/files/minio/minio-webhook.ts +35 -0
  74. package/src/payment/apple-iap/adapter.ts +104 -120
  75. package/src/payment/apple-iap/index.ts +2 -4
  76. package/src/payment/cryptopay/index.ts +2 -4
  77. package/src/payment/cryptopay/middleware.ts +65 -74
  78. package/src/payment/datatrans-v2/api/makeFetcher.ts +1 -1
  79. package/src/payment/datatrans-v2/getPaths.ts +12 -11
  80. package/src/payment/datatrans-v2/index.ts +2 -3
  81. package/src/payment/datatrans-v2/middleware.ts +66 -133
  82. package/src/payment/postfinance-checkout/index.ts +2 -3
  83. package/src/payment/postfinance-checkout/middleware.ts +37 -45
  84. package/src/payment/stripe.ts +68 -83
  85. package/src/payment/worldline-saferpay/worldline-saferpay-client/api/SaferpayConnection.ts +1 -2
  86. package/src/plugins-index.ts +147 -0
  87. package/src/warehousing/eth-minter.ts +36 -50
  88. package/src/worker/http-request.ts +1 -1
  89. package/src/worker/update-coinbase-rates.ts +1 -1
  90. package/src/worker/update-ecb-rates.ts +1 -1
  91. package/src/worker/zombie-killer.ts +1 -1
  92. package/lib/payment/bity/adapter.d.ts +0 -2
  93. package/lib/payment/bity/adapter.js +0 -320
  94. package/lib/payment/bity/adapter.js.map +0 -1
  95. package/lib/payment/bity/db/BityCredentialsCollection.d.ts +0 -11
  96. package/lib/payment/bity/db/BityCredentialsCollection.js +0 -5
  97. package/lib/payment/bity/db/BityCredentialsCollection.js.map +0 -1
  98. package/lib/payment/bity/index.d.ts +0 -3
  99. package/lib/payment/bity/index.js +0 -4
  100. package/lib/payment/bity/index.js.map +0 -1
  101. package/lib/payment/bity/module/configureBityModule.d.ts +0 -11
  102. package/lib/payment/bity/module/configureBityModule.js +0 -33
  103. package/lib/payment/bity/module/configureBityModule.js.map +0 -1
  104. package/src/files/minio/minio-webhook.js +0 -54
  105. package/src/payment/bity/adapter.ts +0 -421
  106. package/src/payment/bity/db/BityCredentialsCollection.ts +0 -17
  107. package/src/payment/bity/index.ts +0 -4
  108. package/src/payment/bity/module/configureBityModule.ts +0 -46
@@ -1,4 +1,2 @@
1
- import setupAppleIAP from './adapter';
2
-
3
- export default setupAppleIAP;
4
- export { configureAppleTransactionsModule } from './module/configureAppleTransactionsModule';
1
+ export * from './adapter';
2
+ export * from './module/configureAppleTransactionsModule';
@@ -1,8 +1,6 @@
1
- import setupCryptopayWebhooks from './middleware';
2
1
  import CryptopayPlugin from './plugin';
3
2
 
4
- export { configureCryptopayModule } from './module/configureCryptopayModule';
5
-
6
- export { setupCryptopayWebhooks };
3
+ export * from './middleware';
4
+ export * from './module/configureCryptopayModule';
7
5
 
8
6
  export default CryptopayPlugin;
@@ -1,95 +1,86 @@
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
3
 
6
4
  import { UnchainedCore } from '@unchainedshop/types/core';
7
5
  import { OrderStatus } from '@unchainedshop/core-orders';
8
6
  import { ProductPriceRate } from '@unchainedshop/types/products.pricing';
9
- import { CryptopayModule } from './module/configureCryptopayModule';
7
+ import type { CryptopayModule } from './module/configureCryptopayModule';
10
8
 
11
- const {
12
- CRYPTOPAY_WEBHOOK_PATH = '/payment/cryptopay',
13
- CRYPTOPAY_SECRET,
14
- CRYPTOPAY_MAX_RATE_AGE,
15
- } = process.env;
9
+ const { CRYPTOPAY_SECRET, CRYPTOPAY_MAX_RATE_AGE } = process.env;
16
10
 
17
11
  const logger = createLogger('unchained:core-payment:cryptopay');
18
12
 
19
- export default (app: any) => {
20
- useMiddlewareWithCurrentContext(app, CRYPTOPAY_WEBHOOK_PATH, bodyParser.json());
21
- useMiddlewareWithCurrentContext(app, CRYPTOPAY_WEBHOOK_PATH, async (req, res) => {
22
- const resolvedContext = req.unchainedContext as Context;
23
- const modules = resolvedContext.modules as UnchainedCore['modules'] & { cryptopay: CryptopayModule };
24
- if (req.method === 'POST') {
25
- try {
26
- const { secret, price, wallet, ping } = req.body;
27
- if (secret !== CRYPTOPAY_SECRET) {
28
- logger.warn(`Cryptopay Plugin: Invalid Cryptopay Secret provided`);
29
- throw new Error('Secret invalid');
30
- }
13
+ export const cryptopayHandler = async (req, res) => {
14
+ const resolvedContext = req.unchainedContext as Context;
15
+ const modules = resolvedContext.modules as UnchainedCore['modules'] & { cryptopay: CryptopayModule };
16
+ if (req.method === 'POST') {
17
+ try {
18
+ const { secret, price, wallet, ping } = req.body;
19
+ if (secret !== CRYPTOPAY_SECRET) {
20
+ logger.warn(`Cryptopay Plugin: Invalid Cryptopay Secret provided`);
21
+ throw new Error('Secret invalid');
22
+ }
31
23
 
32
- if (wallet) {
33
- const { address, blockHeight, amount, contract, decimals, currency } = wallet;
34
- const { orderPaymentId } = await modules.cryptopay.updateWalletAddress({
35
- addressId: address,
36
- blockHeight,
37
- amount,
38
- contract,
39
- decimals,
40
- currency,
41
- });
42
- const orderPayment =
43
- orderPaymentId &&
44
- (await modules.orders.payments.findOrderPayment({
45
- orderPaymentId,
46
- }));
24
+ if (wallet) {
25
+ const { address, blockHeight, amount, contract, decimals, currency } = wallet;
26
+ const { orderPaymentId } = await modules.cryptopay.updateWalletAddress({
27
+ addressId: address,
28
+ blockHeight,
29
+ amount,
30
+ contract,
31
+ decimals,
32
+ currency,
33
+ });
34
+ const orderPayment =
35
+ orderPaymentId &&
36
+ (await modules.orders.payments.findOrderPayment({
37
+ orderPaymentId,
38
+ }));
47
39
 
48
- if (orderPayment) {
49
- // Try to process order to next status
50
- const order = await modules.orders.findOrder({ orderId: orderPayment.orderId });
51
- if (order.status === null) {
52
- await modules.orders.checkout(order._id, {}, resolvedContext);
53
- } else if (order.status === OrderStatus.PENDING) {
54
- await modules.orders.processOrder(order, {}, resolvedContext);
55
- } else {
56
- throw new Error('Already processed');
57
- }
40
+ if (orderPayment) {
41
+ // Try to process order to next status
42
+ const order = await modules.orders.findOrder({ orderId: orderPayment.orderId });
43
+ if (order.status === null) {
44
+ await modules.orders.checkout(order._id, {}, resolvedContext);
45
+ } else if (order.status === OrderStatus.PENDING) {
46
+ await modules.orders.processOrder(order, {}, resolvedContext);
47
+ } else {
48
+ throw new Error('Already processed');
58
49
  }
59
50
  }
51
+ }
60
52
 
61
- if (price) {
62
- const { baseCurrency, token, rate, timestamp } = price;
63
-
64
- const timestampDate = new Date(timestamp);
65
- const expiresAt = new Date(new Date().getTime() + parseInt(CRYPTOPAY_MAX_RATE_AGE, 10) * 1000);
53
+ if (price) {
54
+ const { baseCurrency, token, rate, timestamp } = price;
66
55
 
67
- const rateData: ProductPriceRate = {
68
- baseCurrency,
69
- quoteCurrency: token,
70
- rate,
71
- expiresAt,
72
- timestamp: timestampDate,
73
- };
74
- console.log('update rate', price, rateData);
75
- await resolvedContext.modules.products.prices.rates.updateRates([rateData]);
76
- }
56
+ const timestampDate = new Date(timestamp);
57
+ const expiresAt = new Date(new Date().getTime() + parseInt(CRYPTOPAY_MAX_RATE_AGE, 10) * 1000);
77
58
 
78
- if (ping) {
79
- const { blockHeight, currency } = ping;
80
- await modules.cryptopay.updateMostRecentBlock(currency, blockHeight);
81
- }
59
+ const rateData: ProductPriceRate = {
60
+ baseCurrency,
61
+ quoteCurrency: token,
62
+ rate,
63
+ expiresAt,
64
+ timestamp: timestampDate,
65
+ };
66
+ console.log('update rate', price, rateData);
67
+ await resolvedContext.modules.products.prices.rates.updateRates([rateData]);
68
+ }
82
69
 
83
- res.writeHead(200);
84
- res.end(JSON.stringify({ success: true }));
85
- return;
86
- } catch (e) {
87
- res.writeHead(500);
88
- res.end(JSON.stringify({ success: false, error: e.message }));
89
- return;
70
+ if (ping) {
71
+ const { blockHeight, currency } = ping;
72
+ await modules.cryptopay.updateMostRecentBlock(currency, blockHeight);
90
73
  }
74
+
75
+ res.writeHead(200);
76
+ res.end(JSON.stringify({ success: true }));
77
+ return;
78
+ } catch (e) {
79
+ res.writeHead(500);
80
+ res.end(JSON.stringify({ success: false, error: e.message }));
81
+ return;
91
82
  }
92
- res.writeHead(404);
93
- res.end(JSON.stringify({ success: false }));
94
- });
83
+ }
84
+ res.writeHead(404);
85
+ res.end(JSON.stringify({ success: false }));
95
86
  };
@@ -1,8 +1,8 @@
1
+ /// <reference lib="dom" />
1
2
  import fs from 'fs';
2
3
  import util from 'util';
3
4
  import { resolve } from 'path';
4
5
  import { createLogger } from '@unchainedshop/logger';
5
- import fetch, { Response } from 'node-fetch';
6
6
 
7
7
  const readFile = util.promisify(fs.readFile);
8
8
 
@@ -1,10 +1,11 @@
1
1
  const {
2
2
  ROOT_URL,
3
- DATATRANS_WEBHOOK_PATH,
4
- DATATRANS_SUCCESS_PATH,
5
- DATATRANS_ERROR_PATH,
6
- DATATRANS_CANCEL_PATH,
7
- DATATRANS_RETURN_PATH,
3
+ EMAIL_WEBSITE_URL,
4
+ DATATRANS_WEBHOOK_PATH = '/payment/datatrans/webhook',
5
+ DATATRANS_SUCCESS_PATH = '/datatrans/success',
6
+ DATATRANS_ERROR_PATH = '/datatrans/error',
7
+ DATATRANS_CANCEL_PATH = '/datatrans/cancel',
8
+ DATATRANS_RETURN_PATH = '/datatrans/return',
8
9
  } = process.env;
9
10
 
10
11
  type Paths = {
@@ -15,10 +16,10 @@ type Paths = {
15
16
  returnUrl: string;
16
17
  };
17
18
 
18
- export default (relative = false): Paths => ({
19
- postUrl: `${relative ? '' : ROOT_URL}${DATATRANS_WEBHOOK_PATH || '/payment/datatrans/webhook'}`,
20
- successUrl: `${relative ? '' : ROOT_URL}${DATATRANS_SUCCESS_PATH || '/payment/datatrans/success'}`,
21
- cancelUrl: `${relative ? '' : ROOT_URL}${DATATRANS_CANCEL_PATH || '/payment/datatrans/cancel'}`,
22
- errorUrl: `${relative ? '' : ROOT_URL}${DATATRANS_ERROR_PATH || '/payment/datatrans/error'}`,
23
- returnUrl: `${relative ? '' : ROOT_URL}${DATATRANS_RETURN_PATH || '/payment/datatrans/return'}`,
19
+ export default (): Paths => ({
20
+ postUrl: `${ROOT_URL}${DATATRANS_WEBHOOK_PATH}`,
21
+ successUrl: `${EMAIL_WEBSITE_URL}${DATATRANS_SUCCESS_PATH}`,
22
+ cancelUrl: `${EMAIL_WEBSITE_URL}${DATATRANS_CANCEL_PATH}`,
23
+ errorUrl: `${EMAIL_WEBSITE_URL}${DATATRANS_ERROR_PATH}`,
24
+ returnUrl: `${EMAIL_WEBSITE_URL}${DATATRANS_RETURN_PATH}`,
24
25
  });
@@ -10,13 +10,12 @@ import type {
10
10
  StatusResponseSuccess,
11
11
  ValidateResponseSuccess,
12
12
  } from './api/types';
13
- import setupDatatrans from './middleware';
14
13
  import parseRegistrationData from './parseRegistrationData';
15
14
  import roundedAmountFromOrder from './roundedAmountFromOrder';
16
15
 
17
- const logger = createLogger('unchained:core-payment:datatrans');
16
+ export * from './middleware';
18
17
 
19
- export default setupDatatrans;
18
+ const logger = createLogger('unchained:core-payment:datatrans');
20
19
 
21
20
  // v2
22
21
  const { DATATRANS_SECRET, DATATRANS_SIGN_KEY, DATATRANS_API_ENDPOINT, DATATRANS_MERCHANT_ID } =
@@ -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
  };