File size: 11,978 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useShoppingCart } from '@automattic/shopping-cart';
import { isURL } from '@wordpress/url';
import debugFactory from 'debug';
import { useCallback } from 'react';
import { recordPurchase } from 'calypso/lib/analytics/record-purchase';
import { hasEcommercePlan } from 'calypso/lib/cart-values/cart-items';
import getThankYouPageUrl from 'calypso/my-sites/checkout/get-thank-you-page-url';
import useSiteDomains from 'calypso/my-sites/checkout/src/hooks/use-site-domains';
import useCartKey from 'calypso/my-sites/checkout/use-cart-key';
import {
	retrieveSignupDestination,
	clearSignupDestinationCookie,
} from 'calypso/signup/storageUtils';
import { useSelector, useDispatch } from 'calypso/state';
import { clearPurchases } from 'calypso/state/purchases/actions';
import { fetchReceiptCompleted } from 'calypso/state/receipts/actions';
import hasGravatarDomainQueryParam from 'calypso/state/selectors/has-gravatar-domain-query-param';
import isAtomicSite from 'calypso/state/selectors/is-site-automated-transfer';
import { requestSite } from 'calypso/state/sites/actions';
import { fetchSiteFeatures } from 'calypso/state/sites/features/actions';
import {
	isJetpackSite,
	getJetpackCheckoutRedirectUrl,
	isBackupPluginActive,
	isSearchPluginActive,
} from 'calypso/state/sites/selectors';
import { getSelectedSite, getSelectedSiteId } from 'calypso/state/ui/selectors';
import { recordCompositeCheckoutErrorDuringAnalytics } from '../lib/analytics';
import normalizeTransactionResponse from '../lib/normalize-transaction-response';
import { absoluteRedirectThroughPending, redirectThroughPending } from '../lib/pending-page';
import type {
	PaymentEventCallback,
	PaymentEventCallbackArguments,
} from '@automattic/composite-checkout';
import type { ResponseCart } from '@automattic/shopping-cart';
import type {
	WPCOMTransactionEndpointResponse,
	SitelessCheckoutType,
} from '@automattic/wpcom-checkout';
import type { PostCheckoutUrlArguments } from 'calypso/my-sites/checkout/get-thank-you-page-url';
import type { CalypsoDispatch } from 'calypso/state/types';

const debug = debugFactory( 'calypso:composite-checkout:use-on-payment-complete' );

/**
 * Generates a callback to be called after checkout is successfully complete.
 *
 * 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`.
 */
