File size: 10,299 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
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
import { confirmStripeSetupIntentAndAttachCard } from '@automattic/calypso-stripe';
import {
	makeRedirectResponse,
	makeSuccessResponse,
	makeErrorResponse,
} from '@automattic/composite-checkout';
import { CartKey } from '@automattic/shopping-cart';
import { ManagedContactDetails } from '@automattic/wpcom-checkout';
import { addQueryArgs } from '@wordpress/url';
import wp from 'calypso/lib/wp';
import { getTaxValidationResult } from 'calypso/my-sites/checkout/src/lib/contact-validation';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { updateCreditCard, saveCreditCard } from './stored-payment-method-api';
import type {
	StripeSetupIntentId,
	StripeConfiguration,
	StripeSetupIntent,
} from '@automattic/calypso-stripe';
import type { PaymentProcessorResponse } from '@automattic/composite-checkout';
import type { Stripe, StripeCardNumberElement } from '@stripe/stripe-js';
import type { Purchase } from 'calypso/lib/purchases/types';
import type { CalypsoDispatch } from 'calypso/state/types';
import type { LocalizeProps } from 'i18n-calypso';

/**
 * Call our endpoint to create the Stripe Setup Intent to later be confirmed by
 * `confirmStripeSetupIntentAndAttachCard()`.
 *
 * NOTE: if countryCode is not provided, geolocation will be used to determine
 * which Stripe account to use to create the Payment Method.
 * The cartKey is optional and is only used in the Checkout flow to create
 * the SetupIntent using information from the cart - for special cases like
 * Indian Payments Methods with e-mandates.
 */
async function createStripeSetupIntent(
	countryCode?: string,
	cartKey?: CartKey
): Promise< StripeSetupIntentId > {
	const configuration = await wp.req.post( '/me/stripe-setup-intent', {
		country: countryCode,
		cart_key: cartKey,
	} );
	const intentId: string | undefined =
		configuration?.setup_intent_id && typeof configuration.setup_intent_id === 'string'
			? configuration.setup_intent_id
			: undefined;
	if ( ! intentId ) {
		throw new Error(
			'Error loading new payment method intent. Received invalid data from the server.'
		);
	}
	return intentId;
}

const wpcomAssignPaymentMethod = (
	subscriptionId: string,
	stored_details_id: string
): Promise< unknown > =>
	wp.req.post( {
		path: '/upgrades/' + subscriptionId + '/assign-payment-method',
		body: { stored_details_id },
		apiVersion: '1',
	} );

const wpcomCreatePayPalAgreement = (
	subscription_id: string,
	success_url: string,
	cancel_url: string,
	tax_country_code: string,
	tax_postal_code: string,
	tax_address: string,
	tax_organization: string,
	tax_city: string,
	tax_subdivision_code: string
): Promise< string > =>
	wp.req.post( {
		path: '/payment-methods/create-paypal-agreement',
		body: {
			subscription_id,
			success_url,
			cancel_url,
			tax_postal_code,
			tax_country_code,
			tax_address,
			tax_organization,
			tax_city,
			tax_subdivision_code,
		},
		apiVersion: '1',
	} );

export async function assignNewCardProcessor(
	{
		purchase,
		translate,
		stripe,
		stripeConfiguration,
		cardNumberElement,
		reduxDispatch,
		eventSource,
		cartKey,
	}: {
		purchase: Purchase | undefined;
		translate: LocalizeProps[ 'translate' ];
		stripe: Stripe | null;
		stripeConfiguration: StripeConfiguration | null;
		cardNumberElement: StripeCardNumberElement | undefined;
		reduxDispatch: CalypsoDispatch;
		eventSource?: string;
		cartKey?: CartKey;
	},
	submitData: unknown
): Promise< PaymentProcessorResponse > {
	try {
		if ( ! isNewCardDataValid( submitData ) ) {
			throw new Error( 'Credit Card data is invalid' );
		}
		if ( ! stripe || ! stripeConfiguration ) {
			throw new Error( 'Cannot assign payment method if Stripe is not loaded' );
		}
		if ( ! cardNumberElement ) {
			throw new Error( 'Cannot assign payment method if there is no card number' );
		}

		const {
			name,
			countryCode,
			postalCode,
			state,
			city,
			organization,
			address,
			useForAllSubscriptions,
			useForBusiness,
		} = submitData;

		const contactInfo: ManagedContactDetails = {
			countryCode: {
				value: countryCode,
				isTouched: true,
				errors: [],
			},
			postalCode: {
				value: postalCode ?? '',
				isTouched: true,
				errors: [],
			},
		};
		if ( state ) {
			contactInfo.state = {
				value: state,
				isTouched: true,
				errors: [],
			};
		}
		if ( city ) {
			contactInfo.city = {
				value: city,
				isTouched: true,
				errors: [],
			};
		}
		if ( organization ) {
			contactInfo.organization = {
				value: organization,
				isTouched: true,
				errors: [],
			};
		}
		if ( address ) {
			contactInfo.address1 = {
				value: address,
				isTouched: true,
				errors: [],
			};
		}
		const contactValidationResponse = await getTaxValidationResult( contactInfo );
		if ( ! contactValidationResponse.success ) {
			const errorMessage =
				contactValidationResponse.messages_simple.length > 0
					? contactValidationResponse.messages_simple[ 0 ]
					: 'Unknown error validating location information';
			throw new Error( errorMessage );
		}

		reduxDispatch( recordFormSubmitEvent( { purchase, useForAllSubscriptions } ) );

		// @todo: we should pass the countryCode to createStripeSetupIntent,
		// but since `prepareAndConfirmStripeSetupIntent()` uses the `stripe`
		// object created by `StripeHookProvider`, that object must also be
		// created with the same countryCode, and right now it is not.
		const stripeSetupIntentId = await createStripeSetupIntent( undefined, cartKey );
		const formFieldValues = {
			country: countryCode,
			postal_code: postalCode ?? '',
			name: name ?? '',
		};
		const tokenResponse = await prepareAndConfirmStripeSetupIntent(
			formFieldValues,
			stripe,
			cardNumberElement,
			stripeSetupIntentId
		);
		const token = tokenResponse.payment_method;
		const setupKey = tokenResponse.id;
		if ( ! token ) {
			throw new Error( String( translate( 'Failed to add card.' ) ) );
		}

		if ( purchase ) {
			const result = await updateCreditCard( {
				purchase,
				token: String( token ),
				stripeConfiguration,
				useForAllSubscriptions: Boolean( useForAllSubscriptions ),
				eventSource,
				postalCode,
				countryCode,
				state,
				city,
				organization,
				address,
				setupKey,
			} );

			return makeSuccessResponse( result );
		}

		const result = await saveCreditCard( {
			token: String( token ),
			stripeConfiguration,
			useForAllSubscriptions: Boolean( useForAllSubscriptions ),
			useForBusiness,
			eventSource,
			postalCode,
			countryCode,
			state,
			city,
			organization,
			address,
			setupKey,
		} );

		return makeSuccessResponse( result );
	} catch ( error ) {
		return makeErrorResponse( ( error as Error ).message );
	}
}

