@blocklet/payment-react-headless 1.26.0

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 (250) hide show
  1. package/.eslintrc.js +18 -0
  2. package/build.config.ts +30 -0
  3. package/es/checkout/context/CheckoutProvider.d.ts +6 -0
  4. package/es/checkout/context/CheckoutProvider.js +209 -0
  5. package/es/checkout/context/CustomerFormContext.d.ts +4 -0
  6. package/es/checkout/context/CustomerFormContext.js +9 -0
  7. package/es/checkout/context/ExchangeRateContext.d.ts +11 -0
  8. package/es/checkout/context/ExchangeRateContext.js +9 -0
  9. package/es/checkout/context/PaymentMethodContext.d.ts +26 -0
  10. package/es/checkout/context/PaymentMethodContext.js +9 -0
  11. package/es/checkout/context/SessionContext.d.ts +45 -0
  12. package/es/checkout/context/SessionContext.js +9 -0
  13. package/es/checkout/context/SubmitContext.d.ts +4 -0
  14. package/es/checkout/context/SubmitContext.js +9 -0
  15. package/es/checkout/context/index.d.ts +6 -0
  16. package/es/checkout/context/index.js +6 -0
  17. package/es/checkout/core/billingInterval.d.ts +15 -0
  18. package/es/checkout/core/billingInterval.js +36 -0
  19. package/es/checkout/core/crossSell.d.ts +4 -0
  20. package/es/checkout/core/crossSell.js +30 -0
  21. package/es/checkout/core/customerForm.d.ts +5 -0
  22. package/es/checkout/core/customerForm.js +105 -0
  23. package/es/checkout/core/exchangeRate.d.ts +11 -0
  24. package/es/checkout/core/exchangeRate.js +25 -0
  25. package/es/checkout/core/index.d.ts +10 -0
  26. package/es/checkout/core/index.js +55 -0
  27. package/es/checkout/core/lineItems.d.ts +7 -0
  28. package/es/checkout/core/lineItems.js +59 -0
  29. package/es/checkout/core/paymentMethod.d.ts +23 -0
  30. package/es/checkout/core/paymentMethod.js +85 -0
  31. package/es/checkout/core/pricing.d.ts +32 -0
  32. package/es/checkout/core/pricing.js +221 -0
  33. package/es/checkout/core/promotion.d.ts +10 -0
  34. package/es/checkout/core/promotion.js +39 -0
  35. package/es/checkout/core/session.d.ts +26 -0
  36. package/es/checkout/core/session.js +50 -0
  37. package/es/checkout/core/submit.d.ts +40 -0
  38. package/es/checkout/core/submit.js +66 -0
  39. package/es/checkout/hooks/index.d.ts +34 -0
  40. package/es/checkout/hooks/index.js +19 -0
  41. package/es/checkout/hooks/useBillingInterval.d.ts +14 -0
  42. package/es/checkout/hooks/useBillingInterval.js +50 -0
  43. package/es/checkout/hooks/useCheckout.d.ts +2 -0
  44. package/es/checkout/hooks/useCheckout.js +212 -0
  45. package/es/checkout/hooks/useCheckoutSession.d.ts +58 -0
  46. package/es/checkout/hooks/useCheckoutSession.js +107 -0
  47. package/es/checkout/hooks/useCheckoutStatus.d.ts +10 -0
  48. package/es/checkout/hooks/useCheckoutStatus.js +16 -0
  49. package/es/checkout/hooks/useCrossSell.d.ts +8 -0
  50. package/es/checkout/hooks/useCrossSell.js +57 -0
  51. package/es/checkout/hooks/useCustomerForm.d.ts +14 -0
  52. package/es/checkout/hooks/useCustomerForm.js +116 -0
  53. package/es/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
  54. package/es/checkout/hooks/useCustomerFormFeature.js +4 -0
  55. package/es/checkout/hooks/useExchangeRate.d.ts +11 -0
  56. package/es/checkout/hooks/useExchangeRate.js +15 -0
  57. package/es/checkout/hooks/useLineItems.d.ts +22 -0
  58. package/es/checkout/hooks/useLineItems.js +139 -0
  59. package/es/checkout/hooks/usePaymentMethod.d.ts +26 -0
  60. package/es/checkout/hooks/usePaymentMethod.js +101 -0
  61. package/es/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
  62. package/es/checkout/hooks/usePaymentMethodFeature.js +4 -0
  63. package/es/checkout/hooks/usePricing.d.ts +57 -0
  64. package/es/checkout/hooks/usePricing.js +174 -0
  65. package/es/checkout/hooks/usePricingFeature.d.ts +28 -0
  66. package/es/checkout/hooks/usePricingFeature.js +36 -0
  67. package/es/checkout/hooks/useProduct.d.ts +32 -0
  68. package/es/checkout/hooks/useProduct.js +5 -0
  69. package/es/checkout/hooks/usePromotion.d.ts +12 -0
  70. package/es/checkout/hooks/usePromotion.js +48 -0
  71. package/es/checkout/hooks/useSlippage.d.ts +8 -0
  72. package/es/checkout/hooks/useSlippage.js +29 -0
  73. package/es/checkout/hooks/useSubmit.d.ts +38 -0
  74. package/es/checkout/hooks/useSubmit.js +493 -0
  75. package/es/checkout/hooks/useSubmitFeature.d.ts +2 -0
  76. package/es/checkout/hooks/useSubmitFeature.js +4 -0
  77. package/es/checkout/hooks/useUpsell.d.ts +5 -0
  78. package/es/checkout/hooks/useUpsell.js +25 -0
  79. package/es/checkout/index.d.ts +37 -0
  80. package/es/checkout/index.js +28 -0
  81. package/es/checkout/types.d.ts +262 -0
  82. package/es/checkout/types.js +0 -0
  83. package/es/index.d.ts +1 -0
  84. package/es/index.js +28 -0
  85. package/es/shared/api.d.ts +41 -0
  86. package/es/shared/api.js +81 -0
  87. package/es/shared/format.d.ts +38 -0
  88. package/es/shared/format.js +229 -0
  89. package/es/shared/polling.d.ts +15 -0
  90. package/es/shared/polling.js +20 -0
  91. package/es/shared/types.d.ts +10 -0
  92. package/es/shared/types.js +0 -0
  93. package/es/shared/validation.d.ts +38 -0
  94. package/es/shared/validation.js +190 -0
  95. package/es/types/checkout-augmented.d.ts +42 -0
  96. package/es/types/checkout-augmented.js +17 -0
  97. package/es/types/external.d.ts +18 -0
  98. package/examples/01-basic-checkout.tsx +159 -0
  99. package/examples/01-credit-recharge.tsx +19 -0
  100. package/examples/02-subscription.tsx +40 -0
  101. package/examples/03-upsell.tsx +60 -0
  102. package/examples/04-cross-sell.tsx +54 -0
  103. package/examples/05-full-checkout.tsx +126 -0
  104. package/jest.config.js +15 -0
  105. package/lib/checkout/context/CheckoutProvider.d.ts +6 -0
  106. package/lib/checkout/context/CheckoutProvider.js +181 -0
  107. package/lib/checkout/context/CustomerFormContext.d.ts +4 -0
  108. package/lib/checkout/context/CustomerFormContext.js +16 -0
  109. package/lib/checkout/context/ExchangeRateContext.d.ts +11 -0
  110. package/lib/checkout/context/ExchangeRateContext.js +16 -0
  111. package/lib/checkout/context/PaymentMethodContext.d.ts +26 -0
  112. package/lib/checkout/context/PaymentMethodContext.js +16 -0
  113. package/lib/checkout/context/SessionContext.d.ts +45 -0
  114. package/lib/checkout/context/SessionContext.js +16 -0
  115. package/lib/checkout/context/SubmitContext.d.ts +4 -0
  116. package/lib/checkout/context/SubmitContext.js +16 -0
  117. package/lib/checkout/context/index.d.ts +6 -0
  118. package/lib/checkout/context/index.js +77 -0
  119. package/lib/checkout/core/billingInterval.d.ts +15 -0
  120. package/lib/checkout/core/billingInterval.js +42 -0
  121. package/lib/checkout/core/crossSell.d.ts +4 -0
  122. package/lib/checkout/core/crossSell.js +43 -0
  123. package/lib/checkout/core/customerForm.d.ts +5 -0
  124. package/lib/checkout/core/customerForm.js +106 -0
  125. package/lib/checkout/core/exchangeRate.d.ts +11 -0
  126. package/lib/checkout/core/exchangeRate.js +45 -0
  127. package/lib/checkout/core/index.d.ts +10 -0
  128. package/lib/checkout/core/index.js +297 -0
  129. package/lib/checkout/core/lineItems.d.ts +7 -0
  130. package/lib/checkout/core/lineItems.js +76 -0
  131. package/lib/checkout/core/paymentMethod.d.ts +23 -0
  132. package/lib/checkout/core/paymentMethod.js +114 -0
  133. package/lib/checkout/core/pricing.d.ts +32 -0
  134. package/lib/checkout/core/pricing.js +216 -0
  135. package/lib/checkout/core/promotion.d.ts +10 -0
  136. package/lib/checkout/core/promotion.js +62 -0
  137. package/lib/checkout/core/session.d.ts +26 -0
  138. package/lib/checkout/core/session.js +58 -0
  139. package/lib/checkout/core/submit.d.ts +40 -0
  140. package/lib/checkout/core/submit.js +84 -0
  141. package/lib/checkout/hooks/index.d.ts +34 -0
  142. package/lib/checkout/hooks/index.js +138 -0
  143. package/lib/checkout/hooks/useBillingInterval.d.ts +14 -0
  144. package/lib/checkout/hooks/useBillingInterval.js +63 -0
  145. package/lib/checkout/hooks/useCheckout.d.ts +2 -0
  146. package/lib/checkout/hooks/useCheckout.js +190 -0
  147. package/lib/checkout/hooks/useCheckoutSession.d.ts +58 -0
  148. package/lib/checkout/hooks/useCheckoutSession.js +119 -0
  149. package/lib/checkout/hooks/useCheckoutStatus.d.ts +10 -0
  150. package/lib/checkout/hooks/useCheckoutStatus.js +28 -0
  151. package/lib/checkout/hooks/useCrossSell.d.ts +8 -0
  152. package/lib/checkout/hooks/useCrossSell.js +75 -0
  153. package/lib/checkout/hooks/useCustomerForm.d.ts +14 -0
  154. package/lib/checkout/hooks/useCustomerForm.js +135 -0
  155. package/lib/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
  156. package/lib/checkout/hooks/useCustomerFormFeature.js +10 -0
  157. package/lib/checkout/hooks/useExchangeRate.d.ts +11 -0
  158. package/lib/checkout/hooks/useExchangeRate.js +29 -0
  159. package/lib/checkout/hooks/useLineItems.d.ts +22 -0
  160. package/lib/checkout/hooks/useLineItems.js +142 -0
  161. package/lib/checkout/hooks/usePaymentMethod.d.ts +26 -0
  162. package/lib/checkout/hooks/usePaymentMethod.js +101 -0
  163. package/lib/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
  164. package/lib/checkout/hooks/usePaymentMethodFeature.js +10 -0
  165. package/lib/checkout/hooks/usePricing.d.ts +57 -0
  166. package/lib/checkout/hooks/usePricing.js +168 -0
  167. package/lib/checkout/hooks/usePricingFeature.d.ts +28 -0
  168. package/lib/checkout/hooks/usePricingFeature.js +48 -0
  169. package/lib/checkout/hooks/useProduct.d.ts +32 -0
  170. package/lib/checkout/hooks/useProduct.js +21 -0
  171. package/lib/checkout/hooks/usePromotion.d.ts +12 -0
  172. package/lib/checkout/hooks/usePromotion.js +57 -0
  173. package/lib/checkout/hooks/useSlippage.d.ts +8 -0
  174. package/lib/checkout/hooks/useSlippage.js +39 -0
  175. package/lib/checkout/hooks/useSubmit.d.ts +38 -0
  176. package/lib/checkout/hooks/useSubmit.js +504 -0
  177. package/lib/checkout/hooks/useSubmitFeature.d.ts +2 -0
  178. package/lib/checkout/hooks/useSubmitFeature.js +10 -0
  179. package/lib/checkout/hooks/useUpsell.d.ts +5 -0
  180. package/lib/checkout/hooks/useUpsell.js +40 -0
  181. package/lib/checkout/index.d.ts +37 -0
  182. package/lib/checkout/index.js +182 -0
  183. package/lib/checkout/types.d.ts +262 -0
  184. package/lib/checkout/types.js +1 -0
  185. package/lib/index.d.ts +1 -0
  186. package/lib/index.js +162 -0
  187. package/lib/shared/api.d.ts +41 -0
  188. package/lib/shared/api.js +88 -0
  189. package/lib/shared/format.d.ts +38 -0
  190. package/lib/shared/format.js +262 -0
  191. package/lib/shared/polling.d.ts +15 -0
  192. package/lib/shared/polling.js +32 -0
  193. package/lib/shared/types.d.ts +10 -0
  194. package/lib/shared/types.js +1 -0
  195. package/lib/shared/validation.d.ts +38 -0
  196. package/lib/shared/validation.js +212 -0
  197. package/lib/types/checkout-augmented.d.ts +42 -0
  198. package/lib/types/checkout-augmented.js +24 -0
  199. package/lib/types/external.d.ts +18 -0
  200. package/package.json +64 -0
  201. package/src/checkout/context/CheckoutProvider.tsx +269 -0
  202. package/src/checkout/context/CustomerFormContext.ts +14 -0
  203. package/src/checkout/context/ExchangeRateContext.ts +21 -0
  204. package/src/checkout/context/PaymentMethodContext.ts +36 -0
  205. package/src/checkout/context/SessionContext.ts +49 -0
  206. package/src/checkout/context/SubmitContext.ts +14 -0
  207. package/src/checkout/context/index.ts +6 -0
  208. package/src/checkout/core/billingInterval.ts +62 -0
  209. package/src/checkout/core/crossSell.ts +52 -0
  210. package/src/checkout/core/customerForm.ts +122 -0
  211. package/src/checkout/core/exchangeRate.ts +38 -0
  212. package/src/checkout/core/index.ts +60 -0
  213. package/src/checkout/core/lineItems.ts +106 -0
  214. package/src/checkout/core/paymentMethod.ts +113 -0
  215. package/src/checkout/core/pricing.ts +347 -0
  216. package/src/checkout/core/promotion.ts +59 -0
  217. package/src/checkout/core/session.ts +62 -0
  218. package/src/checkout/core/submit.ts +109 -0
  219. package/src/checkout/hooks/index.ts +41 -0
  220. package/src/checkout/hooks/useBillingInterval.ts +71 -0
  221. package/src/checkout/hooks/useCheckout.ts +267 -0
  222. package/src/checkout/hooks/useCheckoutSession.ts +217 -0
  223. package/src/checkout/hooks/useCheckoutStatus.ts +31 -0
  224. package/src/checkout/hooks/useCrossSell.ts +80 -0
  225. package/src/checkout/hooks/useCustomerForm.ts +156 -0
  226. package/src/checkout/hooks/useCustomerFormFeature.ts +7 -0
  227. package/src/checkout/hooks/useExchangeRate.ts +28 -0
  228. package/src/checkout/hooks/useLineItems.ts +191 -0
  229. package/src/checkout/hooks/usePaymentMethod.ts +165 -0
  230. package/src/checkout/hooks/usePaymentMethodFeature.ts +8 -0
  231. package/src/checkout/hooks/usePricing.ts +274 -0
  232. package/src/checkout/hooks/usePricingFeature.ts +73 -0
  233. package/src/checkout/hooks/useProduct.ts +32 -0
  234. package/src/checkout/hooks/usePromotion.ts +67 -0
  235. package/src/checkout/hooks/useSlippage.ts +39 -0
  236. package/src/checkout/hooks/useSubmit.ts +684 -0
  237. package/src/checkout/hooks/useSubmitFeature.ts +7 -0
  238. package/src/checkout/hooks/useUpsell.ts +35 -0
  239. package/src/checkout/index.ts +65 -0
  240. package/src/checkout/types.ts +292 -0
  241. package/src/index.ts +64 -0
  242. package/src/shared/api.ts +118 -0
  243. package/src/shared/format.ts +318 -0
  244. package/src/shared/polling.ts +49 -0
  245. package/src/shared/types.ts +13 -0
  246. package/src/shared/validation.ts +254 -0
  247. package/src/types/checkout-augmented.ts +77 -0
  248. package/src/types/external.d.ts +18 -0
  249. package/tools/jest.js +1 -0
  250. package/tsconfig.json +18 -0