export default function useCreatePaymentCompleteCallback( {
	createUserAndSiteBeforeTransaction,
	productAliasFromUrl,
	redirectTo,
	purchaseId,
	feature,
	isInModal,
	isComingFromUpsell,
	disabledThankYouPage,
	siteSlug,
	sitelessCheckoutType,
	connectAfterCheckout,
	adminUrl: wpAdminUrl,
	fromSiteSlug,
}: {
	createUserAndSiteBeforeTransaction?: boolean;
	productAliasFromUrl?: string | undefined;
	redirectTo?: string | undefined;
	purchaseId?: number | string | undefined;
	feature?: string | undefined;
	isInModal?: boolean;
	isComingFromUpsell?: boolean;
	disabledThankYouPage?: boolean;
	siteSlug: string | undefined;
	sitelessCheckoutType?: SitelessCheckoutType;
	connectAfterCheckout?: boolean;
	adminUrl?: string;
	/**
	 * `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;
} ): PaymentEventCallback {
	const cartKey = useCartKey();
	const { responseCart, reloadFromServer: reloadCart } = useShoppingCart( cartKey );
	const reduxDispatch = useDispatch();
	const siteId = useSelector( getSelectedSiteId );
	const selectedSiteData = useSelector( getSelectedSite );
	const adminUrl = selectedSiteData?.options?.admin_url || wpAdminUrl;
	const sitePlanSlug = selectedSiteData?.plan?.product_slug;
	const isJetpackNotAtomic =
		useSelector(
			( state ) =>
				siteId &&
				( isJetpackSite( state, siteId ) ||
					isBackupPluginActive( state, siteId ) ||
					isSearchPluginActive( state, siteId ) ) &&
				! isAtomicSite( state, siteId )
		) || false;
	const isGravatarDomain = useSelector( hasGravatarDomainQueryParam );
	const adminPageRedirect = useSelector( ( state ) =>
		getJetpackCheckoutRedirectUrl( state, siteId )
	);

	const domains = useSiteDomains( siteId ?? undefined );

	return useCallback(
		async ( { transactionLastResponse }: PaymentEventCallbackArguments ) => {
			debug( 'payment completed successfully' );
			const transactionResult = normalizeTransactionResponse( transactionLastResponse );

			// In the case of a Jetpack product site-less purchase, we need to include the blog ID of the
			// created site in the Thank You page URL.
			// TODO: It does not seem like this would be needed for Akismet, but marking to follow up
			let jetpackTemporarySiteId: string | undefined;
			if (
				sitelessCheckoutType === 'jetpack' &&
				! siteSlug &&
				[ 'no-user', 'no-site' ].includes( String( responseCart.cart_key ) ) &&
				'purchases' in transactionResult &&
				transactionResult.purchases
			) {
				jetpackTemporarySiteId = Object.keys( transactionResult.purchases ).pop();
			}

			const getThankYouPageUrlArguments: PostCheckoutUrlArguments = {
				siteSlug: siteSlug || undefined,
				siteId: siteId || undefined,
				adminUrl,
				receiptId: 'receipt_id' in transactionResult ? transactionResult.receipt_id : undefined,
				redirectTo,
				purchaseId,
				feature,
				cart: responseCart,
				sitelessCheckoutType,
				isJetpackNotAtomic,
				isGravatarDomain,
				productAliasFromUrl,
				hideNudge: isComingFromUpsell,
				isInModal,
				jetpackTemporarySiteId,
				adminPageRedirect,
				domains,
				connectAfterCheckout,
				fromSiteSlug,
			};

			debug( 'getThankYouUrl called with', getThankYouPageUrlArguments );
			const url = getThankYouPageUrl( getThankYouPageUrlArguments );
			debug( 'getThankYouUrl returned', url );

			try {
				await recordPaymentCompleteAnalytics( {
					transactionResult,
					responseCart,
					reduxDispatch,
					sitePlanSlug,
				} );
			} catch ( err ) {
				// eslint-disable-next-line no-console
				console.error( err );
				reduxDispatch(
					recordCompositeCheckoutErrorDuringAnalytics( {
						errorObject: err as Error,
						failureDescription: 'useCreatePaymentCompleteCallback',
					} )
				);
			}

			const receiptId =
				transactionResult && 'receipt_id' in transactionResult
					? transactionResult.receipt_id
					: undefined;
			debug( 'transactionResult was', transactionResult );

			reduxDispatch( clearPurchases() );

			// Removes the destination cookie only if redirecting to the signup destination.
			// (e.g. if the destination is an upsell nudge, it does not remove the cookie).
			const destinationFromCookie = retrieveSignupDestination();
			if ( url.includes( destinationFromCookie ) ) {
				debug( 'clearing redirect url cookie' );
				clearSignupDestinationCookie();
			}

			if (
				receiptId &&
				transactionResult &&
				'purchases' in transactionResult &&
				transactionResult.purchases &&
				transactionResult.success
			) {
				debug( 'fetching receipt' );
				reduxDispatch( fetchReceiptCompleted( receiptId, transactionResult ) );
			}

			if ( siteId ) {
				reduxDispatch( requestSite( siteId ) );
				reduxDispatch( fetchSiteFeatures( siteId ) );
			}

			// Checkout in the modal might not need thank you page.
			// For example, Focused Launch is showing a success dialog directly in editor instead of a thank you page.
			// See https://github.com/Automattic/wp-calypso/pull/47808#issuecomment-755196691
			if ( isInModal && disabledThankYouPage && ! hasEcommercePlan( responseCart ) ) {
				return;
			}

			/**
			 * IMPORTANT
			 *
			 * This function is only called for purchases which use specific
			 * payment methods. Redirect payment methods like PayPal or
			 * Bancontact or some 3DS credit cards will not trigger this
			 * function. Functions triggered on the "pending" page will be more
			 * accurate and will capture most flows, but not purchases made
			 * through the one-click checkout modal, which only use saved
			 * credit cards.
			 */

			debug( 'just redirecting to', url );

			if ( createUserAndSiteBeforeTransaction ) {
				try {
					window.localStorage.removeItem( 'shoppingCart' );
					window.localStorage.removeItem( 'siteParams' );
				} catch ( err ) {
					debug( 'error while clearing localStorage cart' );
				}

				// We use window.location instead of page() so that the cookies are
				// detected on fresh page load. Using page(url) will take us to the
				// log-in page which we don't want.
				absoluteRedirectThroughPending( url, {
					siteSlug,
					orderId: 'order_id' in transactionResult ? transactionResult.order_id : undefined,
					receiptId: 'receipt_id' in transactionResult ? transactionResult.receipt_id : undefined,
					fromExternalCheckout: sitelessCheckoutType === 'a4a',
				} );
				return;
			}

			// We need to do a hard redirect if we're redirecting to the stepper.
			// Since stepper is self-contained, it doesn't load properly if we do a normal history state change
			// The same is true if we are redirecting to the signup flow, we are restricting it to only 1 specific flow here.
			if (
				isURL( url ) ||
				url.includes( '/setup/' ) ||
				url.includes( '/start/site-content-collection' )
			) {
				absoluteRedirectThroughPending( url, {
					siteSlug,
					orderId: 'order_id' in transactionResult ? transactionResult.order_id : undefined,
					receiptId: 'receipt_id' in transactionResult ? transactionResult.receipt_id : undefined,
					fromSiteSlug,
					fromExternalCheckout: sitelessCheckoutType === 'a4a',
				} );
				return;
			}

			reloadCart().catch( () => {
				// No need to do anything here. CartMessages will report this error to the user.
			} );
			redirectThroughPending( url, {
				siteSlug,
				orderId: 'order_id' in transactionResult ? transactionResult.order_id : undefined,
				receiptId: 'receipt_id' in transactionResult ? transactionResult.receipt_id : undefined,
				fromExternalCheckout: sitelessCheckoutType === 'a4a',
				isGravatarDomain,
			} );
		},
		[
			reloadCart,
			siteSlug,
			adminUrl,
			redirectTo,
			purchaseId,
			feature,
			isJetpackNotAtomic,
			isGravatarDomain,
			productAliasFromUrl,
			isComingFromUpsell,
			isInModal,
			reduxDispatch,
			siteId,
			responseCart,
			createUserAndSiteBeforeTransaction,
			disabledThankYouPage,
			sitelessCheckoutType,
			adminPageRedirect,
			domains,
			sitePlanSlug,
			connectAfterCheckout,
			fromSiteSlug,
		]
	);
}

