File size: 6,413 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 |
import { loadStripeLibrary } from '@automattic/calypso-stripe';
import {
makeSuccessResponse,
makeRedirectResponse,
makeErrorResponse,
} from '@automattic/composite-checkout';
import debugFactory from 'debug';
import { getStripeConfiguration } from 'calypso/lib/store-transactions';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { recordTransactionBeginAnalytics, logStashEvent } from '../lib/analytics';
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 { PaymentProcessorResponse } from '@automattic/composite-checkout';
import type { TransactionRequest } from '@automattic/wpcom-checkout';
const debug = debugFactory( 'calypso:composite-checkout:existing-card-processor' );
type ExistingCardTransactionRequest = Partial< Omit< TransactionRequest, 'paymentMethodType' > > &
Required<
Pick<
TransactionRequest,
'storedDetailsId' | 'paymentMethodToken' | 'paymentPartnerProcessorId'
>
>;
export default async function existingCardProcessor(
transactionData: unknown,
dataForProcessor: PaymentProcessorOptions
): Promise< PaymentProcessorResponse > {
if ( ! isValidTransactionData( transactionData ) ) {
throw new Error( 'Required purchase data is missing' );
}
const {
stripe,
includeDomainDetails,
includeGSuiteDetails,
contactDetails,
reduxDispatch,
responseCart,
} = dataForProcessor;
if ( ! stripe ) {
throw new Error( 'Stripe is required to submit an existing card payment' );
}
reduxDispatch( recordTransactionBeginAnalytics( { paymentMethodId: 'existingCard' } ) );
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,
} )
);
}
const domainDetails = getDomainDetails( contactDetails, {
includeDomainDetails,
includeGSuiteDetails,
} );
debug( 'formatting existing card transaction', transactionData );
const formattedTransactionData = createTransactionEndpointRequestPayload( {
...transactionData,
name: transactionData.name ?? '',
country: contactDetails?.countryCode?.value ?? '',
postalCode: getPostalCode( contactDetails ),
subdivisionCode: contactDetails?.state?.value,
domainDetails,
cart: createTransactionEndpointCartFromResponseCart( {
siteId: dataForProcessor.siteId,
contactDetails: domainDetails ?? null,
responseCart,
} ),
paymentMethodType: 'WPCOM_Billing_MoneyPress_Stored',
} );
debug( 'submitting existing card transaction', formattedTransactionData );
let paymentIntentId: string | undefined = undefined;
return submitWpcomTransaction( formattedTransactionData, dataForProcessor )
.then( async ( stripeResponse ) => {
if ( doesTransactionResponseRequire3DS( stripeResponse ) ) {
debug( 'transaction requires authentication' );
paymentIntentId = stripeResponse.message.payment_intent_id;
// Saved cards already have a payment partner ID and we must use that ID to
// generate the `stripe` object we use to confirm 3DS challenges. Otherwise
// we may contact the wrong Stripe account.
const cardSpecificStripe = transactionData.paymentPartnerProcessorId
? await loadStripeLibrary( {
fetchStripeConfiguration: getStripeConfiguration,
paymentPartner: transactionData.paymentPartnerProcessorId,
} )
: undefined;
await handle3DSChallenge(
reduxDispatch,
cardSpecificStripe ?? 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 ) ) {
debug( 'transaction requires redirect' );
return makeRedirectResponse( stripeResponse.redirect_url );
}
debug( 'transaction was successful' );
return makeSuccessResponse( stripeResponse );
} )
.catch( ( error: Error ) => {
debug( 'transaction failed' );
reduxDispatch(
recordTracksEvent( 'calypso_checkout_existing_card_transaction_failed', {
payment_intent_id: paymentIntentId ?? '',
error: error.message,
} )
);
logStashEvent(
'calypso_checkout_existing_card_transaction_failed',
{
payment_intent_id: paymentIntentId ?? '',
tags: [ `payment_intent_id:${ paymentIntentId }` ],
error: error.message,
},
'info'
);
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 );
} );
}
function isValidTransactionData(
submitData: unknown
): submitData is ExistingCardTransactionRequest {
const data = submitData as ExistingCardTransactionRequest;
// Validate data required for this payment method type. Some other data may
// be required by the server but not required here since the server will give
// a better localized error message than we can provide.
if ( ! data.storedDetailsId ) {
throw new Error( 'Transaction requires saved card information and none was provided' );
}
if ( ! data.paymentMethodToken ) {
throw new Error( 'Transaction requires a Stripe token and none was provided' );
}
if ( ! data.paymentPartnerProcessorId ) {
throw new Error( 'Transaction requires a processor id and none was provided' );
}
return true;
}
|