@tagadapay/plugin-sdk 3.1.5 → 3.1.8

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 (53) hide show
  1. package/dist/external-tracker.js +1104 -491
  2. package/dist/external-tracker.min.js +2 -2
  3. package/dist/external-tracker.min.js.map +4 -4
  4. package/dist/react/hooks/useApplePay.js +25 -36
  5. package/dist/react/hooks/usePaymentPolling.d.ts +9 -3
  6. package/dist/react/utils/money.d.ts +4 -3
  7. package/dist/react/utils/money.js +39 -6
  8. package/dist/react/utils/trackingUtils.js +1 -0
  9. package/dist/v2/core/client.js +34 -2
  10. package/dist/v2/core/config/environment.js +9 -2
  11. package/dist/v2/core/funnelClient.d.ts +92 -1
  12. package/dist/v2/core/funnelClient.js +247 -3
  13. package/dist/v2/core/resources/apiClient.js +1 -1
  14. package/dist/v2/core/resources/checkout.d.ts +68 -0
  15. package/dist/v2/core/resources/funnel.d.ts +15 -0
  16. package/dist/v2/core/resources/payments.d.ts +50 -3
  17. package/dist/v2/core/resources/payments.js +38 -7
  18. package/dist/v2/core/utils/pluginConfig.js +40 -5
  19. package/dist/v2/core/utils/previewMode.d.ts +3 -0
  20. package/dist/v2/core/utils/previewMode.js +44 -14
  21. package/dist/v2/core/utils/previewModeIndicator.d.ts +19 -0
  22. package/dist/v2/core/utils/previewModeIndicator.js +414 -0
  23. package/dist/v2/core/utils/tokenStorage.d.ts +4 -0
  24. package/dist/v2/core/utils/tokenStorage.js +15 -1
  25. package/dist/v2/index.d.ts +6 -1
  26. package/dist/v2/index.js +6 -1
  27. package/dist/v2/react/components/ApplePayButton.d.ts +21 -121
  28. package/dist/v2/react/components/ApplePayButton.js +221 -290
  29. package/dist/v2/react/components/FunnelScriptInjector.d.ts +3 -1
  30. package/dist/v2/react/components/FunnelScriptInjector.js +107 -3
  31. package/dist/v2/react/components/PreviewModeIndicator.d.ts +46 -0
  32. package/dist/v2/react/components/PreviewModeIndicator.js +113 -0
  33. package/dist/v2/react/hooks/useApplePayCheckout.d.ts +16 -0
  34. package/dist/v2/react/hooks/useApplePayCheckout.js +193 -0
  35. package/dist/v2/react/hooks/useFunnel.d.ts +42 -6
  36. package/dist/v2/react/hooks/useFunnel.js +25 -5
  37. package/dist/v2/react/hooks/usePaymentPolling.d.ts +9 -3
  38. package/dist/v2/react/hooks/usePaymentPolling.js +31 -9
  39. package/dist/v2/react/hooks/usePaymentQuery.d.ts +32 -2
  40. package/dist/v2/react/hooks/usePaymentQuery.js +304 -7
  41. package/dist/v2/react/hooks/usePaymentRetrieve.d.ts +26 -0
  42. package/dist/v2/react/hooks/usePaymentRetrieve.js +175 -0
  43. package/dist/v2/react/hooks/useStepConfig.d.ts +62 -0
  44. package/dist/v2/react/hooks/useStepConfig.js +52 -0
  45. package/dist/v2/react/index.d.ts +9 -3
  46. package/dist/v2/react/index.js +5 -1
  47. package/dist/v2/react/providers/ExpressPaymentMethodsProvider.js +27 -19
  48. package/dist/v2/react/providers/TagadaProvider.js +2 -2
  49. package/dist/v2/standalone/external-tracker.d.ts +2 -0
  50. package/dist/v2/standalone/external-tracker.js +6 -3
  51. package/package.json +1 -1
  52. package/dist/v2/react/hooks/useApplePay.d.ts +0 -16
  53. package/dist/v2/react/hooks/useApplePay.js +0 -247
