@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,6 @@
1
+ /// <reference lib="dom" />
1
2
  import { Context } from '@unchainedshop/types/api';
2
3
  import { IPaymentAdapter } from '@unchainedshop/types/payments';
3
- import bodyParser from 'body-parser';
4
- import fetch from 'node-fetch';
5
- import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
6
4
  import { EnrollmentStatus } from '@unchainedshop/core-enrollments';
7
5
  import { PaymentAdapter, PaymentDirector, PaymentError } from '@unchainedshop/core-payment';
8
6
  import { createLogger } from '@unchainedshop/logger';
@@ -10,11 +8,7 @@ import { AppleTransactionsModule } from './module/configureAppleTransactionsModu
10
8
 
11
9
  const logger = createLogger('unchained:core-payment:iap');
12
10
 
13
- const {
14
- APPLE_IAP_SHARED_SECRET,
15
- APPLE_IAP_ENVIRONMENT = 'sandbox',
16
- APPLE_IAP_WEBHOOK_PATH = '/payment/apple-iap',
17
- } = process.env;
11
+ const { APPLE_IAP_SHARED_SECRET, APPLE_IAP_ENVIRONMENT = 'sandbox' } = process.env;
18
12
 
19
13
  // https://developer.apple.com/documentation/storekit/in-app_purchase/validating_receipts_with_the_app_store
20
14
  const environments = {
@@ -88,144 +82,134 @@ const fixPeriods = async (
88
82
  );
89
83
  };
90
84
 