async function recordPaymentCompleteAnalytics( {
	transactionResult,
	responseCart,
	reduxDispatch,
	sitePlanSlug,
}: {
	transactionResult: WPCOMTransactionEndpointResponse | undefined;
	responseCart: ResponseCart;
	reduxDispatch: CalypsoDispatch;
	sitePlanSlug?: string | null;
} ) {
	/**
	 * IMPORTANT
	 *
	 * Do not rely on analytics recorded in this function because these are
	 * only recorded for purchases which use specific payment methods. Redirect
	 * payment methods like PayPal or Bancontact or some 3DS credit cards will
	 * not trigger this function. Events triggered on the "pending" page will
	 * be more accurate and will capture most flows, but not purchases made
	 * through the one-click checkout modal. Prefer backend events which are
	 * much more accurate.
	 */

	try {
		await recordPurchase( {
			cart: responseCart,
			orderId:
				transactionResult && 'receipt_id' in transactionResult
					? transactionResult.receipt_id
					: undefined,
			sitePlanSlug,
		} );
	} catch ( err ) {
		// eslint-disable-next-line no-console
		console.error( err );
		reduxDispatch(
			recordCompositeCheckoutErrorDuringAnalytics( {
				errorObject: err as Error,
				failureDescription: 'useCreatePaymentCompleteCallback',
			} )
		);
	}
}