@@ -1,247 +0,0 @@
1
- /**
2
- * Apple Pay Hook for v2 Architecture
3
- * Handles Apple Pay payment flow with Basis Theory integration
4
- */
5
- import { useState, useCallback, useEffect } from 'react';
6
- import { getBasisTheoryApiKey } from '../../../react/config/payment';
7
- import { minorUnitsToMajorUnits, getCurrencyInfo } from '../../../react/utils/money';
8
- import { useCheckoutQuery } from './useCheckoutQuery';
9
- import { usePaymentQuery } from './usePaymentQuery';
10
- import { PaymentsResource } from '../../core/resources/payments';
11
- import { OrdersResource } from '../../core/resources/orders';
12
- import { getGlobalApiClient } from './useApiQuery';
13
- export function useApplePay(options = {}) {
14
- const [processingPayment, setProcessingPayment] = useState(false);
15
- const [error, setError] = useState(null);
16
- const [isAvailable, setIsAvailable] = useState(false);
17
- const { checkout } = useCheckoutQuery();
18
- const { createApplePayPaymentInstrument } = usePaymentQuery();
19
- const checkoutSessionId = checkout?.checkoutSession?.id;
20
- const store = checkout?.checkoutSession?.store;
21
- const summary = checkout?.summary;
22
- const basistheoryPublicKey = getBasisTheoryApiKey();
23
- // Create SDK resource clients
24
- const paymentsResource = new PaymentsResource(getGlobalApiClient());
25
- const ordersResource = new OrdersResource(getGlobalApiClient());
26
- // Helper to convert minor units to currency string for Apple Pay
27
- const minorUnitsToCurrencyString = useCallback((amountMinor, currency) => {
28
- if (!amountMinor || !currency)
29
- return '0.00';
30
- const currencyInfo = getCurrencyInfo(currency);
31
- if (!currencyInfo) {
32
- console.warn(`Currency info not found for ${currency}, using fallback`);
33
- return (amountMinor / 100).toFixed(2);
34
- }
35
- const majorUnits = minorUnitsToMajorUnits(amountMinor, currency);
36
- return majorUnits.toFixed(currencyInfo.ISOdigits);
37
- }, []);
38
- // Check Apple Pay availability on mount
39
- useEffect(() => {
40
- const checkApplePayAvailability = () => {
41
- if (typeof window === 'undefined' || !window.ApplePaySession) {
42
- setIsAvailable(false);
43
- return;
44
- }
45
- try {
46
- const canMakePayments = window.ApplePaySession.canMakePayments();
47
- setIsAvailable(canMakePayments);
48
- }
49
- catch (error) {
50
- console.error('Error checking Apple Pay availability:', error);
51
- setIsAvailable(false);
52
- }
53
- };
54
- checkApplePayAvailability();
55
- }, []);
56
- // Validate merchant with Basis Theory
57
- const validateMerchant = useCallback(async () => {
58
- try {
59
- const response = await fetch('https://api.basistheory.com/apple-pay/session', {
60
- method: 'POST',
61
- headers: {
62
- 'Content-Type': 'application/json',
63
- 'BT-API-KEY': basistheoryPublicKey,
64
- },
65
- body: JSON.stringify({
66
- display_name: store?.name || 'Store',
67
- domain: window.location.host,
68
- }),
69
- });
70
- if (!response.ok) {
71
- throw new Error(`HTTP error! Status: ${response.status}`);
72
- }
73
- return response.json();
74
- }
75
- catch (err) {
76
- console.error('Merchant validation failed:', err);
77
- throw err;
78
- }
79
- }, [basistheoryPublicKey, store?.name]);
80
- // Tokenize Apple Pay payment with Basis Theory
81
- const tokenizeApplePay = useCallback(async (event) => {
82
- try {
83
- const response = await fetch('https://api.basistheory.com/apple-pay', {
84
- method: 'POST',
85
- headers: {
86
- 'Content-Type': 'application/json',
87
- 'BT-API-KEY': basistheoryPublicKey,
88
- },
89
- body: JSON.stringify({
90
- apple_payment_data: event.payment.token,
91
- }),
92
- });
93
- if (!response.ok) {
94
- setError('Payment Failed');
95
- throw new Error(`HTTP error! Status: ${response.status}`);
96
- }
97
- const result = await response.json();
98
- return result.apple_pay; // Basis Theory returns the Apple Pay token in the apple_pay field
99
- }
100
- catch (error) {
101
- console.error('Tokenization failed:', error);
102
- throw error;
103
- }
104
- }, [basistheoryPublicKey]);
105
- // Charge payment using SDK methods
106
- const chargePayment = useCallback(async (applePayToken) => {
107
- if (!checkoutSessionId) {
108
- throw new Error('Checkout session ID not available');
109
- }
110
- setProcessingPayment(true);
111
- try {
112
- // 1. Tokenize with Basis Theory (already done - we have applePayToken)
113
- // 2. Create payment instrument from the tokenized Apple Pay payment
114
- const paymentInstrumentData = {
115
- type: 'apple_pay',
116
- token: applePayToken.id,
117
- dpanType: applePayToken.type,
118
- card: {
119
- bin: applePayToken.card.bin,
120
- last4: applePayToken.card.last4,
121
- expirationMonth: applePayToken.card.expiration_month,
122
- expirationYear: applePayToken.card.expiration_year,
123
- brand: applePayToken.card.brand,
124
- },
125
- };
126
- const paymentInstrument = await paymentsResource.createPaymentInstrument(paymentInstrumentData);
127
- if (!paymentInstrument?.id) {
128
- throw new Error('Failed to create payment instrument');
129
- }
130
- // 3. Create order from checkout session
131
- const orderResponse = await ordersResource.createOrder(checkoutSessionId);
132
- if (!orderResponse?.success || !orderResponse?.order?.id) {
133
- throw new Error('Failed to create order');
134
- }
135
- // 4. Process payment
136
- const paymentResult = await paymentsResource.processPaymentDirect(checkoutSessionId, paymentInstrument.id, undefined, {
137
- initiatedBy: 'customer',
138
- source: 'checkout',
139
- });
140
- if (options.onSuccess) {
141
- options.onSuccess(paymentResult);
142
- }
143
- return paymentResult;
144
- }
145
- catch (error) {
146
- console.error('Payment failed:', error);
147
- const errorMessage = error instanceof Error ? error.message : 'Payment Failed';
148
- setError(errorMessage);
149
- if (options.onError) {
150
- options.onError(errorMessage);
151
- }
152
- throw error;
153
- }
154
- finally {
155
- setProcessingPayment(false);
156
- }
157
- }, [checkoutSessionId, paymentsResource, ordersResource, options]);
158
- // Handle Apple Pay button click - opens Apple Pay sheet
159
- const handleApplePayClick = useCallback(() => {
160
- if (!summary || !store) {
161
- console.error('Order summary or store not available');
162
- return;
163
- }
164
- const total = {
165
- label: store.name || 'Store',
166
- amount: minorUnitsToCurrencyString(summary.totalAdjustedAmount, summary.currency),
167
- type: 'final',
168
- };
169
- const lineItems = [
170
- {
171
- label: 'Subtotal',
172
- amount: minorUnitsToCurrencyString(summary.subtotalAdjustedAmount, summary.currency),
173
- type: 'final',
174
- },
175
- {
176
- label: 'Shipping',
177
- amount: minorUnitsToCurrencyString(summary.shippingCost ?? 0, summary.currency),
178
- type: 'final',
179
- },
180
- {
181
- label: 'Tax',
182
- amount: minorUnitsToCurrencyString(summary.totalTaxAmount, summary.currency),
183
- type: 'final',
184
- },
185
- ];
186
- const request = {
187
- countryCode: 'US', // TODO: Get from checkout session metadata
188
- currencyCode: summary.currency,
189
- supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
190
- merchantCapabilities: ['supports3DS'],
191
- total,
192
- lineItems,
193
- };
194
- try {
195
- const session = new ApplePaySession(3, request);
196
- session.onvalidatemerchant = (event) => {
197
- void (async () => {
198
- try {
199
- console.log('Merchant validation requested for:', event.validationURL);
200
- const merchantSession = await validateMerchant();
201
- session.completeMerchantValidation(merchantSession);
202
- }
203
- catch (error) {
204
- console.error('Merchant validation failed:', error);
205
- session.abort();
206
- }
207
- })();
208
- };
209
- session.onpaymentauthorized = (event) => {
210
- void (async () => {
211
- try {
212
- const applePayToken = await tokenizeApplePay(event);
213
- session.completePayment(ApplePaySession.STATUS_SUCCESS);
214
- await chargePayment(applePayToken);
215
- }
216
- catch (error) {
217
- console.error('Payment processing failed:', error);
218
- session.completePayment(ApplePaySession.STATUS_FAILURE);
219
- }
220
- })();
221
- };
222
- session.onerror = (event) => {
223
- console.error('Apple Pay Session Error:', event);
224
- };
225
- session.oncancel = () => {
226
- console.log('Payment cancelled by user');
227
- if (options.onCancel) {
228
- options.onCancel();
229
- }
230
- };
231
- session.begin();
232
- }
233
- catch (error) {
234
- console.error('Failed to start Apple Pay session:', error);
235
- setError('Failed to start Apple Pay session');
236
- if (options.onError) {
237
- options.onError('Failed to start Apple Pay session');
238
- }
239
- }
240
- }, [summary, store, minorUnitsToCurrencyString, validateMerchant, tokenizeApplePay, chargePayment, options]);
241
- return {
242
- handleApplePayClick,
243
- processingPayment,
244
- applePayError: error,
245
- isAvailable,
246
- };
247
- }