File size: 5,487 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 |
import { makeErrorResponse, makeSuccessResponse } from '@automattic/composite-checkout';
import debugFactory from 'debug';
import wp from 'calypso/lib/wp';
import { recordTransactionBeginAnalytics } from '../lib/analytics';
import getDomainDetails from '../lib/get-domain-details';
import { addUrlToPendingPageRedirect } from '../lib/pending-page';
import {
createTransactionEndpointCartFromResponseCart,
createTransactionEndpointRequestPayload,
} from '../lib/translate-cart';
import getPostalCode from './get-postal-code';
import submitWpcomTransaction from './submit-wpcom-transaction';
import type { PaymentProcessorOptions } from '../types/payment-processors';
import type { PaymentProcessorResponse } from '@automattic/composite-checkout';
const debug = debugFactory( 'calypso:paypal-js-processor' );
type PayPalSubmitData = {
resolvePayPalOrderPromise: ( payPalOrderId: string ) => Promise< string >;
payPalApprovalPromise: Promise< void >;
};
type PayPalConfirmFailResponse = {
error: string;
message: string;
};
type PayPalConfirmSuccessResponse = {
success: true;
};
type PayPalConfirmResponse = PayPalConfirmFailResponse | PayPalConfirmSuccessResponse;
function isValidPayPalJsSubmitData( data: unknown ): data is PayPalSubmitData {
const payPalData = data as PayPalSubmitData;
if ( 'resolvePayPalOrderPromise' in payPalData ) {
return true;
}
return false;
}
async function payPalJsApproval(
bdOrderId: string,
payPalOrderId: string
): Promise< PayPalConfirmResponse > {
const body = {
bd_order_id: bdOrderId,
paypal_order_id: payPalOrderId,
};
const path = '/me/paypal-ppcp-confirm-payment';
return wp.req.post( { path, body } );
}
export async function payPalJsProcessor(
submitData: unknown,
transactionOptions: PaymentProcessorOptions
): Promise< PaymentProcessorResponse > {
if ( ! isValidPayPalJsSubmitData( submitData ) ) {
throw new Error( 'Missing promise in submitted PayPal data' );
}
const {
getThankYouUrl,
createUserAndSiteBeforeTransaction,
reduxDispatch,
includeDomainDetails,
includeGSuiteDetails,
responseCart,
siteId,
siteSlug,
contactDetails,
fromSiteSlug,
} = transactionOptions;
reduxDispatch( recordTransactionBeginAnalytics( { paymentMethodId: 'paypal-js' } ) );
let currentUrl;
try {
currentUrl = new URL( window.location.href );
} catch ( error ) {
currentUrl = new URL( `https://wordpress.com/checkout/${ siteSlug }` );
}
// We must strip out the hash value because it may break URL encoding when
// this value is passed back and forth to PayPal and through our own
// endpoints. Otherwise we may end up with an incorrect URL like
// 'http://wordpress.com/checkout?cart=no-user#step2?paypal=ABCDEFG'.
currentUrl.hash = '';
if ( createUserAndSiteBeforeTransaction ) {
// It's not clear if this is still required but it may be.
currentUrl.searchParams.set( 'cart', 'no-user' );
}
const cancelUrl = currentUrl.toString();
const thankYouUrl = getThankYouUrl() || 'https://wordpress.com';
const successUrl = addUrlToPendingPageRedirect( thankYouUrl, {
siteSlug,
urlType: 'absolute',
fromSiteSlug,
} );
const formattedTransactionData = createTransactionEndpointRequestPayload( {
name: '',
country: contactDetails?.countryCode?.value ?? '',
postalCode: getPostalCode( contactDetails ),
subdivisionCode: contactDetails?.state?.value,
siteId: transactionOptions.siteId ? String( transactionOptions.siteId ) : undefined,
domainDetails: getDomainDetails( contactDetails, {
includeDomainDetails,
includeGSuiteDetails,
} ),
cart: createTransactionEndpointCartFromResponseCart( {
siteId,
contactDetails:
getDomainDetails( contactDetails, { includeDomainDetails, includeGSuiteDetails } ) ?? null,
responseCart: responseCart,
} ),
paymentMethodType: 'WPCOM_Billing_PayPal_PPCP',
successUrl,
cancelUrl,
} );
debug( 'sending paypal transaction', formattedTransactionData );
try {
const response = await submitWpcomTransaction( formattedTransactionData, transactionOptions );
if ( ! ( 'paypal_order_id' in response ) || ! response.paypal_order_id ) {
return makeErrorResponse( 'Transaction response did not include PayPal order ID' );
}
if ( ! ( 'order_id' in response ) || ! response.order_id ) {
return makeErrorResponse( 'Transaction response did not include WordPress.com order ID' );
}
// Resolve the Promise which will trigger the PayPal button to display the confirmation dialog.
submitData.resolvePayPalOrderPromise( response.paypal_order_id );
// Wait for the PayPal dialog to complete before continuing.
await submitData.payPalApprovalPromise;
// Capture PayPal order information after dialog approval.
const confirmResponse = await payPalJsApproval(
response.order_id.toString(),
response.paypal_order_id
);
if ( 'error' in confirmResponse ) {
if (
confirmResponse.error === 'paypal_ppcp_payment_confirm_no_order' &&
confirmResponse.message
) {
return makeErrorResponse( confirmResponse.message );
}
if (
confirmResponse.error === 'paypal_ppcp_payment_confirm_status_wrong' &&
confirmResponse.message
) {
return makeErrorResponse( confirmResponse.message );
}
return makeErrorResponse( 'Transaction could not be completed' );
}
return makeSuccessResponse( response );
} catch ( error ) {
const errorError = error as Error;
return makeErrorResponse( errorError.message ?? 'PayPal transaction had an unknown error' );
}
}
|