| | import { Elements } from '@stripe/react-stripe-js'; |
| | import { loadStripe } from '@stripe/stripe-js'; |
| | import debugFactory from 'debug'; |
| | import { |
| | useRef, |
| | useEffect, |
| | useCallback, |
| | useState, |
| | useContext, |
| | createContext, |
| | ComponentType, |
| | PropsWithChildren, |
| | } from 'react'; |
| | import type { |
| | Stripe, |
| | StripeError, |
| | SetupIntent, |
| | StripeElementLocale, |
| | StripeCardNumberElement, |
| | StripeCardElement, |
| | } from '@stripe/stripe-js'; |
| |
|
| | const debug = debugFactory( 'calypso-stripe' ); |
| |
|
| | type PaymentDetails = Record< string, unknown >; |
| |
|
| | interface PaymentRequestOptionsItem { |
| | label: string; |
| | amount: number; |
| | } |
| |
|
| | export interface PaymentRequestOptions { |
| | requestPayerName: boolean; |
| | requestPayerPhone: boolean; |
| | requestPayerEmail: boolean; |
| | requestShipping: boolean; |
| | country: string; |
| | currency: string; |
| | displayItems: PaymentRequestOptionsItem[]; |
| | total: PaymentRequestOptionsItem; |
| | } |
| |
|
| | export interface StripeConfiguration { |
| | js_url: string; |
| | public_key: string; |
| | processor_id: string; |
| | } |
| |
|
| | export type ReloadSetupIntentId = () => void; |
| |
|
| | export type StripeLoadingError = undefined | null | Error; |
| |
|
| | export interface StripeData { |
| | stripe: null | Stripe; |
| | stripeConfiguration: null | StripeConfiguration; |
| | isStripeLoading: boolean; |
| | stripeLoadingError: StripeLoadingError; |
| | } |
| |
|
| | export interface StripeSetupIntentIdData { |
| | setupIntentId: StripeSetupIntentId | undefined; |
| | error: StripeLoadingError; |
| | reload: ReloadSetupIntentId; |
| | } |
| |
|
| | export type StripeSetupIntentId = string; |
| |
|
| | export type StripeSetupIntent = SetupIntent; |
| |
|
| | export type StripeAuthenticationResponse = { status?: string; redirect_url?: string }; |
| |
|
| | const StripeContext = createContext< StripeData | undefined >( undefined ); |
| | const StripeSetupIntentContext = createContext< StripeSetupIntentIdData | undefined >( undefined ); |
| |
|
| | export interface UseStripeJs { |
| | stripe: Stripe | null; |
| | isStripeLoading: boolean; |
| | stripeLoadingError: StripeLoadingError; |
| | } |
| |
|
| | export type GetStripeConfigurationArgs = { country?: string; payment_partner?: string }; |
| | export type GetStripeSetupIntentId = () => Promise< { |
| | setup_intent_id: StripeSetupIntentId | undefined; |
| | } >; |
| | export type GetStripeConfiguration = ( |
| | requestArgs: GetStripeConfigurationArgs & { needs_intent?: boolean } |
| | ) => Promise< StripeConfiguration & { setup_intent_id: StripeSetupIntentId | undefined } >; |
| |
|
| | export type StripePaymentRequestHandler = ( event: StripePaymentRequestHandlerEvent ) => void; |
| |
|
| | export interface StripePaymentRequestHandlerEvent { |
| | token?: { |
| | id: string; |
| | object: 'token'; |
| | }; |
| | paymentMethod?: { |
| | id: string; |
| | object: 'payment_method'; |
| | }; |
| | complete: () => void; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export class StripeValidationError extends Error { |
| | code: string | undefined; |
| | messagesByField: Record< string, string[] >; |
| |
|
| | constructor( code: string | undefined, messagesByField: Record< string, string[] > ) { |
| | let firstMessage = code; |
| | if ( Object.keys( messagesByField ).length > 0 ) { |
| | const firstKey = Object.keys( messagesByField )[ 0 ]; |
| | const firstMessages = messagesByField[ firstKey ]; |
| | if ( firstMessages.length > 0 ) { |
| | firstMessage = firstMessages[ 0 ]; |
| | } |
| | } |
| | super( firstMessage ); |
| | this.message = firstMessage || 'Unknown error'; |
| | this.code = code; |
| | this.messagesByField = messagesByField; |
| | } |
| | } |
| |
|
| | export class StripeConfigurationError extends Error {} |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export class StripeSetupIntentError extends Error { |
| | stripeError: Error; |
| |
|
| | constructor( stripeError: Error ) { |
| | super( stripeError.message ); |
| | this.stripeError = stripeError; |
| | this.message = stripeError.message; |
| | } |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | export class StripePaymentMethodError extends Error { |
| | stripeError: Error; |
| |
|
| | constructor( stripeError: Error ) { |
| | super( stripeError.message ); |
| | this.stripeError = stripeError; |
| | this.message = stripeError.message; |
| | } |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export async function createStripePaymentMethod( |
| | stripe: Stripe, |
| | element: StripeCardNumberElement | StripeCardElement, |
| | paymentDetails: PaymentDetails |
| | ): Promise< { id: string } > { |
| | debug( 'creating payment method...', paymentDetails ); |
| | const { paymentMethod, error } = await stripe.createPaymentMethod( { |
| | type: 'card', |
| | card: element, |
| | billing_details: paymentDetails, |
| | } ); |
| | debug( 'payment method creation complete', paymentMethod, error ); |
| | if ( error ) { |
| | |
| | if ( error.type === 'validation_error' ) { |
| | throw new StripeValidationError( |
| | error.code, |
| | getValidationErrorsFromStripeError( error ) || {} |
| | ); |
| | } |
| | throw new Error( error.message ); |
| | } |
| | if ( ! paymentMethod ) { |
| | |
| | throw new Error( 'Unknown error while creating Stripe payment method' ); |
| | } |
| | return paymentMethod; |
| | } |
| |
|
| | export async function createStripeSetupIntent( |
| | stripe: Stripe, |
| | element: StripeCardNumberElement | StripeCardElement, |
| | setupIntentId: StripeSetupIntentId, |
| | paymentDetails: PaymentDetails |
| | ): Promise< StripeSetupIntent > { |
| | |
| | console.warn( |
| | 'createStripeSetupIntent is poorly named and deprecated. Please switch to confirmStripeSetupIntentAndAttachCard instead.' |
| | ); |
| | return confirmStripeSetupIntentAndAttachCard( stripe, element, setupIntentId, paymentDetails ); |
| | } |
| |
|
| | export async function confirmStripeSetupIntentAndAttachCard( |
| | stripe: Stripe, |
| | element: StripeCardNumberElement | StripeCardElement, |
| | setupIntentId: StripeSetupIntentId, |
| | paymentDetails: PaymentDetails |
| | ): Promise< StripeSetupIntent > { |
| | debug( 'creating setup intent...', paymentDetails ); |
| | let stripeResponse; |
| | try { |
| | stripeResponse = await stripe.confirmCardSetup( setupIntentId, { |
| | payment_method: { |
| | card: element, |
| | billing_details: paymentDetails, |
| | }, |
| | } ); |
| | } catch ( error ) { |
| | |
| | throw new StripeSetupIntentError( error as Error ); |
| | } |
| | debug( 'setup intent creation complete', stripeResponse ); |
| | if ( stripeResponse?.error || ! stripeResponse?.setupIntent ) { |
| | |
| | if ( stripeResponse?.error?.type === 'validation_error' ) { |
| | throw new StripeValidationError( |
| | stripeResponse.error.code, |
| | getValidationErrorsFromStripeError( stripeResponse.error ) || {} |
| | ); |
| | } |
| | throw new StripeSetupIntentError( |
| | new Error( |
| | stripeResponse?.error?.message ?? 'Unknown error while submitting Stripe setup intent' |
| | ) |
| | ); |
| | } |
| | return stripeResponse.setupIntent; |
| | } |
| |
|
| | |
| | |
| | export async function confirmStripePaymentIntent( |
| | stripe: Stripe, |
| | paymentIntentClientSecret: string |
| | ): Promise< StripeAuthenticationResponse > { |
| | debug( 'Confirming paymentIntent...', paymentIntentClientSecret ); |
| | const { paymentIntent, error } = await stripe.confirmCardPayment( paymentIntentClientSecret ); |
| | if ( error || ! paymentIntent ) { |
| | debug( 'Confirming paymentIntent failed', error ); |
| | |
| | throw new StripePaymentMethodError( |
| | new Error( error?.message ?? 'Unknown error while confirming Stripe payment intent' ) |
| | ); |
| | } |
| | return paymentIntent; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | function getValidationErrorsFromStripeError( |
| | error: StripeError |
| | ): null | Record< string, string[] > { |
| | if ( error.type !== 'validation_error' || ! error.code ) { |
| | return null; |
| | } |
| | switch ( error.code ) { |
| | case 'incomplete_number': |
| | case 'invalid_number': |
| | return { |
| | card_number: [ error.message ?? error.code ], |
| | }; |
| | case 'incomplete_cvc': |
| | case 'invalid_cvc': |
| | return { |
| | card_cvc: [ error.message ?? error.code ], |
| | }; |
| | case 'incomplete_expiry': |
| | case 'invalid_expiry': |
| | return { |
| | card_expiry: [ error.message ?? error.code ], |
| | }; |
| | } |
| | return null; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | function useStripeJs( |
| | stripeConfiguration: StripeConfiguration | null, |
| | stripeConfigurationError: undefined | Error, |
| | locale: string | undefined = undefined |
| | ): UseStripeJs { |
| | const [ state, setState ] = useState< UseStripeJs >( { |
| | stripe: null, |
| | isStripeLoading: true, |
| | stripeLoadingError: undefined, |
| | } ); |
| | const stripeLocale = getStripeLocaleForLocale( locale ); |
| | useEffect( () => { |
| | let isSubscribed = true; |
| |
|
| | async function loadAndInitStripe() { |
| | if ( stripeConfigurationError ) { |
| | throw stripeConfigurationError; |
| | } |
| | if ( ! stripeConfiguration ) { |
| | return; |
| | } |
| | debug( 'loading stripe...' ); |
| | const stripe = await loadStripe( stripeConfiguration.public_key, { |
| | locale: stripeLocale as StripeElementLocale, |
| | } ); |
| | debug( 'stripe loaded!' ); |
| | if ( isSubscribed ) { |
| | setState( { |
| | stripe, |
| | isStripeLoading: false, |
| | stripeLoadingError: undefined, |
| | } ); |
| | } |
| | } |
| |
|
| | loadAndInitStripe().catch( ( error ) => { |
| | debug( 'error while loading stripe', error ); |
| | if ( isSubscribed ) { |
| | setState( { |
| | stripe: null, |
| | isStripeLoading: false, |
| | stripeLoadingError: error, |
| | } ); |
| | } |
| | } ); |
| |
|
| | return () => { |
| | isSubscribed = false; |
| | }; |
| | }, [ stripeConfigurationError, stripeConfiguration, stripeLocale ] ); |
| | return state; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | function useStripeConfiguration( |
| | fetchStripeConfiguration: GetStripeConfiguration, |
| | requestArgs?: undefined | null | GetStripeConfigurationArgs |
| | ): { |
| | stripeConfiguration: StripeConfiguration | null; |
| | stripeConfigurationError: undefined | Error; |
| | } { |
| | const [ stripeConfigurationError, setStripeConfigurationError ] = useState< undefined | Error >(); |
| | const [ stripeConfiguration, setStripeConfiguration ] = useState< null | StripeConfiguration >( |
| | null |
| | ); |
| | const memoizedRequestArgs = useMemoCompare( requestArgs, areRequestArgsEqual ); |
| |
|
| | useEffect( () => { |
| | debug( 'loading stripe configuration' ); |
| | let isSubscribed = true; |
| | fetchStripeConfiguration( memoizedRequestArgs || {} ) |
| | .then( ( configuration ) => { |
| | if ( ! isSubscribed ) { |
| | return; |
| | } |
| | if ( |
| | ! configuration.js_url || |
| | ! configuration.public_key || |
| | ! configuration.processor_id |
| | ) { |
| | debug( 'invalid stripe configuration; missing some data', configuration ); |
| | throw new StripeConfigurationError( |
| | 'Error loading payment method configuration. Received invalid data from the server.' |
| | ); |
| | } |
| | debug( 'stripe configuration received', configuration ); |
| | setStripeConfiguration( configuration ?? null ); |
| | } ) |
| | .catch( ( error ) => { |
| | setStripeConfigurationError( error ); |
| | } ); |
| | return () => { |
| | isSubscribed = false; |
| | }; |
| | }, [ memoizedRequestArgs, fetchStripeConfiguration ] ); |
| | return { stripeConfiguration, stripeConfigurationError }; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | function useFetchSetupIntentId( |
| | fetchStripeSetupIntentId: GetStripeSetupIntentId, |
| | { isDisabled }: { isDisabled?: boolean } |
| | ): { |
| | setupIntentId: StripeSetupIntentId | undefined; |
| | error: undefined | Error; |
| | reload: ReloadSetupIntentId; |
| | } { |
| | const [ stripeReloadCount, setReloadCount ] = useState< number >( 0 ); |
| | const [ error, setError ] = useState< undefined | Error >(); |
| | const [ setupIntentId, setSetupIntentId ] = useState< undefined | StripeSetupIntentId >(); |
| | const reload = useCallback( () => setReloadCount( ( count ) => count + 1 ), [] ); |
| |
|
| | useEffect( () => { |
| | let isSubscribed = true; |
| | if ( isDisabled ) { |
| | debug( 'not loading stripe setup intent id because it is disabled' ); |
| | return () => { |
| | isSubscribed = false; |
| | }; |
| | } |
| | debug( 'loading stripe setup intent id' ); |
| | fetchStripeSetupIntentId() |
| | .then( ( configuration ) => { |
| | if ( ! isSubscribed ) { |
| | return; |
| | } |
| | if ( ! configuration?.setup_intent_id ) { |
| | debug( 'invalid stripe configuration; missing setup_intent_id', configuration ); |
| | throw new StripeConfigurationError( |
| | 'Error loading new payment method configuration. Received invalid data from the server.' |
| | ); |
| | } |
| | debug( 'stripe configuration received', configuration ); |
| | setSetupIntentId( configuration.setup_intent_id ); |
| | } ) |
| | .catch( ( error ) => { |
| | setError( error ); |
| | } ); |
| | return () => { |
| | isSubscribed = false; |
| | }; |
| | }, [ stripeReloadCount, fetchStripeSetupIntentId, isDisabled ] ); |
| | return { setupIntentId, error, reload }; |
| | } |
| |
|
| | function areRequestArgsEqual( |
| | previous: undefined | null | GetStripeConfigurationArgs, |
| | next: undefined | null | GetStripeConfigurationArgs |
| | ): boolean { |
| | if ( next?.country !== previous?.country ) { |
| | return false; |
| | } |
| | return true; |
| | } |
| |
|
| | export function StripeSetupIntentIdProvider( { |
| | children, |
| | fetchStripeSetupIntentId, |
| | isDisabled, |
| | }: PropsWithChildren< { |
| | fetchStripeSetupIntentId: GetStripeSetupIntentId; |
| | isDisabled?: boolean; |
| | } > ) { |
| | |
| | console.warn( |
| | 'StripeSetupIntentIdProvider creates too many setup intents and is deprecated. Please create the setup intent on the fly when submitting the form. See https://github.com/Automattic/wp-calypso/pull/79881' |
| | ); |
| | const setupIntentData = useFetchSetupIntentId( fetchStripeSetupIntentId, { isDisabled } ); |
| |
|
| | return ( |
| | <StripeSetupIntentContext.Provider value={ setupIntentData }> |
| | { children } |
| | </StripeSetupIntentContext.Provider> |
| | ); |
| | } |
| |
|
| | export function StripeHookProvider( { |
| | children, |
| | fetchStripeConfiguration, |
| | locale, |
| | country, |
| | }: PropsWithChildren< { |
| | fetchStripeConfiguration: GetStripeConfiguration; |
| | locale?: string; |
| | country?: string; |
| | } > ) { |
| | const configurationArgs = { |
| | country, |
| | }; |
| | const { stripeConfiguration, stripeConfigurationError } = useStripeConfiguration( |
| | fetchStripeConfiguration, |
| | configurationArgs |
| | ); |
| | const { stripe, isStripeLoading, stripeLoadingError } = useStripeJs( |
| | stripeConfiguration, |
| | stripeConfigurationError, |
| | locale |
| | ); |
| |
|
| | const stripeData = { |
| | stripe, |
| | stripeConfiguration, |
| | isStripeLoading, |
| | stripeLoadingError, |
| | }; |
| |
|
| | return ( |
| | <Elements stripe={ stripe }> |
| | <StripeContext.Provider value={ stripeData }>{ children }</StripeContext.Provider> |
| | </Elements> |
| | ); |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export function useStripe(): StripeData { |
| | const stripeData = useContext( StripeContext ); |
| | if ( ! stripeData ) { |
| | throw new Error( 'useStripe can only be used inside a StripeHookProvider' ); |
| | } |
| | return stripeData; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export function useStripeSetupIntentId(): StripeSetupIntentIdData { |
| | |
| | console.warn( |
| | 'useStripeSetupIntentId creates too many setup intents and is deprecated. Please create the setup intent on the fly when submitting the form. See https://github.com/Automattic/wp-calypso/pull/79881' |
| | ); |
| | const stripeData = useContext( StripeSetupIntentContext ); |
| | if ( ! stripeData ) { |
| | throw new Error( |
| | 'useStripeSetupIntentId can only be used inside a StripeSetupIntentIdProvider' |
| | ); |
| | } |
| | return stripeData; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | export function withStripeProps< P >( WrappedComponent: ComponentType< P > ) { |
| | return ( props: P ) => { |
| | const stripeData = useStripe(); |
| | const newProps = { ...props, ...stripeData }; |
| | return <WrappedComponent { ...newProps } />; |
| | }; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | function getStripeLocaleForLocale( locale: string | null | undefined ): string { |
| | const stripeSupportedLocales = [ |
| | 'ar', |
| | 'bg', |
| | 'cs', |
| | 'da', |
| | 'de', |
| | 'el', |
| | 'et', |
| | 'en', |
| | 'es', |
| | 'fi', |
| | 'fr', |
| | 'he', |
| | 'id', |
| | 'it', |
| | 'ja', |
| | 'lt', |
| | 'lv', |
| | 'ms', |
| | 'nb', |
| | 'nl', |
| | 'pl', |
| | 'pt', |
| | 'ru', |
| | 'sk', |
| | 'sl', |
| | 'sv', |
| | 'zh', |
| | ]; |
| | if ( ! locale ) { |
| | return 'auto'; |
| | } |
| | if ( locale.toLowerCase() === 'pt-br' ) { |
| | return 'pt-BR'; |
| | } |
| | const stripeLocale = locale.toLowerCase().substring( 0, 2 ); |
| | if ( ! stripeSupportedLocales.includes( stripeLocale ) ) { |
| | return 'auto'; |
| | } |
| | return stripeLocale; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export async function loadStripeLibrary( { |
| | country, |
| | paymentPartner, |
| | locale, |
| | fetchStripeConfiguration, |
| | }: { |
| | country?: string; |
| | paymentPartner?: string; |
| | locale?: string; |
| | fetchStripeConfiguration: GetStripeConfiguration; |
| | } ): Promise< Stripe > { |
| | const stripeConfiguration = await fetchStripeConfiguration( { |
| | country, |
| | payment_partner: paymentPartner, |
| | } ); |
| | if ( |
| | ! stripeConfiguration.js_url || |
| | ! stripeConfiguration.public_key || |
| | ! stripeConfiguration.processor_id |
| | ) { |
| | throw new StripeConfigurationError( |
| | 'Error loading payment method configuration. Received invalid data from the server.' |
| | ); |
| | } |
| |
|
| | const stripeLocale = getStripeLocaleForLocale( locale ); |
| | const stripe = await loadStripe( stripeConfiguration.public_key, { |
| | locale: stripeLocale as StripeElementLocale, |
| | } ); |
| |
|
| | if ( ! stripe ) { |
| | throw new StripeConfigurationError( 'Error loading payment method processing library.' ); |
| | } |
| |
|
| | return stripe; |
| | } |
| |
|
| | |
| | function useMemoCompare< A, B >( |
| | next: B, |
| | compare: ( previous: A | B | undefined, next: B ) => boolean |
| | ): A | B | undefined { |
| | |
| | const previousRef = useRef< undefined | A | B >(); |
| | const previous = previousRef.current; |
| |
|
| | |
| | |
| | const isEqual = compare( previous, next ); |
| |
|
| | |
| | |
| | |
| | useEffect( () => { |
| | if ( ! isEqual ) { |
| | previousRef.current = next; |
| | } |
| | } ); |
| |
|
| | |
| | return isEqual ? previous : next; |
| | } |
| |
|