91
- export default (app) => {
92
- useMiddlewareWithCurrentContext(
93
- app,
94
- APPLE_IAP_WEBHOOK_PATH,
95
- bodyParser.json({
96
- strict: false,
97
- }),
98
- );
99
-
100
- useMiddlewareWithCurrentContext(app, APPLE_IAP_WEBHOOK_PATH, async (req, res) => {
101
- if (req.method === 'POST') {
102
- try {
103
- const resolvedContext = req.unchainedContext as Context;
104
- const { modules, services } = resolvedContext;
105
- const responseBody = req.body || {};
106
- if (responseBody.password !== APPLE_IAP_SHARED_SECRET) {
107
- throw new Error('shared secret not valid');
108
- }
109
-
110
- const transactions = responseBody?.unified_receipt?.latest_receipt_info; // eslint-disable-line
111
- const latestTransaction = transactions[0];
112
-
113
- if (responseBody.notification_type === AppleNotificationTypes.INITIAL_BUY) {
114
- // Find the cart to checkout
115
- const orderPayment = await modules.orders.payments.findOrderPaymentByContextData({
116
- context: {
117
- 'meta.transactionIdentifier': latestTransaction.transaction_id,
118
- },
119
- });
85
+ export const appleIAPHandler = async (req, res) => {
86
+ if (req.method === 'POST') {
87
+ try {
88
+ const resolvedContext = req.unchainedContext as Context;
89
+ const { modules, services } = resolvedContext;
90
+ const responseBody = req.body || {};
91
+ if (responseBody.password !== APPLE_IAP_SHARED_SECRET) {
92
+ throw new Error('shared secret not valid');
93
+ }
120
94
 
121
- if (!orderPayment) throw new Error('Could not find any matching order payment');
122
- const order = await modules.orders.findOrder({
123
- orderId: orderPayment.orderId,
124
- });
95
+ const transactions = responseBody?.unified_receipt?.latest_receipt_info; // eslint-disable-line
96
+ const latestTransaction = transactions[0];
125
97
 
126
- if (modules.orders.isCart(order)) {
127
- // checkout if is cart, else just ignore because the cart is already checked out
128
- // through submission of the receipt with GraphQL
129
- const checkedOut = await modules.orders.checkout(
130
- order._id,
131
- {
132
- paymentContext: {
133
- receiptData: responseBody?.unified_receipt?.latest_receipt, // eslint-disable-line
134
- },
135
- },
136
- resolvedContext,
137
- );
138
- const orderId = checkedOut._id;
139
- const enrollment = await modules.enrollments.findEnrollment({
140
- orderId,
141
- });
142
- await fixPeriods(
143
- {
144
- transactionId: latestTransaction.original_transaction_id,
145
- transactions,
146
- enrollmentId: enrollment._id,
147
- orderId,
148
- },
149
- resolvedContext,
150
- );
98
+ if (responseBody.notification_type === AppleNotificationTypes.INITIAL_BUY) {
99
+ // Find the cart to checkout
100
+ const orderPayment = await modules.orders.payments.findOrderPaymentByContextData({
101
+ context: {
102
+ 'meta.transactionIdentifier': latestTransaction.transaction_id,
103
+ },
104
+ });
151
105
 
152
- logger.info(`Apple IAP Webhook: Confirmed checkout for order ${checkedOut.orderNumber}`, {
153
- orderId: checkedOut._id,
154
- });
155
- }
156
- } else {
157
- // Just store payment credentials, use the enrollments paymentProvider reference and
158
- // let the job do the rest
159
- const originalOrderPayment = await modules.orders.payments.findOrderPaymentByContextData({
160
- context: {
161
- 'meta.transactionIdentifier': latestTransaction.original_transaction_id,
162
- },
163
- });
164
- if (!originalOrderPayment) throw new Error('Could not find any matching order payment');
165
- const originalOrder = await modules.orders.findOrder({
166
- orderId: originalOrderPayment.orderId,
167
- });
168
- const enrollment = await modules.enrollments.findEnrollment({
169
- orderId: originalOrder._id,
170
- });
106
+ if (!orderPayment) throw new Error('Could not find any matching order payment');
107
+ const order = await modules.orders.findOrder({
108
+ orderId: orderPayment.orderId,
109
+ });
171
110
 
172
- await services.payment.registerPaymentCredentials(
173
- enrollment.payment.paymentProviderId,
111
+ if (modules.orders.isCart(order)) {
112
+ // checkout if is cart, else just ignore because the cart is already checked out
113
+ // through submission of the receipt with GraphQL
114
+ const checkedOut = await modules.orders.checkout(
115
+ order._id,
174
116
  {
175
- transactionContext: {
117
+ paymentContext: {
176
118
  receiptData: responseBody?.unified_receipt?.latest_receipt, // eslint-disable-line
177
119
  },
178
120
  },
179
121
  resolvedContext,
180
122
  );
181
-
123
+ const orderId = checkedOut._id;
124
+ const enrollment = await modules.enrollments.findEnrollment({
125
+ orderId,
126
+ });
182
127
  await fixPeriods(
183
128
  {
184
129
  transactionId: latestTransaction.original_transaction_id,
185
130
  transactions,
186
131
  enrollmentId: enrollment._id,
187
- orderId: originalOrder._id,
132
+ orderId,
188
133
  },
189
134
  resolvedContext,
190
135
  );
191
136
 
192
- logger.info(
193
- `Apple IAP Webhook: Processed notification for ${latestTransaction.original_transaction_id} and type ${responseBody.notification_type}`,
194
- );
137
+ logger.info(`Apple IAP Webhook: Confirmed checkout for order ${checkedOut.orderNumber}`, {
138
+ orderId: checkedOut._id,
139
+ });
140
+ }
141
+ } else {
142
+ // Just store payment credentials, use the enrollments paymentProvider reference and
143
+ // let the job do the rest
144
+ const originalOrderPayment = await modules.orders.payments.findOrderPaymentByContextData({
145
+ context: {
146
+ 'meta.transactionIdentifier': latestTransaction.original_transaction_id,
147
+ },
148
+ });
149
+ if (!originalOrderPayment) throw new Error('Could not find any matching order payment');
150
+ const originalOrder = await modules.orders.findOrder({
151
+ orderId: originalOrderPayment.orderId,
152
+ });
153
+ const enrollment = await modules.enrollments.findEnrollment({
154
+ orderId: originalOrder._id,
155
+ });
195
156
 
196
- if (responseBody.notification_type === AppleNotificationTypes.DID_RECOVER) {
197
- if (
198
- enrollment.status !== EnrollmentStatus.TERMINATED &&
199
- responseBody.auto_renew_status === 'false'
200
- ) {
201
- await modules.enrollments.terminateEnrollment(enrollment, {}, resolvedContext);
202
- }
203
- }
157
+ await services.payment.registerPaymentCredentials(
158
+ enrollment.payment.paymentProviderId,
159
+ {
160
+ transactionContext: {
161
+ receiptData: responseBody?.unified_receipt?.latest_receipt, // eslint-disable-line
162
+ },
163
+ },
164
+ resolvedContext,
165
+ );
204
166
 
205
- if (responseBody.notification_type === AppleNotificationTypes.DID_CHANGE_RENEWAL_STATUS) {
206
- if (
207
- enrollment.status !== EnrollmentStatus.TERMINATED &&
208
- responseBody.auto_renew_status === 'false'
209
- ) {
210
- await modules.enrollments.terminateEnrollment(enrollment, {}, resolvedContext);
211
- }
167
+ await fixPeriods(
168
+ {
169
+ transactionId: latestTransaction.original_transaction_id,
170
+ transactions,
171
+ enrollmentId: enrollment._id,
172
+ orderId: originalOrder._id,
173
+ },
174
+ resolvedContext,
175
+ );
176
+
177
+ logger.info(
178
+ `Apple IAP Webhook: Processed notification for ${latestTransaction.original_transaction_id} and type ${responseBody.notification_type}`,
179
+ );
180
+
181
+ if (responseBody.notification_type === AppleNotificationTypes.DID_RECOVER) {
182
+ if (
183
+ enrollment.status !== EnrollmentStatus.TERMINATED &&
184
+ responseBody.auto_renew_status === 'false'
185
+ ) {
186
+ await modules.enrollments.terminateEnrollment(enrollment, {}, resolvedContext);
212
187
  }
213
- logger.info(`Apple IAP Webhook: Updated enrollment from Apple`);
214
188
  }
215
189
 
216
- res.writeHead(200);
217
- res.end();
218
- return;
219
- } catch (e) {
220
- logger.warn(`Apple IAP Webhook: ${e.message}`, e);
221
- res.writeHead(503);
222
- res.end(JSON.stringify({ name: e.name, code: e.code, message: e.message }));
223
- return;
190
+ if (responseBody.notification_type === AppleNotificationTypes.DID_CHANGE_RENEWAL_STATUS) {
191
+ if (
192
+ enrollment.status !== EnrollmentStatus.TERMINATED &&
193
+ responseBody.auto_renew_status === 'false'
194
+ ) {
195
+ await modules.enrollments.terminateEnrollment(enrollment, {}, resolvedContext);
196
+ }
197
+ }
198
+ logger.info(`Apple IAP Webhook: Updated enrollment from Apple`);
224
199
  }
200
+
201
+ res.writeHead(200);
202
+ res.end();
203
+ return;
204
+ } catch (e) {
205
+ logger.warn(`Apple IAP Webhook: ${e.message}`, e);
206
+ res.writeHead(503);
207
+ res.end(JSON.stringify({ name: e.name, code: e.code, message: e.message }));
208
+ return;
225
209
  }
226
- res.writeHead(404);
227
- res.end();
228
- });
210
+ }
211
+ res.writeHead(404);
212
+ res.end();
229
213
  };
230
214
 
231
215
  const AppleIAP: IPaymentAdapter = {
@@ -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';
@@ -112,7 +112,7 @@ const BraintreeDirect: IPaymentAdapter = {
112
112
  // @ts-ignore
113
113
  const braintree = (await import('braintree')).default; // eslint-disable-line
114
114
  const gateway = getGateway(braintree);
115
- const address = order.billingAddress || {};
115
+ const address = order.billingAddress;
116
116
  const pricing = modules.orders.pricingSheet(order);
117
117
  const rounded = Math.round(pricing.total({ useNetPrice: false }).amount / 10 || 0) * 10;
118
118
  const saleRequest = {
@@ -120,17 +120,19 @@ const BraintreeDirect: IPaymentAdapter = {
120
120
  merchantAccountId: order.currency,
121
121
  paymentMethodNonce: paypalPaymentMethodNonce,
122
122
  orderId: order.orderNumber || order._id,
123
- shipping: {
124
- firstName: address.firstName,
125
- lastName: address.lastName,
126
- company: address.company,
127
- streetAddress: address.addressLine,
128
- extendedAddress: address.addressLine2,
129
- locality: address.city,
130
- region: address.regionCode,
131
- postalCode: address.postalCode,
132
- countryCodeAlpha2: address.countryCode,
133
- },
123
+ shipping: address
124
+ ? {
125
+ firstName: address.firstName,
126
+ lastName: address.lastName,
127
+ company: address.company,
128
+ streetAddress: address.addressLine,
129
+ extendedAddress: address.addressLine2,
130
+ locality: address.city,
131
+ region: address.regionCode,
132
+ postalCode: address.postalCode,
133
+ countryCodeAlpha2: address.countryCode,
134
+ }
135
+ : undefined,
134
136
  options: {
135
137
  submitForSettlement: true,
136
138
  },
@@ -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
+ logger.verbose(`update rate ${JSON.stringify(price)}, ${JSON.stringify(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 } =