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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
import { createStripePaymentMethod } from '@automattic/calypso-stripe';
import {
	makeSuccessResponse,
	makeRedirectResponse,
	makeErrorResponse,
	PaymentProcessorResponseType,
} from '@automattic/composite-checkout';
import { getContactDetailsType } from '@automattic/wpcom-checkout';
import debugFactory from 'debug';
import { createEbanxToken } from 'calypso/lib/store-transactions';
import { assignNewCardProcessor } from 'calypso/me/purchases/manage-purchase/payment-method-selector/assignment-processor-functions';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { logStashEvent, recordTransactionBeginAnalytics } from '../lib/analytics';
import existingCardProcessor from './existing-card-processor';
import getDomainDetails from './get-domain-details';
import getPostalCode from './get-postal-code';
import {
	doesTransactionResponseRequire3DS,
	handle3DSChallenge,
	handle3DSInFlightError,
} from './stripe-3ds';
import submitWpcomTransaction from './submit-wpcom-transaction';
import {
	createTransactionEndpointRequestPayload,
	createTransactionEndpointCartFromResponseCart,
} from './translate-cart';
import type { PaymentProcessorOptions } from '../types/payment-processors';
import type { StripeConfiguration } from '@automattic/calypso-stripe';
import type { PaymentProcessorResponse } from '@automattic/composite-checkout';
import type { Stripe, StripeCardNumberElement } from '@stripe/stripe-js';
import type { LocalizeProps } from 'i18n-calypso';

const debug = debugFactory( 'calypso:composite-checkout:multi-partner-card-processor' );

type CardTransactionRequest = {
	paymentPartner: string;
};

type StripeCardTransactionRequest = {
	stripe: Stripe;
	stripeConfiguration: StripeConfiguration;
	paymentPartner: string;
	name: string;
	countryCode: string | undefined;
	postalCode: string | undefined;
	cardNumberElement: StripeCardNumberElement;
	useForAllSubscriptions: boolean;
};

type EbanxCardTransactionRequest = {
	name: string;
	countryCode: string;
	number: string;
	cvv: string;
	'expiration-date': string;
	state: string;
	city: string;
	postalCode: string;
	address: string;
	streetNumber: string;
	phoneNumber: string;
	document: string;
};

type EbanxToken = {
	deviceId: string;
	token: string;
};

async function stripeCardProcessor(
	submitData: unknown,
	transactionOptions: PaymentProcessorOptions
): Promise< PaymentProcessorResponse > {
	if ( ! isValidStripeCardTransactionData( submitData ) ) {
		throw new Error( 'Required purchase data is missing' );
	}

	const {
		includeDomainDetails,
		includeGSuiteDetails,
		responseCart,
		siteId,
		contactDetails,
		reduxDispatch,
	} = transactionOptions;
	reduxDispatch(
		recordTransactionBeginAnalytics( {
			paymentMethodId: 'stripe',
			useForAllSubscriptions: submitData.useForAllSubscriptions,
		} )
	);

	const cartCountry = responseCart.tax.location.country_code ?? '';
	const formCountry = contactDetails?.countryCode?.value ?? '';
	if ( cartCountry !== formCountry ) {
		// Changes to the contact form data should always be sent to the cart, so
		// this should not be possible.
		reduxDispatch(
			recordTracksEvent( 'calypso_checkout_mismatched_tax_location', {
				form_country: formCountry,
				cart_country: cartCountry,
			} )
		);
	}

	let paymentMethodToken;
	try {
		const tokenResponse = await createStripePaymentMethodToken( {
			...submitData,
			country: contactDetails?.countryCode?.value,
			postalCode: getPostalCode( contactDetails ),
		} );
		paymentMethodToken = tokenResponse.id;
	} catch ( error ) {
		debug( 'transaction failed' );
		// Errors here are "expected" errors, meaning that they (hopefully) come
		// from stripe and not from some bug in the frontend code.
		return makeErrorResponse( ( error as Error ).message );
	}

	const formattedTransactionData = createTransactionEndpointRequestPayload( {
		...submitData,
		country: contactDetails?.countryCode?.value ?? '',
		postalCode: getPostalCode( contactDetails ),
		subdivisionCode: contactDetails?.state?.value,
		siteId: transactionOptions.siteId ? String( transactionOptions.siteId ) : undefined,
		domainDetails: getDomainDetails( contactDetails, {
			includeDomainDetails,
			includeGSuiteDetails,
		} ),
		paymentMethodToken,
		cart: createTransactionEndpointCartFromResponseCart( {
			siteId,
			contactDetails:
				getDomainDetails( contactDetails, { includeDomainDetails, includeGSuiteDetails } ) ?? null,
			responseCart: responseCart,
		} ),
		paymentMethodType: 'WPCOM_Billing_Stripe_Payment_Method',
		paymentPartnerProcessorId: transactionOptions.stripeConfiguration?.processor_id,
	} );
	debug( 'sending stripe transaction', formattedTransactionData );
	let paymentIntentId: string | undefined = undefined;
	return submitWpcomTransaction( formattedTransactionData, transactionOptions )
		.then( async ( stripeResponse ) => {
			if ( doesTransactionResponseRequire3DS( stripeResponse ) ) {
				debug( 'transaction requires authentication' );
				paymentIntentId = stripeResponse.message.payment_intent_id;
				await handle3DSChallenge(
					reduxDispatch,
					submitData.stripe,
					stripeResponse.message.payment_intent_client_secret,
					paymentIntentId
				);
				// We must return the original authentication response in order
				// to have access to the order_id so that we can display a
				// pending page while we wait for Stripe to send a webhook to
				// complete the purchase so we do not return the result of
				// confirming the payment intent and instead fall through.
			}
			return stripeResponse;
		} )
		.then( ( stripeResponse ) => {
			if ( stripeResponse.redirect_url && ! doesTransactionResponseRequire3DS( stripeResponse ) ) {
				return makeRedirectResponse( stripeResponse.redirect_url );
			}
			return makeSuccessResponse( stripeResponse );
		} )
		.catch( ( error: Error ) => {
			debug( 'transaction failed' );
			reduxDispatch(
				recordTracksEvent( 'calypso_checkout_card_transaction_failed', {
					payment_intent_id: paymentIntentId ?? '',
					error: error.message,
				} )
			);
			logStashEvent( 'calypso_checkout_card_transaction_failed', {
				payment_intent_id: paymentIntentId ?? '',
				tags: [ `payment_intent_id:${ paymentIntentId }` ],
				error: error.message,
			} );

			handle3DSInFlightError( error, paymentIntentId );

			// Errors here are "expected" errors, meaning that they (hopefully) come
			// from the endpoint and not from some bug in the frontend code.
			return makeErrorResponse( error.message );
		} );
}

