@blocklet/payment-react 1.13.200 → 1.13.202

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.
@@ -6,9 +6,16 @@ import { joinURL } from "ufo";
6
6
  import api from "../api.js";
7
7
  import Payment from "../payment/index.js";
8
8
  import { getPrefix, mergeExtraParams } from "../util.js";
9
- const startFromPaymentLink = async (id, params) => {
10
- const { data } = await api.post(`/api/checkout-sessions/start/${id}?${mergeExtraParams(params)}`);
11
- return data;
9
+ const promises = {};
10
+ const startFromPaymentLink = (id, params) => {
11
+ if (!promises[id]) {
12
+ promises[id] = api.post(`/api/checkout-sessions/start/${id}?${mergeExtraParams(params)}`).then((res) => res.data).finally(() => {
13
+ setTimeout(() => {
14
+ delete promises[id];
15
+ }, 3e3);
16
+ });
17
+ }
18
+ return promises[id];
12
19
  };
13
20
  const fetchCheckoutSession = async (id) => {
14
21
  const { data } = await api.get(`/api/checkout-sessions/retrieve/${id}`);
@@ -25,9 +32,13 @@ export default function CheckoutForm({ id, mode, onPaid, onError, onChange, goBa
25
32
  );
26
33
  useEffect(() => {
27
34
  if (type === "paymentLink" && mode === "standalone" && data) {
28
- window.history.replaceState(null, "", joinURL(getPrefix(), `/checkout/pay/${data.checkoutSession.id}`));
35
+ window.history.replaceState(
36
+ null,
37
+ "",
38
+ joinURL(getPrefix(), `/checkout/pay/${data.checkoutSession.id}?${mergeExtraParams(extraParams)}`)
39
+ );
29
40
  }
30
- }, [type, mode, data]);
41
+ }, [type, mode, data, extraParams]);
31
42
  const handlePaid = () => {
32
43
  setState({ completed: true });
33
44
  onPaid?.(data);
@@ -140,7 +140,7 @@ export default function PaymentForm({
140
140
  }
141
141
  }
142
142
  };
143
- const onSubmit = async (data) => {
143
+ const onFormSubmit = async (data) => {
144
144
  setState({ submitting: true });
145
145
  try {
146
146
  const result = await api.put(`/api/checkout-sessions/${checkoutSession.id}/submit`, data);
@@ -200,14 +200,23 @@ export default function PaymentForm({
200
200
  setState({ submitting: false });
201
201
  }
202
202
  };
203
+ const onFormError = () => {
204
+ setState({ submitting: false });
205
+ };
203
206
  const onAction = () => {
204
207
  if (session?.user) {
205
- handleSubmit(onSubmit)();
208
+ handleSubmit(onFormSubmit, onFormError)();
206
209
  } else {
207
- session?.login({
208
- // @ts-ignored
209
- onSuccess: onUserLoggedIn,
210
- extraParams: {}
210
+ session?.login(() => {
211
+ setState({ submitting: true });
212
+ onUserLoggedIn().then(() => {
213
+ setTimeout(() => {
214
+ handleSubmit(onFormSubmit, onFormError)();
215
+ }, 50);
216
+ }).catch((err) => {
217
+ console.error(err);
218
+ setState({ submitting: false });
219
+ });
211
220
  });
212
221
  }
213
222
  };
package/es/util.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare function getPaymentIntentStatusColor(status: string): "success" |
27
27
  export declare function getRefundStatusColor(status: string): "success" | "warning" | "default";
28
28
  export declare function getInvoiceStatusColor(status: string): "success" | "warning" | "default" | "secondary";
29
29
  export declare function getWebhookStatusColor(status: string): "success" | "default";
30
- export declare function getCheckoutAmount(items: TLineItemExpanded[], currency: TPaymentCurrency, includeFreeTrial?: boolean, upsell?: boolean): {
30
+ export declare function getCheckoutAmount(items: TLineItemExpanded[], currency: TPaymentCurrency, trialing?: boolean, upsell?: boolean): {
31
31
  subtotal: any;
32
32
  total: any;
33
33
  renew: any;
package/es/util.js CHANGED
@@ -265,7 +265,7 @@ export function getWebhookStatusColor(status) {
265
265
  return "default";
266
266
  }
267
267
  }
268
- export function getCheckoutAmount(items, currency, includeFreeTrial = false, upsell = true) {
268
+ export function getCheckoutAmount(items, currency, trialing = false, upsell = true) {
269
269
  let renew = new BN(0);
270
270
  const total = items.filter((x) => {
271
271
  const price = upsell ? x.upsell_price || x.price : x.price;
@@ -274,7 +274,7 @@ export function getCheckoutAmount(items, currency, includeFreeTrial = false, ups
274
274
  const price = upsell ? x.upsell_price || x.price : x.price;
275
275
  if (price?.type === "recurring") {
276
276
  renew = renew.add(new BN(getPriceUintAmountByCurrency(price, currency)).mul(new BN(x.quantity)));
277
- if (includeFreeTrial) {
277
+ if (trialing) {
278
278
  return acc;
279
279
  }
280
280
  if (price.recurring?.usage_type === "metered") {
@@ -333,9 +333,8 @@ export function formatUpsellSaving(items, currency) {
333
333
  return Number(before.sub(after).mul(new BN(100)).div(before).toString()).toFixed(0);
334
334
  }
335
335
  export function formatCheckoutHeadlines(items, currency, trialInDays, locale = "en") {
336
- const trial = trialInDays || 0;
337
336
  const brand = getStatementDescriptor(items);
338
- const { total } = getCheckoutAmount(items, currency, !!trial);
337
+ const { total } = getCheckoutAmount(items, currency, trialInDays > 0);
339
338
  const amount = `${fromUnitToToken(total, currency.decimal)} ${currency.symbol}`;
340
339
  if (items.length === 0) {
341
340
  return {
@@ -375,10 +374,10 @@ export function formatCheckoutHeadlines(items, currency, trialInDays, locale = "
375
374
  currency.symbol
376
375
  ].filter(Boolean).join(" ");
377
376
  if (items.length > 1) {
378
- if (trial > 0) {
377
+ if (trialInDays > 0) {
379
378
  return {
380
379
  action: t("payment.checkout.try2", locale, { name, count: items.length - 1 }),
381
- amount: t("payment.checkout.free", locale, { count: trial }),
380
+ amount: t("payment.checkout.free", locale, { count: trialInDays }),
382
381
  then: t("payment.checkout.then", locale, { subscription: subscription2, recurring })
383
382
  };
384
383
  }
@@ -388,10 +387,10 @@ export function formatCheckoutHeadlines(items, currency, trialInDays, locale = "
388
387
  then: recurring
389
388
  };
390
389
  }
391
- if (trial > 0) {
390
+ if (trialInDays > 0) {
392
391
  return {
393
392
  action: t("payment.checkout.try1", locale, { name }),
394
- amount: t("payment.checkout.free", locale, { count: trial }),
393
+ amount: t("payment.checkout.free", locale, { count: trialInDays }),
395
394
  then: t("payment.checkout.then", locale, { subscription: subscription2, recurring })
396
395
  };
397
396
  }
@@ -13,11 +13,16 @@ var _api = _interopRequireDefault(require("../api"));
13
13
  var _payment = _interopRequireDefault(require("../payment"));
14
14
  var _util = require("../util");
15
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
- const startFromPaymentLink = async (id, params) => {
17
- const {
18
- data
19
- } = await _api.default.post(`/api/checkout-sessions/start/${id}?${(0, _util.mergeExtraParams)(params)}`);
20
- return data;
16
+ const promises = {};
17
+ const startFromPaymentLink = (id, params) => {
18
+ if (!promises[id]) {
19
+ promises[id] = _api.default.post(`/api/checkout-sessions/start/${id}?${(0, _util.mergeExtraParams)(params)}`).then(res => res.data).finally(() => {
20
+ setTimeout(() => {
21
+ delete promises[id];
22
+ }, 3e3);
23
+ });
24
+ }
25
+ return promises[id];
21
26
  };
22
27
  const fetchCheckoutSession = async id => {
23
28
  const {
@@ -48,9 +53,9 @@ function CheckoutForm({
48
53
  } = (0, _ahooks.useRequest)(() => type === "paymentLink" ? startFromPaymentLink(id, extraParams) : fetchCheckoutSession(id));
49
54
  (0, _react.useEffect)(() => {
50
55
  if (type === "paymentLink" && mode === "standalone" && data) {
51
- window.history.replaceState(null, "", (0, _ufo.joinURL)((0, _util.getPrefix)(), `/checkout/pay/${data.checkoutSession.id}`));
56
+ window.history.replaceState(null, "", (0, _ufo.joinURL)((0, _util.getPrefix)(), `/checkout/pay/${data.checkoutSession.id}?${(0, _util.mergeExtraParams)(extraParams)}`));
52
57
  }
53
- }, [type, mode, data]);
58
+ }, [type, mode, data, extraParams]);
54
59
  const handlePaid = () => {
55
60
  setState({
56
61
  completed: true
@@ -171,7 +171,7 @@ function PaymentForm({
171
171
  }
172
172
  }
173
173
  };
174
- const onSubmit = async data => {
174
+ const onFormSubmit = async data => {
175
175
  setState({
176
176
  submitting: true
177
177
  });
@@ -251,14 +251,29 @@ function PaymentForm({
251
251
  });
252
252
  }
253
253
  };
254
+ const onFormError = () => {
255
+ setState({
256
+ submitting: false
257
+ });
258
+ };
254
259
  const onAction = () => {
255
260
  if (session?.user) {
256
- handleSubmit(onSubmit)();
261
+ handleSubmit(onFormSubmit, onFormError)();
257
262
  } else {
258
- session?.login({
259
- // @ts-ignored
260
- onSuccess: onUserLoggedIn,
261
- extraParams: {}
263
+ session?.login(() => {
264
+ setState({
265
+ submitting: true
266
+ });
267
+ onUserLoggedIn().then(() => {
268
+ setTimeout(() => {
269
+ handleSubmit(onFormSubmit, onFormError)();
270
+ }, 50);
271
+ }).catch(err => {
272
+ console.error(err);
273
+ setState({
274
+ submitting: false
275
+ });
276
+ });
262
277
  });
263
278
  }
264
279
  };
package/lib/util.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare function getPaymentIntentStatusColor(status: string): "success" |
27
27
  export declare function getRefundStatusColor(status: string): "success" | "warning" | "default";
28
28
  export declare function getInvoiceStatusColor(status: string): "success" | "warning" | "default" | "secondary";
29
29
  export declare function getWebhookStatusColor(status: string): "success" | "default";
30
- export declare function getCheckoutAmount(items: TLineItemExpanded[], currency: TPaymentCurrency, includeFreeTrial?: boolean, upsell?: boolean): {
30
+ export declare function getCheckoutAmount(items: TLineItemExpanded[], currency: TPaymentCurrency, trialing?: boolean, upsell?: boolean): {
31
31
  subtotal: any;
32
32
  total: any;
33
33
  renew: any;
package/lib/util.js CHANGED
@@ -328,7 +328,7 @@ function getWebhookStatusColor(status) {
328
328
  return "default";
329
329
  }
330
330
  }
331
- function getCheckoutAmount(items, currency, includeFreeTrial = false, upsell = true) {
331
+ function getCheckoutAmount(items, currency, trialing = false, upsell = true) {
332
332
  let renew = new _util.BN(0);
333
333
  const total = items.filter(x => {
334
334
  const price = upsell ? x.upsell_price || x.price : x.price;
@@ -337,7 +337,7 @@ function getCheckoutAmount(items, currency, includeFreeTrial = false, upsell = t
337
337
  const price = upsell ? x.upsell_price || x.price : x.price;
338
338
  if (price?.type === "recurring") {
339
339
  renew = renew.add(new _util.BN(getPriceUintAmountByCurrency(price, currency)).mul(new _util.BN(x.quantity)));
340
- if (includeFreeTrial) {
340
+ if (trialing) {
341
341
  return acc;
342
342
  }
343
343
  if (price.recurring?.usage_type === "metered") {
@@ -400,11 +400,10 @@ function formatUpsellSaving(items, currency) {
400
400
  return Number(before.sub(after).mul(new _util.BN(100)).div(before).toString()).toFixed(0);
401
401
  }
402
402
  function formatCheckoutHeadlines(items, currency, trialInDays, locale = "en") {
403
- const trial = trialInDays || 0;
404
403
  const brand = getStatementDescriptor(items);
405
404
  const {
406
405
  total
407
- } = getCheckoutAmount(items, currency, !!trial);
406
+ } = getCheckoutAmount(items, currency, trialInDays > 0);
408
407
  const amount = `${(0, _util.fromUnitToToken)(total, currency.decimal)} ${currency.symbol}`;
409
408
  if (items.length === 0) {
410
409
  return {
@@ -445,14 +444,14 @@ function formatCheckoutHeadlines(items, currency, trialInDays, locale = "en") {
445
444
  return acc.add(new _util.BN(getPriceUintAmountByCurrency(x.price, currency)).mul(new _util.BN(x.quantity)));
446
445
  }, new _util.BN(0)), currency.decimal), currency.symbol].filter(Boolean).join(" ");
447
446
  if (items.length > 1) {
448
- if (trial > 0) {
447
+ if (trialInDays > 0) {
449
448
  return {
450
449
  action: (0, _locales.t)("payment.checkout.try2", locale, {
451
450
  name,
452
451
  count: items.length - 1
453
452
  }),
454
453
  amount: (0, _locales.t)("payment.checkout.free", locale, {
455
- count: trial
454
+ count: trialInDays
456
455
  }),
457
456
  then: (0, _locales.t)("payment.checkout.then", locale, {
458
457
  subscription: subscription2,
@@ -469,13 +468,13 @@ function formatCheckoutHeadlines(items, currency, trialInDays, locale = "en") {
469
468
  then: recurring
470
469
  };
471
470
  }
472
- if (trial > 0) {
471
+ if (trialInDays > 0) {
473
472
  return {
474
473
  action: (0, _locales.t)("payment.checkout.try1", locale, {
475
474
  name
476
475
  }),
477
476
  amount: (0, _locales.t)("payment.checkout.free", locale, {
478
- count: trial
477
+ count: trialInDays
479
478
  }),
480
479
  then: (0, _locales.t)("payment.checkout.then", locale, {
481
480
  subscription: subscription2,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blocklet/payment-react",
3
- "version": "1.13.200",
3
+ "version": "1.13.202",
4
4
  "description": "Reusable react components for payment kit v2",
5
5
  "keywords": [
6
6
  "react",
@@ -52,8 +52,8 @@
52
52
  }
53
53
  },
54
54
  "dependencies": {
55
- "@arcblock/did-connect": "^2.9.57",
56
- "@arcblock/ux": "^2.9.57",
55
+ "@arcblock/did-connect": "^2.9.63",
56
+ "@arcblock/ux": "^2.9.63",
57
57
  "@mui/icons-material": "^5.15.14",
58
58
  "@mui/lab": "^5.0.0-alpha.169",
59
59
  "@mui/material": "^5.15.14",
@@ -85,12 +85,12 @@
85
85
  "access": "public"
86
86
  },
87
87
  "devDependencies": {
88
- "@arcblock/eslint-config-ts": "^0.2.4",
88
+ "@arcblock/eslint-config-ts": "^0.3.0",
89
89
  "@babel/cli": "^7.23.9",
90
90
  "@babel/core": "^7.23.9",
91
91
  "@babel/preset-env": "^7.23.9",
92
92
  "@babel/preset-react": "^7.23.3",
93
- "@blocklet/payment-types": "1.13.200",
93
+ "@blocklet/payment-types": "1.13.202",
94
94
  "@storybook/addon-essentials": "^7.6.13",
95
95
  "@storybook/addon-interactions": "^7.6.13",
96
96
  "@storybook/addon-links": "^7.6.13",
@@ -119,5 +119,5 @@
119
119
  "vite-plugin-babel": "^1.2.0",
120
120
  "vite-plugin-node-polyfills": "^0.19.0"
121
121
  },
122
- "gitHead": "c57f8e82c4c319183c371393f1bb9891366a36f6"
122
+ "gitHead": "e9c7a403fee7506f92118581d659c91f210714a7"
123
123
  }
@@ -10,9 +10,20 @@ import Payment from '../payment';
10
10
  import { CheckoutContext, CheckoutProps } from '../types';
11
11
  import { getPrefix, mergeExtraParams } from '../util';
12
12
 
13
- const startFromPaymentLink = async (id: string, params?: Record<string, any>): Promise<CheckoutContext> => {
14
- const { data } = await api.post(`/api/checkout-sessions/start/${id}?${mergeExtraParams(params)}`);
15
- return data;
13
+ const promises: { [key: string]: Promise<any> } = {};
14
+ const startFromPaymentLink = (id: string, params?: Record<string, any>): Promise<CheckoutContext> => {
15
+ if (!promises[id]) {
16
+ promises[id] = api
17
+ .post(`/api/checkout-sessions/start/${id}?${mergeExtraParams(params)}`)
18
+ .then((res) => res.data)
19
+ .finally(() => {
20
+ setTimeout(() => {
21
+ delete promises[id];
22
+ }, 3000);
23
+ });
24
+ }
25
+
26
+ return promises[id];
16
27
  };
17
28
 
18
29
  const fetchCheckoutSession = async (id: string): Promise<CheckoutContext> => {
@@ -36,9 +47,13 @@ export default function CheckoutForm({ id, mode, onPaid, onError, onChange, goBa
36
47
 
37
48
  useEffect(() => {
38
49
  if (type === 'paymentLink' && mode === 'standalone' && data) {
39
- window.history.replaceState(null, '', joinURL(getPrefix(), `/checkout/pay/${data.checkoutSession.id}`));
50
+ window.history.replaceState(
51
+ null,
52
+ '',
53
+ joinURL(getPrefix(), `/checkout/pay/${data.checkoutSession.id}?${mergeExtraParams(extraParams)}`)
54
+ );
40
55
  }
41
- }, [type, mode, data]);
56
+ }, [type, mode, data, extraParams]);
42
57
 
43
58
  const handlePaid = () => {
44
59
  setState({ completed: true });
@@ -192,7 +192,7 @@ export default function PaymentForm({
192
192
  }
193
193
  };
194
194
 
195
- const onSubmit = async (data: any) => {
195
+ const onFormSubmit = async (data: any) => {
196
196
  setState({ submitting: true });
197
197
  try {
198
198
  const result = await api.put(`/api/checkout-sessions/${checkoutSession.id}/submit`, data);
@@ -256,15 +256,26 @@ export default function PaymentForm({
256
256
  }
257
257
  };
258
258
 
259
+ const onFormError = () => {
260
+ setState({ submitting: false });
261
+ };
262
+
259
263
  const onAction = () => {
260
264
  if (session?.user) {
261
- handleSubmit(onSubmit)();
265
+ handleSubmit(onFormSubmit, onFormError)();
262
266
  } else {
263
- // @ts-ignored
264
- session?.login({
265
- // @ts-ignored
266
- onSuccess: onUserLoggedIn,
267
- extraParams: {},
267
+ session?.login(() => {
268
+ setState({ submitting: true });
269
+ onUserLoggedIn()
270
+ .then(() => {
271
+ setTimeout(() => {
272
+ handleSubmit(onFormSubmit, onFormError)();
273
+ }, 50);
274
+ })
275
+ .catch((err) => {
276
+ console.error(err);
277
+ setState({ submitting: false });
278
+ });
268
279
  });
269
280
  }
270
281
  };
package/src/util.ts CHANGED
@@ -367,7 +367,7 @@ export function getWebhookStatusColor(status: string) {
367
367
  export function getCheckoutAmount(
368
368
  items: TLineItemExpanded[],
369
369
  currency: TPaymentCurrency,
370
- includeFreeTrial = false,
370
+ trialing = false,
371
371
  upsell = true
372
372
  ) {
373
373
  let renew = new BN(0);
@@ -381,7 +381,7 @@ export function getCheckoutAmount(
381
381
  if (price?.type === 'recurring') {
382
382
  renew = renew.add(new BN(getPriceUintAmountByCurrency(price, currency)).mul(new BN(x.quantity)));
383
383
 
384
- if (includeFreeTrial) {
384
+ if (trialing) {
385
385
  return acc;
386
386
  }
387
387
  if (price.recurring?.usage_type === 'metered') {
@@ -461,9 +461,8 @@ export function formatCheckoutHeadlines(
461
461
  then?: string;
462
462
  secondary?: string;
463
463
  } {
464
- const trial = trialInDays || 0;
465
464
  const brand = getStatementDescriptor(items);
466
- const { total } = getCheckoutAmount(items, currency, !!trial);
465
+ const { total } = getCheckoutAmount(items, currency, trialInDays > 0);
467
466
  const amount = `${fromUnitToToken(total, currency.decimal)} ${currency.symbol}`;
468
467
 
469
468
  // empty
@@ -514,10 +513,10 @@ export function formatCheckoutHeadlines(
514
513
  .filter(Boolean)
515
514
  .join(' ');
516
515
  if (items.length > 1) {
517
- if (trial > 0) {
516
+ if (trialInDays > 0) {
518
517
  return {
519
518
  action: t('payment.checkout.try2', locale, { name, count: items.length - 1 }),
520
- amount: t('payment.checkout.free', locale, { count: trial }),
519
+ amount: t('payment.checkout.free', locale, { count: trialInDays }),
521
520
  then: t('payment.checkout.then', locale, { subscription, recurring }),
522
521
  };
523
522
  }
@@ -529,10 +528,10 @@ export function formatCheckoutHeadlines(
529
528
  };
530
529
  }
531
530
 
532
- if (trial > 0) {
531
+ if (trialInDays > 0) {
533
532
  return {
534
533
  action: t('payment.checkout.try1', locale, { name }),
535
- amount: t('payment.checkout.free', locale, { count: trial }),
534
+ amount: t('payment.checkout.free', locale, { count: trialInDays }),
536
535
  then: t('payment.checkout.then', locale, { subscription, recurring }),
537
536
  };
538
537
  }