async function prepareAndConfirmStripeSetupIntent(
	{
		name,
		country,
		postal_code,
	}: {
		name: string;
		country: string;
		postal_code: string | number;
	},
	stripe: Stripe,
	cardNumberElement: StripeCardNumberElement,
	setupIntentId: StripeSetupIntentId
): Promise< StripeSetupIntent > {
	const paymentDetailsForStripe = {
		name,
		address: {
			country,
			postal_code,
		},
	};
	return confirmStripeSetupIntentAndAttachCard(
		stripe,
		cardNumberElement,
		setupIntentId,
		paymentDetailsForStripe
	);
}

function isNewCardDataValid( data: unknown ): data is NewCardSubmitData {
	const newCardData = data as NewCardSubmitData;
	return newCardData.countryCode !== undefined;
}

interface NewCardSubmitData {
	name?: string;
	countryCode: string;
	postalCode?: string;
	state?: string;
	city?: string;
	organization?: string;
	address?: string;
	useForAllSubscriptions: boolean;
	useForBusiness?: boolean;
}

export async function assignExistingCardProcessor(
	purchase: Purchase | undefined,
	reduxDispatch: CalypsoDispatch,
	submitData: unknown
): Promise< PaymentProcessorResponse > {
	reduxDispatch( recordFormSubmitEvent( { purchase } ) );
	try {
		if ( ! isValidExistingCardData( submitData ) ) {
			throw new Error( 'Credit card data is missing stored details id' );
		}
		const { storedDetailsId } = submitData;
		if ( ! purchase ) {
			throw new Error( 'Cannot assign PayPal payment method without a purchase' );
		}
		const data = await wpcomAssignPaymentMethod( String( purchase.id ), storedDetailsId );
		return makeSuccessResponse( data );
	} catch ( error ) {
		return makeErrorResponse( ( error as Error ).message );
	}
}

function isValidExistingCardData( data: unknown ): data is ExistingCardSubmitData {
	const existingCardData = data as ExistingCardSubmitData;
	return !! existingCardData.storedDetailsId;
}

interface ExistingCardSubmitData {
	storedDetailsId: string;
}

interface PayPalSubmitData {
	postalCode?: string;
	countryCode: string;
	address?: string;
	organization?: string;
	city?: string;
	state?: string;
}

function isValidPayPalData( data: unknown ): data is PayPalSubmitData {
	const payPalData = data as PayPalSubmitData;
	return payPalData.countryCode !== undefined;
}

export async function assignPayPalProcessor(
	purchase: Purchase | undefined,
	reduxDispatch: CalypsoDispatch,
	submitData: unknown
): Promise< PaymentProcessorResponse > {
	try {
		if ( ! purchase ) {
			throw new Error( 'Cannot assign PayPal payment method without a purchase' );
		}
		if ( ! isValidPayPalData( submitData ) ) {
			throw new Error( 'PayPal data is missing tax information' );
		}
		reduxDispatch( recordFormSubmitEvent( { purchase } ) );
		const data = await wpcomCreatePayPalAgreement(
			String( purchase.id ),
			addQueryArgs( window.location.href, { success: 'true' } ),
			window.location.href,
			submitData.countryCode,
			submitData.postalCode ?? '',
			submitData.address ?? '',
			submitData.organization ?? '',
			submitData.city ?? '',
			submitData.state ?? ''
		);
		return makeRedirectResponse( data );
	} catch ( error ) {
		return makeErrorResponse( ( error as Error ).message );
	}
}

function recordFormSubmitEvent( {
	purchase,
	useForAllSubscriptions,
}: {
	purchase?: Purchase;
	useForAllSubscriptions?: boolean;
} ) {
	return purchase?.productSlug
		? recordTracksEvent( 'calypso_purchases_credit_card_form_submit', {
				product_slug: purchase.productSlug,
				use_for_all_subs: String( useForAllSubscriptions ),
		  } )
		: recordTracksEvent( 'calypso_add_credit_card_form_submit', {
				use_for_all_subs: String( useForAllSubscriptions ),
		  } );
}