File size: 1,530 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
import { useContext } from 'react';
import {
	PaymentProcessorFunction,
	PaymentProcessorResponseData,
	PaymentProcessorSuccess,
	PaymentProcessorRedirect,
	PaymentProcessorError,
	PaymentProcessorResponseType,
} from '../types';
import { PaymentMethodProviderContext } from './payment-method-provider-context';

export function usePaymentProcessor( key: string ): PaymentProcessorFunction {
	const { paymentProcessors } = useContext( PaymentMethodProviderContext );
	if ( ! paymentProcessors[ key ] ) {
		throw new Error( `No payment processor found with key: ${ key }` );
	}
	return paymentProcessors[ key ];
}

export function usePaymentProcessors(): Record< string, PaymentProcessorFunction > {
	const { paymentProcessors } = useContext( PaymentMethodProviderContext );
	return paymentProcessors;
}

export function makeErrorResponse( errorMessage: string ): PaymentProcessorError {
	return { type: PaymentProcessorResponseType.ERROR, payload: errorMessage };
}

export function isErrorResponse( value: unknown ): boolean {
	return (
		!! value &&
		typeof value === 'object' &&
		'type' in value &&
		value.type === PaymentProcessorResponseType.ERROR &&
		'payload' in value
	);
}

export function makeSuccessResponse(
	transaction: PaymentProcessorResponseData
): PaymentProcessorSuccess {
	return { type: PaymentProcessorResponseType.SUCCESS, payload: transaction };
}

export function makeRedirectResponse( url: string ): PaymentProcessorRedirect {
	return { type: PaymentProcessorResponseType.REDIRECT, payload: url };
}