@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.
- package/.eslintrc.js +18 -0
- package/build.config.ts +30 -0
- package/es/checkout/context/CheckoutProvider.d.ts +6 -0
- package/es/checkout/context/CheckoutProvider.js +209 -0
- package/es/checkout/context/CustomerFormContext.d.ts +4 -0
- package/es/checkout/context/CustomerFormContext.js +9 -0
- package/es/checkout/context/ExchangeRateContext.d.ts +11 -0
- package/es/checkout/context/ExchangeRateContext.js +9 -0
- package/es/checkout/context/PaymentMethodContext.d.ts +26 -0
- package/es/checkout/context/PaymentMethodContext.js +9 -0
- package/es/checkout/context/SessionContext.d.ts +45 -0
- package/es/checkout/context/SessionContext.js +9 -0
- package/es/checkout/context/SubmitContext.d.ts +4 -0
- package/es/checkout/context/SubmitContext.js +9 -0
- package/es/checkout/context/index.d.ts +6 -0
- package/es/checkout/context/index.js +6 -0
- package/es/checkout/core/billingInterval.d.ts +15 -0
- package/es/checkout/core/billingInterval.js +36 -0
- package/es/checkout/core/crossSell.d.ts +4 -0
- package/es/checkout/core/crossSell.js +30 -0
- package/es/checkout/core/customerForm.d.ts +5 -0
- package/es/checkout/core/customerForm.js +105 -0
- package/es/checkout/core/exchangeRate.d.ts +11 -0
- package/es/checkout/core/exchangeRate.js +25 -0
- package/es/checkout/core/index.d.ts +10 -0
- package/es/checkout/core/index.js +55 -0
- package/es/checkout/core/lineItems.d.ts +7 -0
- package/es/checkout/core/lineItems.js +59 -0
- package/es/checkout/core/paymentMethod.d.ts +23 -0
- package/es/checkout/core/paymentMethod.js +85 -0
- package/es/checkout/core/pricing.d.ts +32 -0
- package/es/checkout/core/pricing.js +221 -0
- package/es/checkout/core/promotion.d.ts +10 -0
- package/es/checkout/core/promotion.js +39 -0
- package/es/checkout/core/session.d.ts +26 -0
- package/es/checkout/core/session.js +50 -0
- package/es/checkout/core/submit.d.ts +40 -0
- package/es/checkout/core/submit.js +66 -0
- package/es/checkout/hooks/index.d.ts +34 -0
- package/es/checkout/hooks/index.js +19 -0
- package/es/checkout/hooks/useBillingInterval.d.ts +14 -0
- package/es/checkout/hooks/useBillingInterval.js +50 -0
- package/es/checkout/hooks/useCheckout.d.ts +2 -0
- package/es/checkout/hooks/useCheckout.js +212 -0
- package/es/checkout/hooks/useCheckoutSession.d.ts +58 -0
- package/es/checkout/hooks/useCheckoutSession.js +107 -0
- package/es/checkout/hooks/useCheckoutStatus.d.ts +10 -0
- package/es/checkout/hooks/useCheckoutStatus.js +16 -0
- package/es/checkout/hooks/useCrossSell.d.ts +8 -0
- package/es/checkout/hooks/useCrossSell.js +57 -0
- package/es/checkout/hooks/useCustomerForm.d.ts +14 -0
- package/es/checkout/hooks/useCustomerForm.js +116 -0
- package/es/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
- package/es/checkout/hooks/useCustomerFormFeature.js +4 -0
- package/es/checkout/hooks/useExchangeRate.d.ts +11 -0
- package/es/checkout/hooks/useExchangeRate.js +15 -0
- package/es/checkout/hooks/useLineItems.d.ts +22 -0
- package/es/checkout/hooks/useLineItems.js +139 -0
- package/es/checkout/hooks/usePaymentMethod.d.ts +26 -0
- package/es/checkout/hooks/usePaymentMethod.js +101 -0
- package/es/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
- package/es/checkout/hooks/usePaymentMethodFeature.js +4 -0
- package/es/checkout/hooks/usePricing.d.ts +57 -0
- package/es/checkout/hooks/usePricing.js +174 -0
- package/es/checkout/hooks/usePricingFeature.d.ts +28 -0
- package/es/checkout/hooks/usePricingFeature.js +36 -0
- package/es/checkout/hooks/useProduct.d.ts +32 -0
- package/es/checkout/hooks/useProduct.js +5 -0
- package/es/checkout/hooks/usePromotion.d.ts +12 -0
- package/es/checkout/hooks/usePromotion.js +48 -0
- package/es/checkout/hooks/useSlippage.d.ts +8 -0
- package/es/checkout/hooks/useSlippage.js +29 -0
- package/es/checkout/hooks/useSubmit.d.ts +38 -0
- package/es/checkout/hooks/useSubmit.js +493 -0
- package/es/checkout/hooks/useSubmitFeature.d.ts +2 -0
- package/es/checkout/hooks/useSubmitFeature.js +4 -0
- package/es/checkout/hooks/useUpsell.d.ts +5 -0
- package/es/checkout/hooks/useUpsell.js +25 -0
- package/es/checkout/index.d.ts +37 -0
- package/es/checkout/index.js +28 -0
- package/es/checkout/types.d.ts +262 -0
- package/es/checkout/types.js +0 -0
- package/es/index.d.ts +1 -0
- package/es/index.js +28 -0
- package/es/shared/api.d.ts +41 -0
- package/es/shared/api.js +81 -0
- package/es/shared/format.d.ts +38 -0
- package/es/shared/format.js +229 -0
- package/es/shared/polling.d.ts +15 -0
- package/es/shared/polling.js +20 -0
- package/es/shared/types.d.ts +10 -0
- package/es/shared/types.js +0 -0
- package/es/shared/validation.d.ts +38 -0
- package/es/shared/validation.js +190 -0
- package/es/types/checkout-augmented.d.ts +42 -0
- package/es/types/checkout-augmented.js +17 -0
- package/es/types/external.d.ts +18 -0
- package/examples/01-basic-checkout.tsx +159 -0
- package/examples/01-credit-recharge.tsx +19 -0
- package/examples/02-subscription.tsx +40 -0
- package/examples/03-upsell.tsx +60 -0
- package/examples/04-cross-sell.tsx +54 -0
- package/examples/05-full-checkout.tsx +126 -0
- package/jest.config.js +15 -0
- package/lib/checkout/context/CheckoutProvider.d.ts +6 -0
- package/lib/checkout/context/CheckoutProvider.js +181 -0
- package/lib/checkout/context/CustomerFormContext.d.ts +4 -0
- package/lib/checkout/context/CustomerFormContext.js +16 -0
- package/lib/checkout/context/ExchangeRateContext.d.ts +11 -0
- package/lib/checkout/context/ExchangeRateContext.js +16 -0
- package/lib/checkout/context/PaymentMethodContext.d.ts +26 -0
- package/lib/checkout/context/PaymentMethodContext.js +16 -0
- package/lib/checkout/context/SessionContext.d.ts +45 -0
- package/lib/checkout/context/SessionContext.js +16 -0
- package/lib/checkout/context/SubmitContext.d.ts +4 -0
- package/lib/checkout/context/SubmitContext.js +16 -0
- package/lib/checkout/context/index.d.ts +6 -0
- package/lib/checkout/context/index.js +77 -0
- package/lib/checkout/core/billingInterval.d.ts +15 -0
- package/lib/checkout/core/billingInterval.js +42 -0
- package/lib/checkout/core/crossSell.d.ts +4 -0
- package/lib/checkout/core/crossSell.js +43 -0
- package/lib/checkout/core/customerForm.d.ts +5 -0
- package/lib/checkout/core/customerForm.js +106 -0
- package/lib/checkout/core/exchangeRate.d.ts +11 -0
- package/lib/checkout/core/exchangeRate.js +45 -0
- package/lib/checkout/core/index.d.ts +10 -0
- package/lib/checkout/core/index.js +297 -0
- package/lib/checkout/core/lineItems.d.ts +7 -0
- package/lib/checkout/core/lineItems.js +76 -0
- package/lib/checkout/core/paymentMethod.d.ts +23 -0
- package/lib/checkout/core/paymentMethod.js +114 -0
- package/lib/checkout/core/pricing.d.ts +32 -0
- package/lib/checkout/core/pricing.js +216 -0
- package/lib/checkout/core/promotion.d.ts +10 -0
- package/lib/checkout/core/promotion.js +62 -0
- package/lib/checkout/core/session.d.ts +26 -0
- package/lib/checkout/core/session.js +58 -0
- package/lib/checkout/core/submit.d.ts +40 -0
- package/lib/checkout/core/submit.js +84 -0
- package/lib/checkout/hooks/index.d.ts +34 -0
- package/lib/checkout/hooks/index.js +138 -0
- package/lib/checkout/hooks/useBillingInterval.d.ts +14 -0
- package/lib/checkout/hooks/useBillingInterval.js +63 -0
- package/lib/checkout/hooks/useCheckout.d.ts +2 -0
- package/lib/checkout/hooks/useCheckout.js +190 -0
- package/lib/checkout/hooks/useCheckoutSession.d.ts +58 -0
- package/lib/checkout/hooks/useCheckoutSession.js +119 -0
- package/lib/checkout/hooks/useCheckoutStatus.d.ts +10 -0
- package/lib/checkout/hooks/useCheckoutStatus.js +28 -0
- package/lib/checkout/hooks/useCrossSell.d.ts +8 -0
- package/lib/checkout/hooks/useCrossSell.js +75 -0
- package/lib/checkout/hooks/useCustomerForm.d.ts +14 -0
- package/lib/checkout/hooks/useCustomerForm.js +135 -0
- package/lib/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
- package/lib/checkout/hooks/useCustomerFormFeature.js +10 -0
- package/lib/checkout/hooks/useExchangeRate.d.ts +11 -0
- package/lib/checkout/hooks/useExchangeRate.js +29 -0
- package/lib/checkout/hooks/useLineItems.d.ts +22 -0
- package/lib/checkout/hooks/useLineItems.js +142 -0
- package/lib/checkout/hooks/usePaymentMethod.d.ts +26 -0
- package/lib/checkout/hooks/usePaymentMethod.js +101 -0
- package/lib/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
- package/lib/checkout/hooks/usePaymentMethodFeature.js +10 -0
- package/lib/checkout/hooks/usePricing.d.ts +57 -0
- package/lib/checkout/hooks/usePricing.js +168 -0
- package/lib/checkout/hooks/usePricingFeature.d.ts +28 -0
- package/lib/checkout/hooks/usePricingFeature.js +48 -0
- package/lib/checkout/hooks/useProduct.d.ts +32 -0
- package/lib/checkout/hooks/useProduct.js +21 -0
- package/lib/checkout/hooks/usePromotion.d.ts +12 -0
- package/lib/checkout/hooks/usePromotion.js +57 -0
- package/lib/checkout/hooks/useSlippage.d.ts +8 -0
- package/lib/checkout/hooks/useSlippage.js +39 -0
- package/lib/checkout/hooks/useSubmit.d.ts +38 -0
- package/lib/checkout/hooks/useSubmit.js +504 -0
- package/lib/checkout/hooks/useSubmitFeature.d.ts +2 -0
- package/lib/checkout/hooks/useSubmitFeature.js +10 -0
- package/lib/checkout/hooks/useUpsell.d.ts +5 -0
- package/lib/checkout/hooks/useUpsell.js +40 -0
- package/lib/checkout/index.d.ts +37 -0
- package/lib/checkout/index.js +182 -0
- package/lib/checkout/types.d.ts +262 -0
- package/lib/checkout/types.js +1 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +162 -0
- package/lib/shared/api.d.ts +41 -0
- package/lib/shared/api.js +88 -0
- package/lib/shared/format.d.ts +38 -0
- package/lib/shared/format.js +262 -0
- package/lib/shared/polling.d.ts +15 -0
- package/lib/shared/polling.js +32 -0
- package/lib/shared/types.d.ts +10 -0
- package/lib/shared/types.js +1 -0
- package/lib/shared/validation.d.ts +38 -0
- package/lib/shared/validation.js +212 -0
- package/lib/types/checkout-augmented.d.ts +42 -0
- package/lib/types/checkout-augmented.js +24 -0
- package/lib/types/external.d.ts +18 -0
- package/package.json +64 -0
- package/src/checkout/context/CheckoutProvider.tsx +269 -0
- package/src/checkout/context/CustomerFormContext.ts +14 -0
- package/src/checkout/context/ExchangeRateContext.ts +21 -0
- package/src/checkout/context/PaymentMethodContext.ts +36 -0
- package/src/checkout/context/SessionContext.ts +49 -0
- package/src/checkout/context/SubmitContext.ts +14 -0
- package/src/checkout/context/index.ts +6 -0
- package/src/checkout/core/billingInterval.ts +62 -0
- package/src/checkout/core/crossSell.ts +52 -0
- package/src/checkout/core/customerForm.ts +122 -0
- package/src/checkout/core/exchangeRate.ts +38 -0
- package/src/checkout/core/index.ts +60 -0
- package/src/checkout/core/lineItems.ts +106 -0
- package/src/checkout/core/paymentMethod.ts +113 -0
- package/src/checkout/core/pricing.ts +347 -0
- package/src/checkout/core/promotion.ts +59 -0
- package/src/checkout/core/session.ts +62 -0
- package/src/checkout/core/submit.ts +109 -0
- package/src/checkout/hooks/index.ts +41 -0
- package/src/checkout/hooks/useBillingInterval.ts +71 -0
- package/src/checkout/hooks/useCheckout.ts +267 -0
- package/src/checkout/hooks/useCheckoutSession.ts +217 -0
- package/src/checkout/hooks/useCheckoutStatus.ts +31 -0
- package/src/checkout/hooks/useCrossSell.ts +80 -0
- package/src/checkout/hooks/useCustomerForm.ts +156 -0
- package/src/checkout/hooks/useCustomerFormFeature.ts +7 -0
- package/src/checkout/hooks/useExchangeRate.ts +28 -0
- package/src/checkout/hooks/useLineItems.ts +191 -0
- package/src/checkout/hooks/usePaymentMethod.ts +165 -0
- package/src/checkout/hooks/usePaymentMethodFeature.ts +8 -0
- package/src/checkout/hooks/usePricing.ts +274 -0
- package/src/checkout/hooks/usePricingFeature.ts +73 -0
- package/src/checkout/hooks/useProduct.ts +32 -0
- package/src/checkout/hooks/usePromotion.ts +67 -0
- package/src/checkout/hooks/useSlippage.ts +39 -0
- package/src/checkout/hooks/useSubmit.ts +684 -0
- package/src/checkout/hooks/useSubmitFeature.ts +7 -0
- package/src/checkout/hooks/useUpsell.ts +35 -0
- package/src/checkout/index.ts +65 -0
- package/src/checkout/types.ts +292 -0
- package/src/index.ts +64 -0
- package/src/shared/api.ts +118 -0
- package/src/shared/format.ts +318 -0
- package/src/shared/polling.ts +49 -0
- package/src/shared/types.ts +13 -0
- package/src/shared/validation.ts +254 -0
- package/src/types/checkout-augmented.ts +77 -0
- package/src/types/external.d.ts +18 -0
- package/tools/jest.js +1 -0
- 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,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,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;
|