async function ebanxCardProcessor(
	submitData: unknown,
	transactionOptions: PaymentProcessorOptions
): Promise< PaymentProcessorResponse > {
	if ( ! isValidEbanxCardTransactionData( submitData ) ) {
		throw new Error( 'Required purchase data is missing' );
	}
	const {
		includeDomainDetails,
		includeGSuiteDetails,
		responseCart,
		contactDetails,
		reduxDispatch,
	} = transactionOptions;
	reduxDispatch( recordTransactionBeginAnalytics( { paymentMethodId: 'ebanx' } ) );

	let paymentMethodToken;
	try {
		const ebanxTokenResponse: EbanxToken = await createEbanxToken( 'new_purchase', {
			country: submitData.countryCode,
			name: submitData.name,
			number: submitData.number,
			cvv: submitData.cvv,
			'expiration-date': submitData[ 'expiration-date' ],
		} );
		paymentMethodToken = ebanxTokenResponse;
	} catch ( error ) {
		debug( 'transaction failed' );
		// Errors here are "expected" errors, meaning that they (hopefully) come
		// from Ebanx and not from some bug in the frontend code.
		return makeErrorResponse( ( error as Error ).message );
	}

	const formattedTransactionData = createTransactionEndpointRequestPayload( {
		...submitData,
		couponId: responseCart.coupon,
		country: submitData.countryCode,
		deviceId: paymentMethodToken?.deviceId,
		domainDetails: getDomainDetails( contactDetails, {
			includeDomainDetails,
			includeGSuiteDetails,
		} ),
		paymentMethodToken: paymentMethodToken.token,
		cart: createTransactionEndpointCartFromResponseCart( {
			siteId: transactionOptions.siteId,
			contactDetails:
				getDomainDetails( contactDetails, { includeDomainDetails, includeGSuiteDetails } ) ?? null,
			responseCart: transactionOptions.responseCart,
		} ),
		paymentMethodType: 'WPCOM_Billing_Ebanx',
	} );
	debug( 'sending ebanx transaction', formattedTransactionData );
	return submitWpcomTransaction( formattedTransactionData, transactionOptions )
		.then( makeSuccessResponse )
		.catch( ( error ) => {
			debug( 'transaction failed' );
			// Errors here are "expected" errors, meaning that they (hopefully) come
			// from the endpoint and not from some bug in the frontend code.
			return makeErrorResponse( error.message );
		} );
}

export interface FreePurchaseData {
	translate: LocalizeProps[ 'translate' ];
}

