File size: 4,634 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
import { useI18n } from '@wordpress/react-i18n';
import debugFactory from 'debug';
import { useCallback, useMemo, useState } from 'react';
import InvalidPaymentProcessorResponseError from '../lib/invalid-payment-processor-response-error';
import { usePaymentProcessor, useTransactionStatus } from '../public-api';
import {
	PaymentProcessorResponse,
	PaymentProcessorResponseType,
	SetTransactionComplete,
	SetTransactionRedirecting,
	ProcessPayment,
	SetTransactionError,
} from '../types';

const debug = debugFactory( 'composite-checkout:use-process-payment' );

export default function useProcessPayment( paymentProcessorId: string ): ProcessPayment {
	const { setTransactionPending } = useTransactionStatus();
	const handlePaymentProcessorPromise = useHandlePaymentProcessorResponse();
	const processor = usePaymentProcessor( paymentProcessorId );

	return useCallback(
		async ( submitData ) => {
			debug( 'beginning payment processor onClick handler' );
			setTransactionPending();
			debug( 'calling payment processor function', paymentProcessorId );
			const response = processor( submitData );
			return handlePaymentProcessorPromise( paymentProcessorId, response );
		},
		[ paymentProcessorId, handlePaymentProcessorPromise, processor, setTransactionPending ]
	);
}

export function useHandlePaymentProcessorResponse() {
	const { __ } = useI18n();
	const redirectErrorMessage = useMemo(
		() =>
			__(
				'An error occurred while redirecting to the payment partner. Please try again or contact support.'
			),
		[ __ ]
	);
	const { setTransactionComplete, setTransactionRedirecting, setTransactionError } =
		useTransactionStatus();

	// processPayment may throw an error, but because it's an async function,
	// that error will not trigger any React error boundaries around this
	// component (error boundaries only catch errors that occur during render).
	// Since we want to know about processing errors, we can cause an error to
	// occur during render of this button if processPayment throws an error using
	// the below technique. See
	// https://github.com/facebook/react/issues/14981#issuecomment-468460187
	const [ , setErrorState ] = useState();

	return useCallback(
		async (
			paymentProcessorId: string,
			processorPromise: Promise< PaymentProcessorResponse >
		): Promise< PaymentProcessorResponse > => {
			return processorPromise
				.then( ( response ) =>
					handlePaymentProcessorResponse( response, paymentProcessorId, redirectErrorMessage, {
						setTransactionRedirecting,
						setTransactionComplete,
						setTransactionError,
					} )
				)
				.catch( ( error: Error ) => {
					setTransactionError( error.message );
					// See note above about transforming an async error into a render-time error
					setErrorState( () => {
						throw error;
					} );
					throw error;
				} );
		},
		[ redirectErrorMessage, setTransactionError, setTransactionComplete, setTransactionRedirecting ]
	);
}

async function handlePaymentProcessorResponse(
	rawResponse: unknown,
	paymentProcessorId: string,
	redirectErrorMessage: string,
	{
		setTransactionRedirecting,
		setTransactionComplete,
		setTransactionError,
	}: {
		setTransactionRedirecting: SetTransactionRedirecting;
		setTransactionComplete: SetTransactionComplete;
		setTransactionError: SetTransactionError;
	}
): Promise< PaymentProcessorResponse > {
	debug( 'payment processor function response', rawResponse );
	const isValid = validateProcessorResponse( rawResponse );
	if ( ! isValid ) {
		throw new InvalidPaymentProcessorResponseError( paymentProcessorId );
	}
	const processorResponse = rawResponse as PaymentProcessorResponse;
	if ( processorResponse.type === PaymentProcessorResponseType.ERROR ) {
		if ( ! processorResponse.payload ) {
			processorResponse.payload = 'Unknown transaction failure';
		}
		setTransactionError( processorResponse.payload );
		return processorResponse;
	}
	if ( processorResponse.type === PaymentProcessorResponseType.REDIRECT ) {
		if ( ! processorResponse.payload ) {
			throw new Error( redirectErrorMessage );
		}
		setTransactionRedirecting( processorResponse.payload );
		return processorResponse;
	}
	if ( processorResponse.type === PaymentProcessorResponseType.SUCCESS ) {
		setTransactionComplete( processorResponse.payload );
		return processorResponse;
	}
	throw new InvalidPaymentProcessorResponseError( paymentProcessorId );
}

function validateProcessorResponse( response: unknown ): response is PaymentProcessorResponse {
	const processorResponse = response as PaymentProcessorResponse;
	if ( ! processorResponse || ! processorResponse.type ) {
		return false;
	}
	return true;
}