@@ -0,0 +1,57 @@
1
+ import { useMemo, useState, useEffect } from "react";
2
+ import { useMemoizedFn } from "ahooks";
3
+ import { getErrorMessage } from "../../types/checkout-augmented.js";
4
+ import { useSessionContext } from "../context/SessionContext.js";
5
+ import { usePaymentMethodContext } from "../context/PaymentMethodContext.js";
6
+ import { getCrossSellItem } from "../core/lineItems.js";
7
+ import { addCrossSellItem, removeCrossSellItem, fetchCrossSellItem } from "../core/crossSell.js";
8
+ export function useCrossSell() {
9
+ const { items, session, effectiveSessionId, refresh } = useSessionContext();
10
+ const { currency } = usePaymentMethodContext();
11
+ const currencyId = currency?.id || null;
12
+ const embeddedItem = useMemo(() => getCrossSellItem(items), [items]);
13
+ const [fetchedItem, setFetchedItem] = useState(null);
14
+ const itemPriceIds = useMemo(() => items.map((i) => i.price_id).join(","), [items]);
15
+ const hasCrossSellInItems = useMemo(() => items.some((i) => i.cross_sell), [items]);
16
+ useEffect(() => {
17
+ if (!effectiveSessionId || !session) return void 0;
18
+ if (session.status === "complete") return void 0;
19
+ if (embeddedItem) {
20
+ setFetchedItem(null);
21
+ return void 0;
22
+ }
23
+ if (hasCrossSellInItems) {
24
+ return void 0;
25
+ }
26
+ let cancelled = false;
27
+ fetchCrossSellItem(effectiveSessionId).then((item2) => {
28
+ if (!cancelled) {
29
+ setFetchedItem(item2);
30
+ }
31
+ });
32
+ return () => {
33
+ cancelled = true;
34
+ };
35
+ }, [effectiveSessionId, session?.id, embeddedItem, itemPriceIds, hasCrossSellInItems]);
36
+ const item = embeddedItem || fetchedItem;
37
+ const required = useMemo(() => items.some((i) => i.cross_sell_required), [items]);
38
+ const add = useMemoizedFn(async () => {
39
+ if (session?.status === "complete") return;
40
+ const crossSellItemPrice = getCrossSellItem(items);
41
+ if (!crossSellItemPrice) return;
42
+ try {
43
+ await addCrossSellItem(effectiveSessionId, crossSellItemPrice.id, session, currencyId, refresh);
44
+ } catch (err) {
45
+ console.error("Failed to add cross-sell:", getErrorMessage(err));
46
+ }
47
+ });
48
+ const remove = useMemoizedFn(async () => {
49
+ if (session?.status === "complete") return;
50
+ try {
51
+ await removeCrossSellItem(effectiveSessionId, session, currencyId, refresh);
52
+ } catch (err) {
53
+ console.error("Failed to remove cross-sell:", getErrorMessage(err));
54
+ }
55
+ });
56
+ return { item, required, add, remove };
57
+ }
@@ -0,0 +1,14 @@
1
+ import type { FieldConfig, CheckoutFormData } from '../types';
2
+ import type { SessionData } from './useCheckoutSession';
3
+ export interface UseCustomerFormReturn {
4
+ fields: FieldConfig[];
5
+ values: CheckoutFormData;
6
+ onChange: (field: string, value: string | boolean | Record<string, string>) => void;
7
+ errors: Partial<Record<string, string>>;
8
+ touched: Record<string, boolean>;
9
+ validate: () => Promise<boolean>;
10
+ validateField: (field: string) => Promise<void>;
11
+ /** Re-fetch customer info from backend and update form values (e.g. after login) */
12
+ refetchCustomer: () => Promise<void>;
13
+ }
14
+ export declare function useCustomerForm(sessionData: SessionData | null, currencyId: string | null, methodId: string | null): UseCustomerFormReturn;
@@ -0,0 +1,116 @@
1
+ import { useState, useMemo, useEffect } from "react";
2
+ import { useMemoizedFn } from "ahooks";
3
+ import api, { API } from "../../shared/api.js";
4
+ import { validateForm } from "../../shared/validation.js";
5
+ import { buildFields, createInitialValues, setNestedValue } from "../core/customerForm.js";
6
+ export function useCustomerForm(sessionData, currencyId, methodId) {
7
+ const session = sessionData?.checkoutSession;
8
+ const customer = sessionData?.customer;
9
+ const fields = useMemo(() => buildFields(session), [session?.id]);
10
+ const [values, setValues] = useState(() => createInitialValues(session, customer));
11
+ const [errors, setErrors] = useState({});
12
+ const [touched, setTouched] = useState({});
13
+ const [prefetched, setPrefetched] = useState(false);
14
+ useEffect(() => {
15
+ if (session && !prefetched) {
16
+ setValues(createInitialValues(session, customer));
17
+ }
18
+ }, [session?.id]);
19
+ useEffect(() => {
20
+ if (currencyId || methodId) {
21
+ setValues((prev) => ({
22
+ ...prev,
23
+ ...currencyId && { payment_currency: currencyId },
24
+ ...methodId && { payment_method: methodId }
25
+ }));
26
+ }
27
+ }, [currencyId, methodId]);
28
+ useEffect(() => {
29
+ if (!session || prefetched || session.status === "complete") return;
30
+ const fetchCustomer = async () => {
31
+ try {
32
+ const { data } = await api.get(`${API.CUSTOMER_ME}?fallback=1&skipSummary=1`);
33
+ if (data) {
34
+ setPrefetched(true);
35
+ setValues((prev) => ({
36
+ ...prev,
37
+ customer_name: prev.customer_name || data.name || "",
38
+ customer_email: prev.customer_email || data.email || "",
39
+ customer_phone: prev.customer_phone || data.phone || "",
40
+ billing_address: {
41
+ ...prev.billing_address,
42
+ country: prev.billing_address?.country || data.address?.country || "",
43
+ state: prev.billing_address?.state || data.address?.state || "",
44
+ city: prev.billing_address?.city || data.address?.city || "",
45
+ line1: prev.billing_address?.line1 || data.address?.line1 || "",
46
+ line2: prev.billing_address?.line2 || data.address?.line2 || "",
47
+ postal_code: prev.billing_address?.postal_code || data.address?.postal_code || ""
48
+ }
49
+ }));
50
+ }
51
+ } catch {
52
+ }
53
+ };
54
+ fetchCustomer();
55
+ }, [session?.id]);
56
+ const onChange = useMemoizedFn((field, value) => {
57
+ setValues((prev) => setNestedValue(prev, field, value));
58
+ setTouched((prev) => ({ ...prev, [field]: true }));
59
+ });
60
+ const getValidateOptions = useMemoizedFn(() => ({
61
+ phoneEnabled: !!session?.phone_number_collection?.enabled,
62
+ addressMode: session?.billing_address_collection,
63
+ fieldValidation: session?.metadata?.page_info?.field_validation
64
+ }));
65
+ const validate = useMemoizedFn(async () => {
66
+ const result = await validateForm(values, getValidateOptions());
67
+ setErrors(result.errors);
68
+ return result.valid;
69
+ });
70
+ const validateField = useMemoizedFn(async (field) => {
71
+ const result = await validateForm(values, getValidateOptions());
72
+ setErrors((prev) => {
73
+ const next = { ...prev };
74
+ if (result.errors[field]) {
75
+ next[field] = result.errors[field];
76
+ } else {
77
+ delete next[field];
78
+ }
79
+ return next;
80
+ });
81
+ });
82
+ const refetchCustomer = useMemoizedFn(async () => {
83
+ try {
84
+ const { data } = await api.get(`${API.CUSTOMER_ME}?fallback=1&skipSummary=1`);
85
+ if (data) {
86
+ setPrefetched(true);
87
+ setValues((prev) => ({
88
+ ...prev,
89
+ customer_name: data.name || prev.customer_name || "",
90
+ customer_email: data.email || prev.customer_email || "",
91
+ customer_phone: data.phone || prev.customer_phone || "",
92
+ billing_address: {
93
+ ...prev.billing_address,
94
+ country: data.address?.country || prev.billing_address?.country || "",
95
+ state: data.address?.state || prev.billing_address?.state || "",
96
+ city: data.address?.city || prev.billing_address?.city || "",
97
+ line1: data.address?.line1 || prev.billing_address?.line1 || "",
98
+ line2: data.address?.line2 || prev.billing_address?.line2 || "",
99
+ postal_code: data.address?.postal_code || prev.billing_address?.postal_code || ""
100
+ }
101
+ }));
102
+ }
103
+ } catch {
104
+ }
105
+ });
106
+ return {
107
+ fields,
108
+ values,
109
+ onChange,
110
+ errors,
111
+ touched,
112
+ validate,
113
+ validateField,
114
+ refetchCustomer
115
+ };
116
+ }
@@ -0,0 +1,2 @@
1
+ import type { UseCustomerFormReturn } from './useCustomerForm';
2
+ export declare function useCustomerFormFeature(): UseCustomerFormReturn;
@@ -0,0 +1,4 @@
1
+ import { useCustomerFormContext } from "../context/CustomerFormContext.js";
2
+ export function useCustomerFormFeature() {
3
+ return useCustomerFormContext();
4
+ }
@@ -0,0 +1,11 @@
1
+ export interface UseExchangeRateReturn {
2
+ value: string | null;
3
+ display: string | null;
4
+ provider: string | null;
5
+ providerDisplay: string | null;
6
+ fetchedAt: number | null;
7
+ status: 'loading' | 'available' | 'unavailable';
8
+ hasDynamicPricing: boolean;
9
+ refresh: () => Promise<void>;
10
+ }
11
+ export declare function useExchangeRate(): UseExchangeRateReturn;
@@ -0,0 +1,15 @@
1
+ import { useExchangeRateContext } from "../context/ExchangeRateContext.js";
2
+ import { formatExchangeRate, formatExchangeRateDisplay } from "../../shared/format.js";
3
+ export function useExchangeRate() {
4
+ const { rate, provider, providerDisplay, fetchedAt, status, hasDynamicPricing, refresh } = useExchangeRateContext();
5
+ return {
6
+ value: formatExchangeRate(rate),
7
+ display: rate ? formatExchangeRateDisplay(rate) : null,
8
+ provider,
9
+ providerDisplay,
10
+ fetchedAt,
11
+ status,
12
+ hasDynamicPricing,
13
+ refresh
14
+ };
15
+ }
@@ -0,0 +1,22 @@
1
+ import type { TLineItemExpanded, TPrice } from '@blocklet/payment-types';
2
+ export interface UseLineItemsReturn {
3
+ items: Array<TLineItemExpanded & {
4
+ adjustable_quantity?: {
5
+ enabled: boolean;
6
+ minimum?: number;
7
+ maximum?: number;
8
+ };
9
+ }>;
10
+ /** true if all items pass inventory check (quantity_available, quantity_limit_per_checkout) */
11
+ inventoryOk: boolean;
12
+ updateQuantity: (itemId: string, qty: number) => Promise<void>;
13
+ upsell: (fromId: string, toId: string) => Promise<void>;
14
+ downsell: (priceId: string) => Promise<void>;
15
+ crossSellItem: TPrice | null;
16
+ crossSellRequired: boolean;
17
+ addCrossSell: () => Promise<void>;
18
+ removeCrossSell: () => Promise<void>;
19
+ isDonation: boolean;
20
+ setDonationAmount: (priceId: string, amount: string) => Promise<void>;
21
+ }
22
+ export declare function useLineItems(): UseLineItemsReturn;
@@ -0,0 +1,139 @@
1
+ import { useMemo, useState, useEffect, useRef } from "react";
2
+ import { useMemoizedFn } from "ahooks";
3
+ import { getErrorMessage } from "../../types/checkout-augmented.js";
4
+ import { useSessionContext } from "../context/SessionContext.js";
5
+ import { usePaymentMethodContext } from "../context/PaymentMethodContext.js";
6
+ import {
7
+ adjustQuantity,
8
+ performUpsell,
9
+ performDownsell,
10
+ changeDonationAmount,
11
+ getCrossSellItem
12
+ } from "../core/lineItems.js";
13
+ import { addCrossSellItem, removeCrossSellItem, fetchCrossSellItem } from "../core/crossSell.js";
14
+ export function useLineItems() {
15
+ const { items, session, effectiveSessionId, isDonation, refresh } = useSessionContext();
16
+ const { currency } = usePaymentMethodContext();
17
+ const currencyId = currency?.id || null;
18
+ const defaultQtyApplied = useRef(false);
19
+ useEffect(() => {
20
+ if (defaultQtyApplied.current || !effectiveSessionId || !items.length || !currencyId || session?.status === "complete") return;
21
+ try {
22
+ const params = new URLSearchParams(window.location.search);
23
+ for (const item of items) {
24
+ const qtyStr = params.get(`qty_${item.price_id}`) || params.get(`qty_${item.price?.id}`) || params.get("qty");
25
+ if (qtyStr) {
26
+ const qty = Math.max(1, parseInt(qtyStr, 10));
27
+ if (Number.isFinite(qty) && qty !== item.quantity) {
28
+ defaultQtyApplied.current = true;
29
+ adjustQuantity(effectiveSessionId, item.price_id, qty, currencyId, session, refresh);
30
+ break;
31
+ }
32
+ }
33
+ }
34
+ } catch {
35
+ }
36
+ }, [effectiveSessionId, items, currencyId]);
37
+ const updateQuantity = useMemoizedFn(async (itemId, qty) => {
38
+ if (session?.status === "complete") return;
39
+ try {
40
+ await adjustQuantity(effectiveSessionId, itemId, qty, currencyId, session, refresh);
41
+ } catch (err) {
42
+ console.error("Failed to update quantity:", getErrorMessage(err));
43
+ }
44
+ });
45
+ const upsell = useMemoizedFn(async (fromId, toId) => {
46
+ if (session?.status === "complete") return;
47
+ await performUpsell(effectiveSessionId, fromId, toId, session, currencyId, refresh);
48
+ });
49
+ const downsell = useMemoizedFn(async (priceId) => {
50
+ if (session?.status === "complete") return;
51
+ await performDownsell(effectiveSessionId, priceId, session, currencyId, refresh);
52
+ });
53
+ const embeddedCrossSellItem = useMemo(() => getCrossSellItem(items), [items]);
54
+ const [fetchedCrossSellItem, setFetchedCrossSellItem] = useState(null);
55
+ const itemPriceIds = useMemo(() => items.map((i) => i.price_id).join(","), [items]);
56
+ const hasCrossSellInItems = useMemo(() => items.some((i) => i.cross_sell), [items]);
57
+ useEffect(() => {
58
+ if (!effectiveSessionId || !session) return void 0;
59
+ if (session.status === "complete") return void 0;
60
+ if (embeddedCrossSellItem) {
61
+ setFetchedCrossSellItem(null);
62
+ return void 0;
63
+ }
64
+ if (hasCrossSellInItems) {
65
+ return void 0;
66
+ }
67
+ let cancelled = false;
68
+ fetchCrossSellItem(effectiveSessionId).then((item) => {
69
+ if (!cancelled) {
70
+ setFetchedCrossSellItem(item);
71
+ }
72
+ });
73
+ return () => {
74
+ cancelled = true;
75
+ };
76
+ }, [effectiveSessionId, session?.id, embeddedCrossSellItem, itemPriceIds, hasCrossSellInItems]);
77
+ const crossSellItem = embeddedCrossSellItem || fetchedCrossSellItem;
78
+ const crossSellRequired = useMemo(() => items.some((item) => item.cross_sell_required), [items]);
79
+ const addCrossSell = useMemoizedFn(async () => {
80
+ if (session?.status === "complete") return;
81
+ if (!crossSellItem) return;
82
+ try {
83
+ await addCrossSellItem(effectiveSessionId, crossSellItem.id, session, currencyId, refresh);
84
+ } catch (err) {
85
+ console.error("Failed to add cross-sell:", getErrorMessage(err));
86
+ }
87
+ });
88
+ const removeCrossSell = useMemoizedFn(async () => {
89
+ if (session?.status === "complete") return;
90
+ try {
91
+ await removeCrossSellItem(effectiveSessionId, session, currencyId, refresh);
92
+ } catch (err) {
93
+ console.error("Failed to remove cross-sell:", getErrorMessage(err));
94
+ }
95
+ });
96
+ const setDonationAmount = useMemoizedFn(async (priceId, amount) => {
97
+ if (session?.status === "complete") return;
98
+ if (!isDonation) return;
99
+ try {
100
+ await changeDonationAmount(effectiveSessionId, priceId, amount, session, currencyId, refresh);
101
+ } catch (err) {
102
+ console.error("Failed to change amount:", getErrorMessage(err));
103
+ }
104
+ });
105
+ const mappedItems = useMemo(
106
+ () => items.map((item) => ({
107
+ ...item,
108
+ adjustable_quantity: item.adjustable_quantity
109
+ })),
110
+ [items]
111
+ );
112
+ const inventoryOk = useMemo(
113
+ () => items.every((item) => {
114
+ const { price } = item;
115
+ if (!price) return true;
116
+ const q = Number(item.quantity) || 0;
117
+ const available = price.quantity_available || 0;
118
+ const sold = price.quantity_sold || 0;
119
+ const limitPerCheckout = price.quantity_limit_per_checkout || 0;
120
+ if (available > 0 && sold + q > available) return false;
121
+ if (limitPerCheckout > 0 && limitPerCheckout < q) return false;
122
+ return true;
123
+ }),
124
+ [items]
125
+ );
126
+ return {
127
+ items: mappedItems,
128
+ inventoryOk,
129
+ updateQuantity,
130
+ upsell,
131
+ downsell,
132
+ crossSellItem,
133
+ crossSellRequired,
134
+ addCrossSell,
135
+ removeCrossSell,
136
+ isDonation,
137
+ setDonationAmount
138
+ };
139
+ }
@@ -0,0 +1,26 @@
1
+ import type { TPaymentMethodExpanded, TPaymentCurrency } from '@blocklet/payment-types';
2
+ import type { SessionData } from './useCheckoutSession';
3
+ export interface UsePaymentMethodReturn {
4
+ current: TPaymentMethodExpanded;
5
+ currency: TPaymentCurrency;
6
+ available: TPaymentMethodExpanded[];
7
+ currencies: TPaymentCurrency[];
8
+ isStripe: boolean;
9
+ isCrypto: boolean;
10
+ isCredit: boolean;
11
+ switching: boolean;
12
+ setType: (type: 'stripe' | 'crypto') => Promise<void>;
13
+ types: Array<{
14
+ type: 'stripe' | 'crypto';
15
+ label: string;
16
+ currencies: TPaymentCurrency[];
17
+ active: boolean;
18
+ }>;
19
+ setCurrency: (currencyId: string) => Promise<void>;
20
+ stripe: {
21
+ publishableKey: string | null;
22
+ clientSecret: string | null;
23
+ status: 'idle' | 'ready' | 'processing' | 'succeeded' | 'failed';
24
+ } | null;
25
+ }
26
+ export declare function usePaymentMethod(sessionData: SessionData | null, sessionId: string, refreshSession: (force?: boolean) => Promise<void>): UsePaymentMethodReturn;
@@ -0,0 +1,101 @@
1
+ import { useState, useMemo, useEffect, useRef } from "react";
2
+ import { useMemoizedFn } from "ahooks";
3
+ import { getErrorMessage } from "../../types/checkout-augmented.js";
4
+ import api, { API } from "../../shared/api.js";
5
+ import {
6
+ flattenCurrencies,
7
+ getInitialCurrencyId,
8
+ getCurrencyStorageKey,
9
+ findMethodAndCurrency,
10
+ buildPaymentTypes
11
+ } from "../core/paymentMethod.js";
12
+ export function usePaymentMethod(sessionData, sessionId, refreshSession) {
13
+ const methods = sessionData?.paymentMethods || [];
14
+ const session = sessionData?.checkoutSession;
15
+ const [currencyId, setCurrencyId] = useState(() => getInitialCurrencyId(session, methods));
16
+ const [switching, setSwitching] = useState(false);
17
+ const initialSyncedRef = useRef(null);
18
+ useEffect(() => {
19
+ if (session && !currencyId) {
20
+ setCurrencyId(getInitialCurrencyId(session, methods));
21
+ }
22
+ }, [session?.id]);
23
+ const { method: currentMethod, currency: currentCurrency } = useMemo(
24
+ () => findMethodAndCurrency(methods, currencyId),
25
+ [methods, currencyId]
26
+ );
27
+ const allCurrencies = useMemo(() => flattenCurrencies(methods), [methods]);
28
+ const isStripe = currentMethod?.type === "stripe";
29
+ const isCrypto = currentMethod?.type !== "stripe" && currentMethod?.type !== void 0;
30
+ const isCredit = currentCurrency?.type === "credit";
31
+ const types = useMemo(() => buildPaymentTypes(methods, currentMethod), [methods, currentMethod]);
32
+ const setType = useMemoizedFn(async (type) => {
33
+ const targetMethod = methods.find((m) => type === "stripe" ? m.type === "stripe" : m.type !== "stripe");
34
+ if (!targetMethod) return;
35
+ const firstCurrency = targetMethod.payment_currencies?.[0];
36
+ if (firstCurrency) {
37
+ await switchCurrency(firstCurrency.id);
38
+ }
39
+ });
40
+ const switchCurrency = useMemoizedFn(async (newCurrencyId) => {
41
+ if (session?.status === "complete") return;
42
+ const { method } = findMethodAndCurrency(methods, newCurrencyId);
43
+ if (!method || !sessionId) return;
44
+ setSwitching(true);
45
+ try {
46
+ await api.put(API.SWITCH_CURRENCY(sessionId), {
47
+ currency_id: newCurrencyId,
48
+ payment_method_id: method.id
49
+ });
50
+ setCurrencyId(newCurrencyId);
51
+ try {
52
+ localStorage.setItem(
53
+ getCurrencyStorageKey(session?.user?.did),
54
+ newCurrencyId
55
+ );
56
+ } catch {
57
+ }
58
+ await refreshSession(true);
59
+ } catch (err) {
60
+ console.error("Failed to switch currency:", getErrorMessage(err));
61
+ if (session?.currency_id) {
62
+ setCurrencyId(session.currency_id);
63
+ }
64
+ } finally {
65
+ setSwitching(false);
66
+ }
67
+ });
68
+ useEffect(() => {
69
+ if (!session?.id || !currencyId || !methods.length) return;
70
+ if (initialSyncedRef.current === session.id) return;
71
+ initialSyncedRef.current = session.id;
72
+ const sessionCurrencyId = session.currency_id;
73
+ if (session.status === "complete") return;
74
+ if (sessionCurrencyId && sessionCurrencyId !== currencyId) {
75
+ switchCurrency(currencyId);
76
+ }
77
+ }, [session?.id, currencyId, methods.length]);
78
+ const stripe = useMemo(() => {
79
+ if (!currentMethod || currentMethod.type !== "stripe") return null;
80
+ const stripeSettings = currentMethod.settings?.stripe;
81
+ return {
82
+ publishableKey: stripeSettings?.publishable_key || null,
83
+ clientSecret: sessionData?.paymentIntent?.client_secret || null,
84
+ status: "idle"
85
+ };
86
+ }, [currentMethod, sessionData?.paymentIntent]);
87
+ return {
88
+ current: currentMethod,
89
+ currency: currentCurrency,
90
+ available: methods,
91
+ currencies: allCurrencies,
92
+ isStripe,
93
+ isCrypto,
94
+ isCredit,
95
+ switching,
96
+ setType,
97
+ types,
98
+ setCurrency: switchCurrency,
99
+ stripe
100
+ };
101
+ }
@@ -0,0 +1,2 @@
1
+ import type { UsePaymentMethodReturn } from './usePaymentMethod';
2
+ export declare function usePaymentMethodFeature(): UsePaymentMethodReturn;
@@ -0,0 +1,4 @@
1
+ import { usePaymentMethodContext } from "../context/PaymentMethodContext.js";
2
+ export function usePaymentMethodFeature() {
3
+ return usePaymentMethodContext();
4
+ }
@@ -0,0 +1,57 @@
1
+ import type { TPaymentCurrency } from '@blocklet/payment-types';
2
+ import type { SessionData } from './useCheckoutSession';
3
+ export interface UsePricingReturn {
4
+ subtotal: string;
5
+ paymentAmount: string;
6
+ discount: string | null;
7
+ tax: {
8
+ amount: string;
9
+ rate: number;
10
+ inclusive: boolean;
11
+ } | null;
12
+ staking: string | null;
13
+ total: string;
14
+ usdEquivalent: string | null;
15
+ hasDynamicPricing: boolean;
16
+ rate: {
17
+ value: string | null;
18
+ display: string | null;
19
+ provider: string | null;
20
+ providerDisplay: string | null;
21
+ fetchedAt: number | null;
22
+ status: 'loading' | 'available' | 'unavailable';
23
+ refresh: () => Promise<void>;
24
+ };
25
+ quote: {
26
+ locked: boolean;
27
+ lockedAt: number | null;
28
+ expiresAt: number | null;
29
+ expired: boolean;
30
+ baseCurrency: string | null;
31
+ };
32
+ slippage: {
33
+ percent: number;
34
+ set: (config: {
35
+ mode: string;
36
+ percent: number;
37
+ }) => Promise<void>;
38
+ };
39
+ promotion: {
40
+ applied: boolean;
41
+ code: string | null;
42
+ active: boolean;
43
+ inactiveReason: string | null;
44
+ apply: (code: string) => Promise<{
45
+ success: boolean;
46
+ error?: string;
47
+ }>;
48
+ remove: () => Promise<void>;
49
+ };
50
+ trial: {
51
+ active: boolean;
52
+ days: number;
53
+ afterTrialPrice: string | null;
54
+ afterTrialInterval: string | null;
55
+ };
56
+ }
57
+ export declare function usePricing(sessionData: SessionData | null, sessionId: string, currency: TPaymentCurrency | null, isStripe: boolean, refreshSession: (force?: boolean) => Promise<void>, paymentMethodType?: string | null): UsePricingReturn;