export default async function multiPartnerCardProcessor(
	submitData: unknown,
	dataForProcessor: PaymentProcessorOptions,
	freePurchaseData?: FreePurchaseData
): Promise< PaymentProcessorResponse > {
	if ( ! isValidMultiPartnerTransactionData( submitData ) ) {
		throw new Error( 'Required purchase data is missing' );
	}

	// For free purchases we cannot use the regular processor because it requires
	// making a charge. Instead, we will create a new card, then use the
	// existingCardProcessor because it works for free purchases.
	const isPurchaseFree =
		dataForProcessor.responseCart.total_cost_integer === 0 &&
		dataForProcessor.responseCart.products.length > 0;
	if ( isPurchaseFree ) {
		if ( ! isValidStripeCardTransactionData( submitData ) ) {
			throw new Error( 'Required purchase data is missing' );
		}
		if ( submitData.paymentPartner === 'ebanx' ) {
			throw new Error( 'Cannot use Ebanx for free purchases' );
		}
		if ( ! freePurchaseData?.translate ) {
			throw new Error( 'Required free purchase data is missing' );
		}

		const contactDetailsType = getContactDetailsType( dataForProcessor.responseCart );
		const submitDataWithContactInfo =
			contactDetailsType === 'none'
				? submitData
				: {
						...submitData,
						// In `PaymentMethodSelector` which is used for adding new cards, the
						// stripe payment method is passed `shouldShowTaxFields` which causes
						// it to show required tax location fields in the payment method
						// itself; that data is then submitted to the `assignNewCardProcessor`
						// to send to Stripe as part of saving the card. However, in checkout
						// we normally do not display those fields since they are already included in
						// the billing details step. Therefore we must pass in the tax location
						// data explicitly here so we can use `assignNewCardProcessor`.
						countryCode: dataForProcessor.contactDetails?.countryCode?.value,
						postalCode: getPostalCode( dataForProcessor.contactDetails ),
						state: dataForProcessor.contactDetails?.state?.value,
						city: dataForProcessor.contactDetails?.city?.value,
						organization: dataForProcessor.contactDetails?.organization?.value,
						address: dataForProcessor.contactDetails?.address1?.value,
				  };
		const newCardResponse = await assignNewCardProcessor(
			{
				purchase: undefined,
				translate: freePurchaseData.translate,
				stripe: dataForProcessor.stripe,
				stripeConfiguration: dataForProcessor.stripeConfiguration,
				cardNumberElement: submitData.cardNumberElement,
				reduxDispatch: dataForProcessor.reduxDispatch,
				eventSource: '/checkout',
				cartKey: dataForProcessor.responseCart.cart_key,
			},
			submitDataWithContactInfo
		);
		if ( newCardResponse.type === PaymentProcessorResponseType.ERROR ) {
			return newCardResponse;
		}

		const storedCard = newCardResponse.payload;
		if ( ! isValidNewCardResponseData( storedCard ) ) {
			throw new Error( 'New card was not saved' );
		}
		return existingCardProcessor(
			{
				...submitData,
				storedDetailsId: storedCard.stored_details_id,
				paymentMethodToken: storedCard.mp_ref,
				paymentPartnerProcessorId: storedCard.payment_partner,
			},
			dataForProcessor
		);
	}

	const paymentPartner = submitData.paymentPartner;
	if ( paymentPartner === 'stripe' ) {
		return stripeCardProcessor( submitData, dataForProcessor );
	}
	if ( paymentPartner === 'ebanx' ) {
		return ebanxCardProcessor( submitData, dataForProcessor );
	}
	throw new RangeError( 'Unrecognized card payment partner: "' + paymentPartner + '"' );
}

function isValidMultiPartnerTransactionData(
	submitData: unknown
): submitData is CardTransactionRequest {
	const data = submitData as CardTransactionRequest;
	if ( ! data?.paymentPartner ) {
		throw new Error( 'Transaction requires paymentPartner and none was provided' );
	}
	return true;
}

function isValidStripeCardTransactionData(
	submitData: unknown
): submitData is StripeCardTransactionRequest {
	const data = submitData as StripeCardTransactionRequest;
	if ( ! data?.stripe ) {
		throw new Error( 'Transaction requires stripe and none was provided' );
	}
	if ( ! data?.stripeConfiguration ) {
		throw new Error( 'Transaction requires stripeConfiguration and none was provided' );
	}
	if ( ! data.cardNumberElement ) {
		throw new Error( 'Transaction requires credit card field and none was provided' );
	}
	return true;
}

function isValidEbanxCardTransactionData(
	submitData: unknown
): submitData is EbanxCardTransactionRequest {
	const data = submitData as EbanxCardTransactionRequest;
	if ( ! data ) {
		throw new Error( 'Transaction requires data and none was provided' );
	}
	return true;
}

interface NewCardResponseData {
	stored_details_id: string;
	mp_ref: string;
	payment_partner: string;
}

function isValidNewCardResponseData( submitData: unknown ): submitData is NewCardResponseData {
	const data = submitData as NewCardResponseData;
	if ( ! data || ! data.stored_details_id || ! data.mp_ref || ! data.payment_partner ) {
		throw new Error( 'New card was not saved' );
	}
	return true;
}

function createStripePaymentMethodToken( {
	stripe,
	cardNumberElement,
	name,
	country,
	postalCode,
}: {
	stripe: Stripe;
	cardNumberElement: StripeCardNumberElement;
	name: string | undefined;
	country: string | undefined;
	postalCode: string | undefined;
} ) {
	return createStripePaymentMethod( stripe, cardNumberElement, {
		name,
		address: {
			country,
			postal_code: postalCode,
		},
	} );
}