-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathcheckout-main.tsx
More file actions
1035 lines (961 loc) · 36 KB
/
Copy pathcheckout-main.tsx
File metadata and controls
1035 lines (961 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useStripe } from '@automattic/calypso-stripe';
import colorStudio from '@automattic/color-studio';
import { CheckoutProvider, checkoutTheme } from '@automattic/composite-checkout';
import { Step } from '@automattic/onboarding';
import { useShoppingCart } from '@automattic/shopping-cart';
import {
isValueTruthy,
getContactDetailsType,
filterAppropriatePaymentMethods,
translateCheckoutPaymentMethodToWpcomPaymentMethod,
translateCheckoutPaymentMethodToTracksPaymentMethod,
} from '@automattic/wpcom-checkout';
import { VGSCollectProvider } from '@vgs/collect-js-react';
import { useSelect } from '@wordpress/data';
import debugFactory from 'debug';
import DOMPurify from 'dompurify';
import { useTranslate } from 'i18n-calypso';
import { useCallback, useMemo } from 'react';
import { getDashboardFromHostname } from 'calypso/dashboard/app/routing';
import { getDashboardStepperLogo } from 'calypso/dashboard/app/stepper-logo';
import { useCheckoutMigrationIntroductoryOfferSticker } from 'calypso/data/site-migration/use-checkout-migration-introductory-offer-sticker';
import { recordAddEvent } from 'calypso/lib/analytics/cart';
import PageViewTracker from 'calypso/lib/analytics/page-view-tracker';
import useSiteDomains from 'calypso/my-sites/checkout/src/hooks/use-site-domains';
import useCartKey from 'calypso/my-sites/checkout/use-cart-key';
import { useSelector, useDispatch } from 'calypso/state';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { errorNotice, infoNotice } from 'calypso/state/notices/actions';
import hasGravatarDomainQueryParam from 'calypso/state/selectors/has-gravatar-domain-query-param';
import isPrivateSite from 'calypso/state/selectors/is-private-site';
import isAtomicSite from 'calypso/state/selectors/is-site-automated-transfer';
import { isJetpackSite, isCommerceGardenSite } from 'calypso/state/sites/selectors';
import useActOnceOnStrings from '../hooks/use-act-once-on-strings';
import useAddProductsFromUrl from '../hooks/use-add-products-from-url';
import useCheckoutFlowTrackKey from '../hooks/use-checkout-flow-track-key';
import { useCheckoutUiRedesignExperiment } from '../hooks/use-checkout-ui-redesign-experiment';
import useCountryList from '../hooks/use-country-list';
import useCreatePaymentMethods from '../hooks/use-create-payment-methods';
import { existingCardPrefix } from '../hooks/use-create-payment-methods/use-create-existing-cards';
import { existingPayPalPPCPPrefix } from '../hooks/use-create-payment-methods/use-create-existing-paypal-ppcp';
import useCreatePaymentSubmittedAndProcessingCallback from '../hooks/use-create-payment-submitted-and-processing-callback';
import useDetectedCountryCode from '../hooks/use-detected-country-code';
import useGetThankYouUrl from '../hooks/use-get-thank-you-url';
import { useMobileCheckoutStickySummaryExperiment } from '../hooks/use-mobile-checkout-sticky-summary-experiment';
import usePrepareProductsForCart from '../hooks/use-prepare-products-for-cart';
import useRecordCartLoaded from '../hooks/use-record-cart-loaded';
import useRecordCheckoutLoaded from '../hooks/use-record-checkout-loaded';
import useRemoveFromCartAndRedirect from '../hooks/use-remove-from-cart-and-redirect';
import { useStoredPaymentMethods } from '../hooks/use-stored-payment-methods';
import { logStashLoadErrorEvent, logStashEvent, convertErrorToString } from '../lib/analytics';
import blikProcessor from '../lib/blik-processor';
import existingCardProcessor from '../lib/existing-card-processor';
import existingPayPalPPCPProcessor from '../lib/existing-paypal-ppcp-processor';
import freePurchaseProcessor from '../lib/free-purchase-processor';
import genericRedirectProcessor from '../lib/generic-redirect-processor';
import multiPartnerCardProcessor from '../lib/multi-partner-card-processor';
import payPalProcessor from '../lib/paypal-express-processor';
import { payPalJsProcessor } from '../lib/paypal-js-processor';
import { pixAutomaticoProcessor } from '../lib/pix-automatico-processor';
import { pixProcessor } from '../lib/pix-processor';
import stripeWalletProcessor from '../lib/stripe-wallet-processor';
import { translateResponseCartToWPCOMCart } from '../lib/translate-cart';
import upiProcessor from '../lib/upi-processor';
import weChatProcessor from '../lib/we-chat-processor';
import webPayProcessor from '../lib/web-pay-processor';
import { CHECKOUT_STORE } from '../lib/wpcom-store';
import { CheckoutLoadingPlaceholder } from './checkout-loading-placeholder';
import CheckoutMainContent from './checkout-main-content';
import { OnChangeItemVariant } from './item-variation-picker';
import JetpackProRedirectModal from './jetpack-pro-redirect-modal';
import PrePurchaseNotices from './prepurchase-notices';
import type { PaymentProcessorOptions } from '../types/payment-processors';
import type {
CheckoutPageErrorCallback,
PaymentEventCallbackArguments,
PaymentMethod,
} from '@automattic/composite-checkout';
import type { MinimalRequestCartProduct, ResponseCart } from '@automattic/shopping-cart';
import type { CheckoutPaymentMethodSlug, SitelessCheckoutType } from '@automattic/wpcom-checkout';
const { colors } = colorStudio;
const debug = debugFactory( 'calypso:checkout-main' );
export interface CheckoutMainProps {
siteSlug: string | undefined;
siteId: number | undefined;
productAliasFromUrl?: string | undefined;
productSourceFromUrl?: string;
redirectTo?: string | undefined;
feature?: string | undefined;
plan?: string | undefined;
purchaseId?: number | string | undefined;
couponCode?: string | undefined;
isComingFromUpsell?: boolean;
isLoggedOutCart?: boolean;
isNoSiteCart?: boolean;
isGiftPurchase?: boolean;
disabledThankYouPage?: boolean;
sitelessCheckoutType?: SitelessCheckoutType;
akismetSiteSlug?: string;
marketplaceSiteSlug?: string;
jetpackSiteSlug?: string;
jetpackPurchaseToken?: string;
isUserComingFromLoginForm?: boolean;
customizedPreviousPath?: string;
connectAfterCheckout?: boolean;
/**
* `fromSiteSlug` is the Jetpack site slug passed from the site via url query arg (into
* checkout), for use cases when the site slug cannot be retrieved from state, ie- when there
* is not a site in context, such as in siteless checkout. As opposed to `siteSlug` which is
* the site slug present when the site is in context (ie- when site is connected and user is
* logged in).
*/
fromSiteSlug?: string;
adminUrl?: string;
hostingIntent?: string | undefined;
}
export default function CheckoutMain( {
siteSlug,
siteId,
productAliasFromUrl,
productSourceFromUrl,
redirectTo,
feature,
plan,
purchaseId,
couponCode: couponCodeFromUrl,
isComingFromUpsell,
isLoggedOutCart,
isNoSiteCart,
isGiftPurchase,
disabledThankYouPage,
sitelessCheckoutType,
akismetSiteSlug,
marketplaceSiteSlug,
jetpackSiteSlug,
jetpackPurchaseToken,
isUserComingFromLoginForm,
customizedPreviousPath,
connectAfterCheckout,
fromSiteSlug,
adminUrl,
hostingIntent,
}: CheckoutMainProps ) {
const translate = useTranslate();
const isJetpackNotAtomic =
useSelector( ( state ) => {
const isCommerce = siteId && isCommerceGardenSite( state, siteId );
return (
siteId && isJetpackSite( state, siteId ) && ! isAtomicSite( state, siteId ) && ! isCommerce
);
} ) || sitelessCheckoutType === 'jetpack';
const isPrivate = useSelector( ( state ) => siteId && isPrivateSite( state, siteId ) ) || false;
const isGravatarDomain = useSelector( hasGravatarDomainQueryParam );
const cartKey = useCartKey();
/**
* The definition of what makes "siteless checkout" varies considerably.
*
* All subscriptions must be assigned to a user and a site before or during
* their purchase, but which site is used and when that site is created
* differentiates the flows.
*
* If `sitelessCheckoutType` is set, then this checkout is siteless, which
* also means that the shopping cart has no `blog_id` set. However,
* sometimes a `blog_id` will be set automatically on the server by the
* shopping cart (for example, if the cart item is a renewal and the site
* has not already been provided in the checkout URL).
*
* Unified siteless checkout (siteless checkout for wpcom products) creates
* one site per purchase. Jetpack siteless checkout and Domain-only flows
* have a holding site created during the transactions endpoint, one per
* purchase (although the created sites are flagged in special ways).
*
* The same is true for Akismet, A4A, and Marketplace siteless checkout but
* for these we only create one holding site per user and that is re-used
* for additional purchases.
*
* Gift purchases (renewals for another user's subscription) are also
* siteless in the sense that no `blog_id` is set when they are in the
* cart, but they are renewing a subscription on an existing site.
*
* Logged-out siteless checkout flows include a temporary userless and
* siteless cart but then create a user just in time before the transaction
* is submitted, and therefore their carts always have a user by the time
* they are processed. Sometimes a site is also created when the user is
* created (this happens if createUserAndSiteBeforeTransaction is true AND
* newSiteParams is set in the createAccount helper) in which case the
* transaction is also submitted with a `blog_id` and no site is created
* during the transaction itself.
*/
const createUserAndSiteBeforeTransaction = ( () => {
if ( sitelessCheckoutType && cartKey === 'no-user' ) {
return true;
}
return false;
} )();
const { stripe, stripeConfiguration, isStripeLoading, stripeLoadingError } = useStripe();
const reduxDispatch = useDispatch();
const updatedSiteSlug = useMemo( () => {
if ( sitelessCheckoutType === 'jetpack' ) {
return jetpackSiteSlug;
}
// Currently, the `akismetSiteSlug` prop is not being passed to this component anywhere
// We are not doing any site specific things with akismet checkout, so this should always be undefined for now
// If this was not here to return `undefined`, the akismet routes would get messed with due to `siteSlug` returning "no-user" in akismet siteless checkout
if ( sitelessCheckoutType === 'akismet' ) {
return akismetSiteSlug;
}
if ( sitelessCheckoutType === 'marketplace' ) {
return marketplaceSiteSlug;
}
// Onboarding unified siteless checkout should return undefined to avoid using siteSlug which becomes "no-user"
if ( sitelessCheckoutType === 'unified' ) {
return undefined;
}
return siteSlug;
}, [ akismetSiteSlug, jetpackSiteSlug, marketplaceSiteSlug, sitelessCheckoutType, siteSlug ] );
const showErrorMessageBriefly = useCallback(
( error: string ) => {
debug( 'error', error );
const message = error && error.toString ? error.toString() : error;
reduxDispatch(
errorNotice( message || translate( 'An error occurred during your purchase.' ), {
duration: 5000,
} )
);
},
[ reduxDispatch, translate ]
);
const checkoutFlow = useCheckoutFlowTrackKey( {
hasJetpackSiteSlug: !! jetpackSiteSlug,
sitelessCheckoutType,
isJetpackNotAtomic,
isLoggedOutCart,
isUserComingFromLoginForm,
} );
const countriesList = useCountryList();
const {
productsForCart,
isLoading: areCartProductsPreparing,
error: cartProductPrepError,
addingRenewals,
} = usePrepareProductsForCart( {
productAliasFromUrl,
purchaseId,
usesJetpackProducts: isJetpackNotAtomic,
isPrivate,
siteSlug: updatedSiteSlug,
sitelessCheckoutType,
isLoggedOutCart,
isNoSiteCart,
jetpackSiteSlug,
jetpackPurchaseToken,
source: productSourceFromUrl,
isGiftPurchase,
hostingIntent,
} );
const {
applyCoupon,
replaceProductInCart,
isLoading: isLoadingCart,
isPendingUpdate: isCartPendingUpdate,
responseCart,
loadingError: cartLoadingError,
loadingErrorType: cartLoadingErrorType,
addProductsToCart,
reloadFromServer,
} = useShoppingCart( cartKey );
const { shouldSetMigrationSticker, isLoading: isStickerLoading } =
useCheckoutMigrationIntroductoryOfferSticker( siteId, reloadFromServer );
// For siteless checkouts, possibly get the blog ID from the cart response
// in cases where the server has assigned it automatically. If so, we
// override the blog ID set in the checkout URL (if any).
const updatedSiteId = sitelessCheckoutType
? parseInt( String( responseCart.blog_id ), 10 )
: siteId;
const isInitialCartLoading = useAddProductsFromUrl( {
isLoadingCart,
isCartPendingUpdate,
productsForCart,
areCartProductsPreparing,
couponCodeFromUrl,
applyCoupon,
addProductsToCart,
addingRenewals,
} );
useRecordCartLoaded( {
responseCart,
productsForCart,
isInitialCartLoading,
} );
const { allowedPaymentMethods } = useMemo(
() => translateResponseCartToWPCOMCart( responseCart ),
[ responseCart ]
);
const domains = useSiteDomains( siteId );
// IMPORTANT NOTE: This will be called BEFORE checkout completes because of
// redirect payment methods like PayPal. They will redirect directly to the
// post-checkout page decided by `getThankYouUrl` and therefore must be
// passed the post-checkout URL before the transaction begins.
const getThankYouUrlBase = useGetThankYouUrl( {
siteSlug: updatedSiteSlug,
redirectTo,
purchaseId,
feature,
cart: responseCart,
isJetpackNotAtomic,
productAliasFromUrl,
hideNudge: !! isComingFromUpsell,
sitelessCheckoutType,
domains,
connectAfterCheckout,
adminUrl,
fromSiteSlug,
isGravatarDomain,
} );
const getThankYouUrl = useCallback( () => {
const url = getThankYouUrlBase();
logStashEvent( 'thank you url generated', { url }, 'info' );
return url;
}, [ getThankYouUrlBase ] );
const contactDetailsType = getContactDetailsType( responseCart );
useDetectedCountryCode();
// Record errors adding products to the cart
useActOnceOnStrings( [ cartProductPrepError ].filter( isValueTruthy ), ( messages ) => {
messages.forEach( ( message ) => {
logStashEvent( 'calypso_composite_checkout_products_load_error', {
error_message: String( message ),
} );
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_products_load_error', {
error_message: String( message ),
} )
);
} );
} );
useActOnceOnStrings( [ cartLoadingError ].filter( isValueTruthy ), ( messages ) => {
messages.forEach( ( message ) => {
logStashEvent( 'calypso_checkout_composite_cart_error', {
type: cartLoadingErrorType ?? '',
message,
} );
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_cart_error', {
error_type: cartLoadingErrorType,
error_message: String( message ),
} )
);
} );
} );
// Display errors. Note that we display all errors if any of them change,
// because errorNotice() otherwise will remove the previously displayed
// errors.
const errorsToDisplay = [
cartLoadingError,
stripeLoadingError?.message,
cartProductPrepError,
].filter( isValueTruthy );
useActOnceOnStrings( errorsToDisplay, () => {
reduxDispatch(
errorNotice( errorsToDisplay.map( ( message ) => <p key={ message }>{ message }</p> ) )
);
} );
const responseCartErrors = responseCart.messages?.errors ?? [];
const areThereErrors =
[ ...responseCartErrors, cartLoadingError, cartProductPrepError ].filter( isValueTruthy )
.length > 0;
const { isRemovingProductFromCart, removeProductFromCartAndMaybeRedirect } =
useRemoveFromCartAndRedirect(
updatedSiteSlug,
createUserAndSiteBeforeTransaction,
customizedPreviousPath
);
const isForBusiness = responseCart?.tax?.location?.is_for_business ?? false;
const {
paymentMethods: storedCards,
isLoading: isLoadingStoredCards,
error: storedCardsError,
} = useStoredPaymentMethods( {
isLoggedOut: isLoggedOutCart,
type: 'all',
isForBusiness,
} );
// If tax_location->is_for_business is set to true, then only business
// cards will show in Checkout. We should announce this filtering to the
// user which these variables will do.
const areStoredCardsFiltered = isForBusiness;
const isBusinessCardsFilterEmpty = isForBusiness && storedCards.length ? false : true;
useActOnceOnStrings( [ storedCardsError ].filter( isValueTruthy ), ( messages ) => {
messages.forEach( ( message ) => {
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_stored_card_error', {
error_message: String( message ),
} )
);
} );
} );
const currentTaxCountryCode = responseCart.tax.location.country_code;
const paymentMethodObjects = useCreatePaymentMethods( {
contactDetailsType,
currentTaxCountryCode,
isStripeLoading,
stripeLoadingError,
stripeConfiguration,
stripe,
storedCards,
} );
debug( 'created payment method objects', paymentMethodObjects );
// Once we pass paymentMethods into CheckoutMain, we should try to avoid
// changing them because it can cause awkward UX. Here we try to wait for
// them to be all finished loading before we pass them along.
const arePaymentMethodsLoading =
responseCart.products.length < 1 ||
isInitialCartLoading ||
// Only wait for stored cards to load if we are using cards
( allowedPaymentMethods.includes( 'card' ) && isLoadingStoredCards );
const contactDetails = useSelect( ( select ) => select( CHECKOUT_STORE ).getContactInfo(), [] );
const recaptchaClientId = useSelect(
( select ) => select( CHECKOUT_STORE ).getRecaptchaClientId(),
[]
);
const paymentMethods = arePaymentMethodsLoading
? []
: filterAppropriatePaymentMethods( {
paymentMethodObjects,
allowedPaymentMethods,
} );
debug( 'filtered payment method objects', paymentMethods );
const { analyticsPath, analyticsProps } = getAnalyticsPath(
purchaseId,
productAliasFromUrl,
updatedSiteSlug,
feature,
plan,
sitelessCheckoutType,
checkoutFlow
);
const changeSelection = useCallback< OnChangeItemVariant >(
( uuidToReplace, newProductSlug, newProductId, newProductVolume ) => {
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_plan_length_change', {
new_product_slug: newProductSlug,
volume: newProductVolume,
} )
);
replaceProductInCart( uuidToReplace, {
product_slug: newProductSlug,
product_id: newProductId,
// Since volume is optional, only add it if it's defined
...( newProductVolume && { volume: newProductVolume } ),
} ).catch( () => {
// Nothing needs to be done here. CartMessages will display the error to the user.
} );
},
[ reduxDispatch, replaceProductInCart ]
);
const addItemAndLog: ( item: MinimalRequestCartProduct ) => void = useCallback(
( cartItem ) => {
try {
recordAddEvent( cartItem );
} catch ( error ) {
logStashEvent( 'checkout_add_product_analytics_error', {
error: String( error ),
} );
}
addProductsToCart( [ cartItem ] ).catch( () => {
// Nothing needs to be done here. CartMessages will display the error to the user.
} );
},
[ addProductsToCart ]
);
const isAkismetSitelessCheckout = responseCart.products.some(
( product ) => product.extra.isAkismetSitelessCheckout
);
const includeDomainDetails = contactDetailsType === 'domain';
const includeGSuiteDetails = contactDetailsType === 'gsuite';
const dataForProcessor: PaymentProcessorOptions = useMemo(
() => ( {
contactDetails,
createUserAndSiteBeforeTransaction,
getThankYouUrl,
includeDomainDetails,
includeGSuiteDetails,
reduxDispatch,
responseCart,
siteId: updatedSiteId,
siteSlug: updatedSiteSlug,
stripeConfiguration,
stripe,
recaptchaClientId,
fromSiteSlug,
isJetpackNotAtomic,
isAkismetSitelessCheckout,
} ),
[
contactDetails,
createUserAndSiteBeforeTransaction,
getThankYouUrl,
includeDomainDetails,
includeGSuiteDetails,
reduxDispatch,
responseCart,
updatedSiteId,
stripe,
stripeConfiguration,
updatedSiteSlug,
recaptchaClientId,
fromSiteSlug,
isJetpackNotAtomic,
isAkismetSitelessCheckout,
]
);
const paymentProcessors = useMemo(
() => ( {
'apple-pay': ( transactionData: unknown ) =>
webPayProcessor( 'apple-pay', transactionData, dataForProcessor ),
'google-pay': ( transactionData: unknown ) =>
webPayProcessor( 'google-pay', transactionData, dataForProcessor ),
'free-purchase': () => freePurchaseProcessor( dataForProcessor ),
card: ( transactionData: unknown ) =>
multiPartnerCardProcessor( transactionData, dataForProcessor, {
translate,
} ),
pix: ( transactionData: unknown ) =>
pixProcessor( transactionData, dataForProcessor, translate ),
pix_automatico: ( transactionData: unknown ) =>
pixAutomaticoProcessor( transactionData, dataForProcessor, translate ),
alipay: ( transactionData: unknown ) =>
genericRedirectProcessor( 'alipay', transactionData, dataForProcessor ),
p24: ( transactionData: unknown ) =>
genericRedirectProcessor( 'p24', transactionData, dataForProcessor ),
bancontact: ( transactionData: unknown ) =>
genericRedirectProcessor( 'bancontact', transactionData, dataForProcessor ),
wechat: ( transactionData: unknown ) =>
weChatProcessor( transactionData, dataForProcessor, translate ),
ideal: ( transactionData: unknown ) =>
genericRedirectProcessor( 'ideal', transactionData, dataForProcessor ),
sofort: ( transactionData: unknown ) =>
genericRedirectProcessor( 'sofort', transactionData, dataForProcessor ),
eps: ( transactionData: unknown ) =>
genericRedirectProcessor( 'eps', transactionData, dataForProcessor ),
'stripe-upi': ( transactionData: unknown ) =>
upiProcessor(
transactionData,
dataForProcessor,
translate,
sitelessCheckoutType === 'a4a'
),
'stripe-blik': ( transactionData: unknown ) =>
blikProcessor( transactionData, dataForProcessor, translate ),
'stripe-wallet': ( transactionData: unknown ) =>
stripeWalletProcessor( transactionData, dataForProcessor ),
'existing-card': ( transactionData: unknown ) =>
existingCardProcessor( transactionData, dataForProcessor ),
'existing-card-ebanx': ( transactionData: unknown ) =>
existingCardProcessor( transactionData, dataForProcessor ),
'existing-paypal-ppcp': ( transactionData: unknown ) =>
existingPayPalPPCPProcessor( transactionData, dataForProcessor ),
'paypal-express': () => payPalProcessor( dataForProcessor ),
'paypal-js': ( transactionData: unknown ) =>
payPalJsProcessor( transactionData, dataForProcessor ),
} ),
[ dataForProcessor, sitelessCheckoutType, translate ]
);
// Gravatar Theme
let gravatarColors = {};
let gravatarFontWeights = {};
if ( isGravatarDomain ) {
gravatarColors = {
primary: '#1d4fc4',
primaryBorder: '#001c5f',
primaryOver: '#002e9b',
success: '#1d4fc4',
discount: '#1d4fc4',
};
gravatarFontWeights = {
bold: '700',
};
}
// Jetpack Theme
const jetpackColors = isJetpackNotAtomic
? {
primary: colors[ 'Jetpack Green' ],
primaryBorder: colors[ 'Jetpack Green 80' ],
primaryOver: colors[ 'Jetpack Green 60' ],
success: colors[ 'Jetpack Green' ],
discount: colors[ 'Jetpack Green' ],
highlight: colors[ 'WordPress Blue 50' ],
highlightBorder: colors[ 'WordPress Blue 80' ],
highlightOver: colors[ 'WordPress Blue 60' ],
}
: {};
// A4A Theme
const a4aColors =
sitelessCheckoutType === 'a4a'
? {
primary: colors[ 'Automattic Blue' ],
primaryBorder: colors[ 'Automattic Blue 80' ],
primaryOver: colors[ 'Automattic Blue 60' ],
highlight: colors[ 'Automattic Blue 50' ],
highlightBorder: colors[ 'Automattic Blue 80' ],
highlightOver: colors[ 'Automattic Blue 60' ],
}
: {};
const theme = {
...checkoutTheme,
colors: { ...checkoutTheme.colors, ...gravatarColors, ...jetpackColors, ...a4aColors },
weights: { ...checkoutTheme.weights, ...gravatarFontWeights },
};
const isCheckoutV2ExperimentLoading = false;
const [ isCheckoutUiRedesignLoading ] = useCheckoutUiRedesignExperiment();
const { isLoading: isMobileCheckoutStickySummaryLoading } =
useMobileCheckoutStickySummaryExperiment();
// This variable determines if we see the loading page or if checkout can
// render its steps.
//
// Note that this does not prevent everything inside `CheckoutProvider` from
// rendering, only everything inside `CheckoutStepGroup`. This is because
// this variable is used to set the `FormStatus` to `FormStatus::LOADING`.
//
// These conditions do not need to be true if the cart is empty. The empty
// cart page will show itself based on `shouldShowEmptyCartPage()` which has
// its own set of conditions and is not affected by this list.
//
// Be careful what you add to this variable because it will slow down
// checkout's apparent load time. If something can be loaded async inside
// checkout, do that instead.
const checkoutLoadingConditions: Array< { name: string; isLoading: boolean } > = [
{ name: translate( 'Loading cart' ), isLoading: isInitialCartLoading },
{ name: translate( 'Loading saved payment methods' ), isLoading: arePaymentMethodsLoading },
{ name: translate( 'Initializing payment methods' ), isLoading: paymentMethods.length < 1 },
{
name: translate( 'Preparing products for cart' ),
isLoading: responseCart.products.length < 1,
},
{ name: translate( 'Loading countries list' ), isLoading: countriesList.length < 1 },
{ name: translate( 'Loading Site' ), isLoading: isCheckoutV2ExperimentLoading },
{
name: translate( 'Loading checkout' ),
isLoading: isCheckoutUiRedesignLoading || isMobileCheckoutStickySummaryLoading,
},
];
if ( shouldSetMigrationSticker ) {
checkoutLoadingConditions.push( {
name: translate( 'Setting introductory offer' ),
isLoading: isStickerLoading,
} );
}
const isCheckoutPageLoading: boolean = checkoutLoadingConditions.some(
( condition ) => condition.isLoading
);
if ( isCheckoutPageLoading ) {
debug( 'still loading because one of these is true', checkoutLoadingConditions );
} else {
debug( 'no longer loading' );
}
useRecordCheckoutLoaded( {
isLoading: isCheckoutPageLoading,
responseCart,
storedCards,
productAliasFromUrl,
checkoutFlow,
} );
const onPageLoadError: CheckoutPageErrorCallback = useCallback(
( errorType, error, errorData ) => {
logStashLoadErrorEvent( errorType, error, errorData );
function errorTypeToTracksEventName( type: string ): string {
switch ( type ) {
case 'page_load':
return 'calypso_checkout_composite_page_load_error';
case 'step_load':
return 'calypso_checkout_composite_step_load_error';
case 'submit_button_load':
return 'calypso_checkout_composite_submit_button_load_error';
case 'payment_method_load':
return 'calypso_checkout_composite_payment_method_load_error';
default:
// These are important so we might as well use something that we'll
// notice even if we don't recognize the event.
return 'calypso_checkout_composite_page_load_error';
}
}
reduxDispatch(
recordTracksEvent( errorTypeToTracksEventName( errorType ), {
error_message: convertErrorToString( error ),
...errorData,
} )
);
},
[ reduxDispatch ]
);
// IMPORTANT NOTE: This will not be called for redirect payment methods like
// PayPal. They will redirect directly to the post-checkout page decided by
// `getThankYouUrl` after passing through the pending page.
//
// DO NOT PUT POST-CHECKOUT BEHAVIOR IN HERE! IT'S NOT WHAT YOU THINK!
const onPaymentSubmittedAndProcessing = useCreatePaymentSubmittedAndProcessingCallback( {
createUserAndSiteBeforeTransaction,
productAliasFromUrl,
redirectTo,
purchaseId,
feature,
isComingFromUpsell,
disabledThankYouPage,
siteSlug: updatedSiteSlug,
sitelessCheckoutType,
connectAfterCheckout,
adminUrl,
fromSiteSlug,
} );
const handleStepChanged = useCallback(
( {
stepNumber,
previousStepNumber,
paymentMethodId,
}: {
stepNumber: number | null;
previousStepNumber: number;
paymentMethodId: string;
} ) => {
if ( stepNumber === 2 && previousStepNumber === 1 ) {
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_first_step_complete', {
payment_method:
translateCheckoutPaymentMethodToWpcomPaymentMethod( paymentMethodId ) || '',
} )
);
}
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_step_changed', {
step: stepNumber,
} )
);
},
[ reduxDispatch ]
);
const handlePaymentMethodChanged = useCallback(
( method: string ) => {
logStashEvent( 'payment_method_select', { newMethodId: String( method ) }, 'info' );
// Need to convert to the slug format used in old checkout so events are comparable
const rawPaymentMethodSlug = String( method );
const legacyPaymentMethodSlug = translateCheckoutPaymentMethodToTracksPaymentMethod(
rawPaymentMethodSlug as CheckoutPaymentMethodSlug
);
reduxDispatch( recordTracksEvent( 'calypso_checkout_switch_to_' + legacyPaymentMethodSlug ) );
},
[ reduxDispatch ]
);
// IMPORTANT NOTE: This will not be called for redirect payment methods like
// PayPal. They will redirect directly to the post-checkout page decided by
// `getThankYouUrl` after passing through the pending page.
//
// DO NOT PUT POST-CHECKOUT BEHAVIOR IN HERE! IT'S NOT WHAT YOU THINK!
const handlePaymentSubmitted = useCallback(
( args: PaymentEventCallbackArguments ) => {
onPaymentSubmittedAndProcessing?.( args );
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_step_complete', {
step: 2,
step_name: 'payment-method-step',
} )
);
},
[ onPaymentSubmittedAndProcessing, reduxDispatch ]
);
const handlePaymentError = useCallback(
( {
transactionError,
paymentMethodId,
}: {
transactionError: string | null;
paymentMethodId: string | null | undefined;
} ) => {
const errorNoticeText = transactionError ? (
<div dangerouslySetInnerHTML={ { __html: DOMPurify.sanitize( transactionError ) } } /> // eslint-disable-line react/no-danger -- The API response can contain anchor elements that we need to parse so they are rendered properly
) : (
translate( 'An error occurred during your purchase.' )
);
reduxDispatch( errorNotice( errorNoticeText, { id: 'checkout-payment-error' } ) );
reduxDispatch(
recordTracksEvent( 'calypso_checkout_payment_error', {
error_code: null,
reason: String( transactionError ),
} )
);
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_payment_error', {
error_code: null,
payment_method:
translateCheckoutPaymentMethodToWpcomPaymentMethod( paymentMethodId ?? '' ) || '',
reason: String( transactionError ),
} )
);
reduxDispatch(
recordTracksEvent( 'calypso_checkout_composite_stripe_transaction_error', {
error_message: String( transactionError ),
} )
);
},
[ reduxDispatch, translate ]
);
const handlePaymentRedirect = useCallback( () => {
reduxDispatch( infoNotice( translate( 'Redirecting to payment partner…' ) ) );
}, [ reduxDispatch, translate ] );
const initiallySelectedPaymentMethodId = getInitiallySelectedPaymentMethodId(
responseCart,
paymentMethods
);
const dashboard = getDashboardFromHostname( window?.location?.hostname );
const stepContainerV2Context = useMemo(
() => ( {
flowName: '',
stepName: '',
recordTracksEvent: () => {},
logo: getDashboardStepperLogo( dashboard ),
} ),
[ dashboard ]
);
return (
<Step.StepContainerV2Provider value={ stepContainerV2Context }>
<PageViewTracker
path={ analyticsPath }
title="Checkout"
properties={ analyticsProps }
options={ {
useJetpackGoogleAnalytics: sitelessCheckoutType === 'jetpack' || isJetpackNotAtomic,
useAkismetGoogleAnalytics: sitelessCheckoutType === 'akismet',
} }
/>
<VGSCollectProvider>
<CheckoutProvider
onPaymentComplete={ handlePaymentSubmitted }
onPaymentError={ handlePaymentError }
onPaymentRedirect={ handlePaymentRedirect }
onPageLoadError={ onPageLoadError }
onPaymentMethodChanged={ handlePaymentMethodChanged }
paymentMethods={ paymentMethods }
paymentProcessors={ paymentProcessors }
isLoading={ isCheckoutPageLoading }
isValidating={ isCartPendingUpdate }
theme={ theme }
selectFirstAvailablePaymentMethod
initiallySelectedPaymentMethodId={ initiallySelectedPaymentMethodId }
>
<CheckoutMainContent
loadingHeader={
<CheckoutLoadingPlaceholder checkoutLoadingConditions={ checkoutLoadingConditions } />
}
onStepChanged={ handleStepChanged }
customizedPreviousPath={ customizedPreviousPath }
isRemovingProductFromCart={ isRemovingProductFromCart }
areThereErrors={ areThereErrors }
isInitialCartLoading={ isInitialCartLoading }
addItemToCart={ addItemAndLog }
changeSelection={ changeSelection }
countriesList={ countriesList }
createUserAndSiteBeforeTransaction={ createUserAndSiteBeforeTransaction }
infoMessage={
<PrePurchaseNotices
siteId={ updatedSiteId }
shouldQueryUserPurchases={ Boolean( sitelessCheckoutType ) }
/>
}
isLoggedOutCart={ !! isLoggedOutCart }
onPageLoadError={ onPageLoadError }
paymentMethods={ paymentMethods }
areStoredCardsFiltered={ areStoredCardsFiltered }
isBusinessCardsFilterEmpty={ isBusinessCardsFilterEmpty }
removeProductFromCart={ removeProductFromCartAndMaybeRedirect }
showErrorMessageBriefly={ showErrorMessageBriefly }
siteId={ updatedSiteId }
siteUrl={ updatedSiteSlug }
/>
{
// Redirect modal is displayed mainly to all the agency partners who are purchasing Jetpack plans
<JetpackProRedirectModal
redirectTo={ redirectTo }
productSourceFromUrl={ productSourceFromUrl }
/>
}
</CheckoutProvider>
</VGSCollectProvider>
</Step.StepContainerV2Provider>
);
}
function getAnalyticsPath(
purchaseId: number | string | undefined,
product: string | undefined,
selectedSiteSlug: string | undefined,
selectedFeature: string | undefined,
plan: string | undefined,
sitelessCheckoutType: SitelessCheckoutType,
checkoutFlow: string
): { analyticsPath: string; analyticsProps: Record< string, string > } {
debug( 'getAnalyticsPath', {
purchaseId,
product,
selectedSiteSlug,
selectedFeature,
plan,
sitelessCheckoutType,
checkoutFlow,
} );
let analyticsPath = '';
let analyticsProps = {};
if ( purchaseId && product ) {
analyticsPath = '/checkout/:product/renew/:purchase_id/:site';
analyticsProps = { product, purchase_id: purchaseId, site: selectedSiteSlug };
} else if ( selectedFeature && plan ) {
analyticsPath = '/checkout/features/:feature/:site/:plan';
analyticsProps = { feature: selectedFeature, plan, site: selectedSiteSlug };
} else if ( selectedFeature && ! plan ) {
analyticsPath = '/checkout/features/:feature/:site';
analyticsProps = { feature: selectedFeature, site: selectedSiteSlug };
} else if ( product && selectedSiteSlug && ! purchaseId ) {
analyticsPath = '/checkout/:site/:product';
analyticsProps = { product, site: selectedSiteSlug, checkout_flow: checkoutFlow };
} else if ( selectedSiteSlug ) {
analyticsPath = '/checkout/:site';
analyticsProps = { site: selectedSiteSlug };
} else if ( product && ! selectedSiteSlug ) {
analyticsPath = '/checkout/:product';
analyticsProps = { product, checkout_flow: checkoutFlow };
} else {
analyticsPath = '/checkout/no-site';
}
if ( sitelessCheckoutType === 'jetpack' ) {
analyticsPath = analyticsPath.replace( 'checkout', 'checkout/jetpack' );
}
if ( sitelessCheckoutType === 'akismet' ) {