@tagadapay/plugin-sdk 1.0.25 → 1.0.27

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.
@@ -1,7 +1,8 @@
1
- import { useState, useCallback, useEffect, useRef } from 'react';
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { useCurrency } from '../hooks/useCurrency';
2
3
  import { useTagadaContext } from '../providers/TagadaProvider';
3
4
  import { getCheckoutToken } from '../utils/urlUtils';
4
- import { useCurrency } from '../hooks/useCurrency';
5
+ import { collectTrackingData } from '../utils/trackingUtils';
5
6
  export function useCheckout(options = {}) {
6
7
  const { apiService, updateCheckoutDebugData, refreshCoordinator, store, currency } = useTagadaContext();
7
8
  const { code: currentCurrency } = useCurrency();
@@ -62,6 +63,14 @@ export function useCheckout(options = {}) {
62
63
  setIsLoading(true);
63
64
  setError(null);
64
65
  try {
66
+ // Collect tracking data
67
+ const trackingData = await collectTrackingData();
68
+ // Enhanced customerMetadata with tracking data
69
+ const enhancedCustomerMetadata = {
70
+ ...params.customerMetadata,
71
+ localStorage: trackingData.localStorageData,
72
+ cookies: trackingData.trackingCookiesData,
73
+ };
65
74
  const requestBody = {
66
75
  ...params,
67
76
  returnUrl: params.returnUrl || window.location.origin,
@@ -69,6 +78,7 @@ export function useCheckout(options = {}) {
69
78
  ...params.customer,
70
79
  currency: params.customer?.currency || currentCurrency,
71
80
  },
81
+ customerMetadata: enhancedCustomerMetadata,
72
82
  };
73
83
  const response = await apiService.fetch('/api/v1/checkout/session/init', {
74
84
  method: 'POST',
@@ -417,7 +427,7 @@ export function useCheckout(options = {}) {
417
427
  lineItems,
418
428
  storeId: store?.id,
419
429
  currency: currency.code,
420
- promotionIds: promotionIds || [],
430
+ promotionIds: promotionIds ?? [],
421
431
  },
422
432
  });
423
433
  return response;
@@ -0,0 +1,109 @@
1
+ export interface PostPurchaseOfferItem {
2
+ id: string;
3
+ productId: string;
4
+ variantId: string;
5
+ product: {
6
+ name: string;
7
+ description: string;
8
+ };
9
+ variant: {
10
+ name: string;
11
+ description: string;
12
+ imageUrl: string;
13
+ grams: number | null;
14
+ };
15
+ unitAmount: number;
16
+ quantity: number;
17
+ amount: number;
18
+ adjustedAmount: number;
19
+ }
20
+ export interface PostPurchaseOfferSummary {
21
+ currency: string;
22
+ totalAmount: number;
23
+ totalAdjustedAmount: number;
24
+ items: PostPurchaseOfferItem[];
25
+ }
26
+ export interface PostPurchaseOfferLineItem {
27
+ id: string;
28
+ quantity: number;
29
+ price: {
30
+ variant: {
31
+ id: string;
32
+ name: string;
33
+ description: string | null;
34
+ grams: number | null;
35
+ product: {
36
+ id: string;
37
+ name: string;
38
+ description: string;
39
+ };
40
+ };
41
+ };
42
+ }
43
+ export interface PostPurchaseOffer {
44
+ id: string;
45
+ titleTrans: Record<string, string> | null;
46
+ summaries: PostPurchaseOfferSummary[];
47
+ offerLineItems: PostPurchaseOfferLineItem[];
48
+ }
49
+ export interface UsePostPurchasesOptions {
50
+ /**
51
+ * OrderID to fetch post-purchase offers for
52
+ */
53
+ orderId: string;
54
+ /**
55
+ * Whether to fetch offers automatically on mount
56
+ * @default true
57
+ */
58
+ enabled?: boolean;
59
+ }
60
+ export interface UsePostPurchasesResult {
61
+ /**
62
+ * Array of fetched post-purchase offers
63
+ */
64
+ offers: PostPurchaseOffer[];
65
+ /**
66
+ * Loading state
67
+ */
68
+ isLoading: boolean;
69
+ /**
70
+ * Error state
71
+ */
72
+ error: Error | null;
73
+ /**
74
+ * Refetch post-purchase offers
75
+ */
76
+ refetch: () => Promise<void>;
77
+ /**
78
+ * Get offer by ID from the loaded offers
79
+ */
80
+ getOffer: (offerId: string) => PostPurchaseOffer | undefined;
81
+ /**
82
+ * Get total value of all post-purchase offers
83
+ */
84
+ getTotalValue: () => number;
85
+ /**
86
+ * Get total savings across all post-purchase offers
87
+ */
88
+ getTotalSavings: () => number;
89
+ /**
90
+ * Initialize a checkout session for a post-purchase offer
91
+ */
92
+ initCheckoutSession: (offerId: string, orderId: string) => Promise<{
93
+ checkoutSessionId: string;
94
+ }>;
95
+ /**
96
+ * Initialize a checkout session for a post-purchase offer with specific variants
97
+ */
98
+ initCheckoutSessionWithVariants: (offerId: string, orderId: string, lineItems: Array<{
99
+ variantId: string;
100
+ quantity: number;
101
+ }>) => Promise<{
102
+ checkoutSessionId: string;
103
+ }>;
104
+ /**
105
+ * Pay with a checkout session for a post-purchase offer
106
+ */
107
+ payWithCheckoutSession: (checkoutSessionId: string, orderId?: string) => Promise<void>;
108
+ }
109
+ export declare function usePostPurchases(options: UsePostPurchasesOptions): UsePostPurchasesResult;
@@ -0,0 +1,104 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { useTagadaContext } from '../providers/TagadaProvider';
3
+ export function usePostPurchases(options) {
4
+ const { apiService } = useTagadaContext();
5
+ const { orderId, enabled = true } = options;
6
+ const [offers, setOffers] = useState([]);
7
+ const [isLoading, setIsLoading] = useState(false);
8
+ const [error, setError] = useState(null);
9
+ const fetchOffers = useCallback(async () => {
10
+ if (!orderId) {
11
+ setOffers([]);
12
+ return;
13
+ }
14
+ setIsLoading(true);
15
+ setError(null);
16
+ try {
17
+ const response = await apiService.fetch(`/api/v1/post-purchase/${orderId}/offers`, {
18
+ method: 'GET',
19
+ });
20
+ setOffers(response || []);
21
+ }
22
+ catch (err) {
23
+ const error = err instanceof Error ? err : new Error('Failed to fetch post-purchase offers');
24
+ setError(error);
25
+ console.error('[SDK] Failed to fetch post-purchase offers:', error);
26
+ }
27
+ finally {
28
+ setIsLoading(false);
29
+ }
30
+ }, [orderId]);
31
+ const initCheckoutSession = useCallback(async (offerId, orderId) => {
32
+ const response = await apiService.fetch(`/api/v1/checkout/offer/init`, {
33
+ method: 'POST',
34
+ body: JSON.stringify({
35
+ offerId: offerId,
36
+ returnUrl: window.location.href,
37
+ customerId: '',
38
+ orderId,
39
+ }),
40
+ });
41
+ return response;
42
+ }, []);
43
+ const initCheckoutSessionWithVariants = useCallback(async (offerId, orderId, lineItems) => {
44
+ const response = await apiService.fetch(`/api/v1/offers/${offerId}/transform-to-checkout`, {
45
+ method: 'POST',
46
+ body: JSON.stringify({
47
+ offerId: offerId,
48
+ lineItems: lineItems,
49
+ returnUrl: window.location.href,
50
+ mainOrderId: orderId,
51
+ }),
52
+ });
53
+ return response;
54
+ }, []);
55
+ const payWithCheckoutSession = useCallback(async (checkoutSessionId, orderId) => {
56
+ const response = await apiService.fetch(`/api/v1/checkout-sessions/${checkoutSessionId}/pay`, {
57
+ method: 'POST',
58
+ body: JSON.stringify({
59
+ checkoutSessionId,
60
+ metadata: {
61
+ comingFromPostPurchase: true,
62
+ postOrder: orderId,
63
+ },
64
+ }),
65
+ });
66
+ return response;
67
+ }, []);
68
+ useEffect(() => {
69
+ if (enabled && orderId) {
70
+ fetchOffers();
71
+ }
72
+ }, [enabled, orderId, fetchOffers]);
73
+ const getOffer = useCallback((offerId) => {
74
+ return offers.find((offer) => offer.id === offerId);
75
+ }, [offers]);
76
+ const getTotalValue = useCallback(() => {
77
+ return offers.reduce((total, offer) => {
78
+ return (total +
79
+ offer.summaries.reduce((summaryTotal, summary) => {
80
+ return summaryTotal + summary.totalAmount;
81
+ }, 0));
82
+ }, 0);
83
+ }, [offers]);
84
+ const getTotalSavings = useCallback(() => {
85
+ return offers.reduce((total, offer) => {
86
+ return (total +
87
+ offer.summaries.reduce((summaryTotal, summary) => {
88
+ return summaryTotal + (summary.totalAmount - summary.totalAdjustedAmount);
89
+ }, 0));
90
+ }, 0);
91
+ }, [offers]);
92
+ return {
93
+ offers,
94
+ isLoading,
95
+ error,
96
+ refetch: fetchOffers,
97
+ getOffer,
98
+ getTotalValue,
99
+ getTotalSavings,
100
+ initCheckoutSession,
101
+ initCheckoutSessionWithVariants,
102
+ payWithCheckoutSession,
103
+ };
104
+ }
@@ -2,28 +2,30 @@
2
2
  * React SDK exports
3
3
  */
4
4
  export { TagadaProvider } from './providers/TagadaProvider';
5
+ export { useAddress } from './hooks/useAddress';
6
+ export { useAuth } from './hooks/useAuth';
5
7
  export { useCheckout } from './hooks/useCheckout';
6
- export { useProducts } from './hooks/useProducts';
7
- export { useOffers } from './hooks/useOffers';
8
- export { useOrderBump } from './hooks/useOrderBump';
9
- export { useSession } from './hooks/useSession';
10
8
  export { useCurrency } from './hooks/useCurrency';
11
9
  export { useCustomer } from './hooks/useCustomer';
12
10
  export { useEnvironment } from './hooks/useEnvironment';
13
11
  export { useLocale } from './hooks/useLocale';
14
- export { useAuth } from './hooks/useAuth';
15
- export { useAddress } from './hooks/useAddress';
12
+ export { useOffers } from './hooks/useOffers';
13
+ export { useOrderBump } from './hooks/useOrderBump';
14
+ export { usePostPurchases } from './hooks/usePostPurchases';
15
+ export { useProducts } from './hooks/useProducts';
16
+ export { useSession } from './hooks/useSession';
16
17
  export { useOrder } from './hooks/useOrder';
17
18
  export type { UseOrderOptions, UseOrderResult } from './hooks/useOrder';
18
19
  export { usePayment } from './hooks/usePayment';
19
20
  export { usePaymentPolling } from './hooks/usePaymentPolling';
20
21
  export { useThreeds } from './hooks/useThreeds';
21
22
  export { useThreedsModal } from './hooks/useThreedsModal';
22
- export type { Customer, Session, AuthState, Locale, Currency, Store, Environment, EnvironmentConfig, Order, OrderItem, OrderSummary, OrderAddress, PickupPoint, } from './types';
23
- export type { UseCheckoutOptions, UseCheckoutResult, CheckoutInitParams, CheckoutLineItem, CheckoutSession, CheckoutData, Promotion, } from './hooks/useCheckout';
24
- export type { UseOrderBumpOptions, UseOrderBumpResult, OrderBumpPreview } from './hooks/useOrderBump';
25
- export type { UseAddressOptions, UseAddressResult, AddressData, AddressField, Country, State, } from './hooks/useAddress';
26
- export type { Payment, PollingOptions, PaymentPollingHook } from './hooks/usePaymentPolling';
27
- export type { PaymentInstrument, ThreedsSession, ThreedsChallenge, ThreedsOptions, ThreedsHook, ThreedsProvider, } from './hooks/useThreeds';
28
- export type { ApplePayToken, CardPaymentMethod, PaymentResponse, PaymentOptions, PaymentInstrumentResponse, PaymentHook, } from './hooks/usePayment';
29
- export { formatMoney, formatMoneyWithoutSymbol, getCurrencyInfo, minorUnitsToMajorUnits, moneyStringOrNumberToMinorUnits, convertCurrency, formatSimpleMoney, } from './utils/money';
23
+ export type { AuthState, Currency, Customer, Environment, EnvironmentConfig, Locale, Order, OrderAddress, OrderItem, OrderSummary, PickupPoint, Session, Store, } from './types';
24
+ export type { CheckoutData, CheckoutInitParams, CheckoutLineItem, CheckoutSession, Promotion, UseCheckoutOptions, UseCheckoutResult, } from './hooks/useCheckout';
25
+ export type { OrderBumpPreview, UseOrderBumpOptions, UseOrderBumpResult } from './hooks/useOrderBump';
26
+ export type { PostPurchaseOffer, PostPurchaseOfferItem, PostPurchaseOfferLineItem, PostPurchaseOfferSummary, UsePostPurchasesOptions, UsePostPurchasesResult, } from './hooks/usePostPurchases';
27
+ export type { AddressData, AddressField, Country, State, UseAddressOptions, UseAddressResult, } from './hooks/useAddress';
28
+ export type { Payment, PaymentPollingHook, PollingOptions } from './hooks/usePaymentPolling';
29
+ export type { PaymentInstrument, ThreedsChallenge, ThreedsHook, ThreedsOptions, ThreedsProvider, ThreedsSession, } from './hooks/useThreeds';
30
+ export type { ApplePayToken, CardPaymentMethod, PaymentHook, PaymentInstrumentResponse, PaymentOptions, PaymentResponse, } from './hooks/usePayment';
31
+ export { convertCurrency, formatMoney, formatMoneyWithoutSymbol, formatSimpleMoney, getCurrencyInfo, minorUnitsToMajorUnits, moneyStringOrNumberToMinorUnits, } from './utils/money';
@@ -5,17 +5,18 @@
5
5
  // Provider exports
6
6
  export { TagadaProvider } from './providers/TagadaProvider';
7
7
  // Hook exports
8
+ export { useAddress } from './hooks/useAddress';
9
+ export { useAuth } from './hooks/useAuth';
8
10
  export { useCheckout } from './hooks/useCheckout';
9
- export { useProducts } from './hooks/useProducts';
10
- export { useOffers } from './hooks/useOffers';
11
- export { useOrderBump } from './hooks/useOrderBump';
12
- export { useSession } from './hooks/useSession';
13
11
  export { useCurrency } from './hooks/useCurrency';
14
12
  export { useCustomer } from './hooks/useCustomer';
15
13
  export { useEnvironment } from './hooks/useEnvironment';
16
14
  export { useLocale } from './hooks/useLocale';
17
- export { useAuth } from './hooks/useAuth';
18
- export { useAddress } from './hooks/useAddress';
15
+ export { useOffers } from './hooks/useOffers';
16
+ export { useOrderBump } from './hooks/useOrderBump';
17
+ export { usePostPurchases } from './hooks/usePostPurchases';
18
+ export { useProducts } from './hooks/useProducts';
19
+ export { useSession } from './hooks/useSession';
19
20
  // Order hook exports
20
21
  export { useOrder } from './hooks/useOrder';
21
22
  // Payment hooks exports
@@ -26,4 +27,4 @@ export { useThreedsModal } from './hooks/useThreedsModal';
26
27
  // Component exports (if any)
27
28
  // export { SomeComponent } from './components/SomeComponent';
28
29
  // Utility exports
29
- export { formatMoney, formatMoneyWithoutSymbol, getCurrencyInfo, minorUnitsToMajorUnits, moneyStringOrNumberToMinorUnits, convertCurrency, formatSimpleMoney, } from './utils/money';
30
+ export { convertCurrency, formatMoney, formatMoneyWithoutSymbol, formatSimpleMoney, getCurrencyInfo, minorUnitsToMajorUnits, moneyStringOrNumberToMinorUnits, } from './utils/money';
@@ -0,0 +1,24 @@
1
+ export interface TrackingData {
2
+ trackingCookiesData: Record<string, string>;
3
+ localStorageData: Record<string, string>;
4
+ }
5
+ /**
6
+ * Define pixel tracking cookie patterns for various platforms
7
+ */
8
+ export declare const trackingCookiePatterns: RegExp[];
9
+ /**
10
+ * Function to get cookies with retry logic
11
+ */
12
+ export declare const getCookiesWithRetry: (maxRetries?: number, delay?: number) => Promise<string[]>;
13
+ /**
14
+ * Collect localStorage data as dictionary
15
+ */
16
+ export declare const getLocalStorageData: () => Record<string, string>;
17
+ /**
18
+ * Collect tracking cookies data based on defined patterns
19
+ */
20
+ export declare const getTrackingCookiesData: () => Promise<Record<string, string>>;
21
+ /**
22
+ * Collect all tracking data (localStorage and cookies)
23
+ */
24
+ export declare const collectTrackingData: () => Promise<TrackingData>;
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Define pixel tracking cookie patterns for various platforms
3
+ */
4
+ export const trackingCookiePatterns = [
5
+ // Meta/Facebook pixels
6
+ /^_fbp/,
7
+ /^_fbc/,
8
+ /^fr$/,
9
+ /^_fbq/,
10
+ /^fbq/,
11
+ /^sb$/,
12
+ // Google Analytics & Ads
13
+ /^_ga/,
14
+ /^_gid/,
15
+ /^_gcl_au/,
16
+ /^_gac_/,
17
+ /^_gtag/,
18
+ /^_gat/,
19
+ /^_dc_gtm_/,
20
+ /^_gtm/,
21
+ // Google Ads
22
+ /^_gcl_/,
23
+ /^_gclid/,
24
+ /^_gclsrc/,
25
+ // Snapchat
26
+ /^_scid/,
27
+ /^_sctr/,
28
+ /^_schn/,
29
+ /^_scpx/,
30
+ // TikTok
31
+ /^_ttp/,
32
+ /^_tt_enable_cookie/,
33
+ /^_ttclid/,
34
+ /^_tta/,
35
+ // Pinterest
36
+ /^_pin/,
37
+ /^_pinterest_/,
38
+ /^_pinid/,
39
+ // Twitter/X
40
+ /^_twitter/,
41
+ /^_twid/,
42
+ /^muc_ads/,
43
+ // LinkedIn
44
+ /^_li/,
45
+ /^AnalyticsSyncHistory/,
46
+ /^bcookie/,
47
+ /^bscookie/,
48
+ // Microsoft/Bing
49
+ /^_uetsid/,
50
+ /^_uetvid/,
51
+ /^MUID/,
52
+ /^_msdcs/,
53
+ // Amazon
54
+ /^ad-id/,
55
+ /^ad-privacy/,
56
+ // CVG tracking
57
+ /^__cvg_uid/,
58
+ /^__cvg_sid/,
59
+ /^__cvg_session/,
60
+ // Shopify tracking
61
+ /^_shopify_y/,
62
+ /^_shopify_s/,
63
+ /^_shopify_ga/,
64
+ /^_shopify_ga_/,
65
+ /^_shopify_sa_p/,
66
+ /^_shopify_sa_t/,
67
+ // General tracking
68
+ /^_awc/,
69
+ /^_aw_/,
70
+ /^utm_/,
71
+ /^_clck/,
72
+ /^_clsk/,
73
+ ];
74
+ /**
75
+ * Function to get cookies with retry logic
76
+ */
77
+ export const getCookiesWithRetry = async (maxRetries = 3, delay = 100) => {
78
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
79
+ try {
80
+ const cookies = document.cookie.split('; ');
81
+ if (cookies.length > 0 && cookies[0] !== '') {
82
+ return cookies;
83
+ }
84
+ // If no cookies found, wait and retry
85
+ if (attempt < maxRetries) {
86
+ console.log(`Cookie collection attempt ${attempt} failed, retrying in ${delay}ms...`);
87
+ await new Promise((resolve) => setTimeout(resolve, delay));
88
+ }
89
+ }
90
+ catch (error) {
91
+ console.warn(`Cookie collection attempt ${attempt} failed:`, error);
92
+ if (attempt < maxRetries) {
93
+ await new Promise((resolve) => setTimeout(resolve, delay));
94
+ }
95
+ }
96
+ }
97
+ return [];
98
+ };
99
+ /**
100
+ * Collect localStorage data as dictionary
101
+ */
102
+ export const getLocalStorageData = () => {
103
+ const localStorageData = {};
104
+ try {
105
+ for (let i = 0; i < localStorage.length; i++) {
106
+ const key = localStorage.key(i);
107
+ if (key) {
108
+ localStorageData[key] = localStorage.getItem(key) || '';
109
+ }
110
+ }
111
+ }
112
+ catch (error) {
113
+ console.warn('Failed to read localStorage:', error);
114
+ }
115
+ return localStorageData;
116
+ };
117
+ /**
118
+ * Collect tracking cookies data based on defined patterns
119
+ */
120
+ export const getTrackingCookiesData = async () => {
121
+ const trackingCookiesData = {};
122
+ try {
123
+ // Get cookies with retry logic
124
+ const cookies = await getCookiesWithRetry();
125
+ if (cookies.length === 0) {
126
+ console.warn('No cookies found after retry attempts');
127
+ }
128
+ else {
129
+ console.log(`Successfully collected ${cookies.length} cookies`);
130
+ }
131
+ cookies.forEach((cookie) => {
132
+ const [key, ...valueParts] = cookie.split('=');
133
+ const value = valueParts.join('='); // Handle values that might contain =
134
+ if (key && trackingCookiePatterns.some((pattern) => pattern.test(key))) {
135
+ try {
136
+ trackingCookiesData[key] = decodeURIComponent(value || '');
137
+ }
138
+ catch (error) {
139
+ // If decoding fails, use raw value
140
+ trackingCookiesData[key] = value || '';
141
+ }
142
+ }
143
+ });
144
+ // Log specific cookies we're looking for
145
+ const importantCookies = ['_shopify_y', '__cvg_uid', '_fbp', '_ga'];
146
+ importantCookies.forEach((cookieName) => {
147
+ if (trackingCookiesData[cookieName]) {
148
+ console.log(`Found ${cookieName}:`, trackingCookiesData[cookieName]);
149
+ }
150
+ else {
151
+ console.log(`Missing ${cookieName} cookie`);
152
+ }
153
+ });
154
+ }
155
+ catch (error) {
156
+ console.warn('Failed to read tracking cookies:', error);
157
+ }
158
+ return trackingCookiesData;
159
+ };
160
+ /**
161
+ * Collect all tracking data (localStorage and cookies)
162
+ */
163
+ export const collectTrackingData = async () => {
164
+ const [localStorageData, trackingCookiesData] = await Promise.all([
165
+ Promise.resolve(getLocalStorageData()),
166
+ getTrackingCookiesData(),
167
+ ]);
168
+ return {
169
+ localStorageData,
170
+ trackingCookiesData,
171
+ };
172
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tagadapay/plugin-sdk",
3
- "version": "1.0.25",
3
+ "version": "1.0.27",
4
4
  "description": "Modern React SDK for building Tagada Pay plugins",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",