UNPKG

@getopenpay/openpay-js-react

Version:

Accept payments through OpenPay, right on your site

1,271 lines (1,127 loc) 42.6 kB
/// <reference types="applepayjs" /> /// <reference types="googlepay" /> import { ElementType as ElementType_2 } from '@getopenpay/openpay-js'; import { FC } from 'react'; import { StripeLinkAuthenticationElement } from '@stripe/stripe-js'; import { z } from 'zod'; declare type AffirmFlowCustomParams = { processor?: PaymentProcessor; useRedirectFlow?: boolean; }; declare type AffirmProcessors = { processors: PaymentProcessor[]; isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: AffirmFlowCustomParams) => Promise<void>; }; declare type AfterpayFlowCustomParams = { processor?: PaymentProcessor; useRedirectFlow?: boolean; }; declare type AfterpayProcessors = { processors: PaymentProcessor[]; isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: AfterpayFlowCustomParams) => Promise<void>; }; declare type AirwallexACHFlowParams = { verificationMethod?: 'plaid' | 'micro_deposit'; defaultFieldValues?: DefaultFieldValues; isBusinessAccount?: boolean; }; declare type AirwallexApplePayFlowCustomParams = { overridePaymentRequest?: { amount: Amount; pending?: boolean; label?: string; applePayPaymentRequest?: ApplePayPaymentRequest; }; defaultFieldValues?: DefaultFieldValues; }; declare type AirwallexBACSFlowParams = { verificationMethod?: 'truelayer' | 'micro_deposit'; defaultFieldValues?: DefaultFieldValues; // sortCode?: string; // accountNumber?: string; }; declare type AirwallexEFTFlowParams = { verificationMethod?: 'plaid' | 'micro_deposit'; defaultFieldValues?: DefaultFieldValues; isBusinessAccount?: boolean; }; declare type AirwallexGooglePayFlowCustomParams = { overridePaymentRequest?: { amount: Amount; pending?: boolean; googlePayPaymentRequest?: GooglePayPaymentRequest; }; defaultFieldValues?: DefaultFieldValues; }; declare type AirwallexSEPAFlowParams = { verificationMethod?: 'truelayer' | 'micro_deposit'; defaultFieldValues?: DefaultFieldValues; }; declare type AllCallbacks = { onFocus?: (elementId: string, field: AllFieldNames) => void; onBlur?: ( elementId: string, field: AllFieldNames, extraArgs?: { obfuscatedValue?: string; } ) => void; onChange?: (elementId: string, field: AllFieldNames, errors?: string[]) => void; onLoad?: (totalAmountAtoms?: number, currency?: string) => void; onLoadError?: (message: string) => void; onValidationError?: OnValidationError; onCheckoutStarted?: OnCheckoutStarted; onCheckoutSuccess?: OnCheckoutSuccess; onSetupPaymentMethodSuccess?: OnSetupPaymentMethodSuccess; onCheckoutError?: OnCheckoutError; /** * @deprecated - use `getAvailablePaymentMethods` and `generalSubmit` instead */ onPaymentRequestLoad?: (paymentRequests: PRStatuses) => void; }; declare const AllFieldNames = z.union([FieldNameEnum, PrivateFieldNameEnum]); declare type AllFieldNames = z.infer<typeof AllFieldNames>; /** * Payment requests */ export declare const Amount = z.object({ amountAtom: z.number(), /** * The three-letter ISO 4217 currency code for the payment. */ currency: RequiredString, }); export declare type Amount = z.infer<typeof Amount>; declare type ApplePayFlowCustomParams = { /** * In case of multiple processors available for ApplePay, the processor setting will * determine which processor to use. * If `processor` is not set or is not available, the first available processor will be used * * **Note**: this processor choice is for the whole process of showing PaymentRequest UI, verification and charging. * It won't perform fallback processor charging when payment failed. */ processor?: PaymentProcessor; overridePaymentRequest?: { amount?: Amount; pending?: boolean; label?: string; applePayPaymentRequest?: ApplePayPaymentRequest; }; defaultFieldValues?: DefaultFieldValues; }; declare type ApplePayPaymentRequest = | ((current: ApplePayJS.ApplePayPaymentRequest) => Partial<ApplePayJS.ApplePayPaymentRequest>) | Partial<ApplePayJS.ApplePayPaymentRequest>; export declare type ApplePayProcessors = { processors: PaymentProcessor[]; isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: ApplePayFlowCustomParams) => Promise<void>; }; /** * Styles */ declare const BaseElementsStyle = z.object({ backgroundColor: OptionalString, color: OptionalString, fontFamily: OptionalString, fontSize: OptionalString, fontWeight: OptionalString, margin: OptionalString, padding: OptionalString, letterSpacing: OptionalString, lineHeight: OptionalString, hideIcon: OptionalString, placeholderStyle: z .object({ color: OptionalString, fontSize: OptionalString, fontWeight: OptionalString, fontFamily: OptionalString, letterSpacing: OptionalString, lineHeight: OptionalString, }) .optional(), }); declare type BaseElementsStyle = z.infer<typeof BaseElementsStyle>; declare enum Blockchain { EVM = 'EVM', SOL = 'Solana', } declare type BlockchainNetwork = keyof typeof Blockchain; export declare const CardCvcElement: FC<ElementProps<'card-cvc'>>; declare const CardCvcElementStyle = BaseElementsStyle.extend({ disableAutoFill: OptionalString, placeholder: z.string().optional(), }); export declare const CardElement: FC<ElementProps<'card'>>; declare const CardElementStyle = BaseElementsStyle.extend({ disableAutoFill: OptionalString, placeholder: z .object({ cardNumber: OptionalString, expiry: OptionalString, cvc: OptionalString, }) .optional(), }); export declare const CardExpiryElement: FC<ElementProps<'card-expiry'>>; declare const CardExpiryElementStyle = BaseElementsStyle.extend({ disableAutoFill: OptionalString, placeholder: z.string().optional(), }); export declare const CardNumberElement: FC<ElementProps<'card-number'>>; declare const CardNumberElementStyle = BaseElementsStyle.extend({ disableAutoFill: OptionalString, placeholder: z.string().optional(), /** * The card icon at the start of the card number input field * It won't affect after the icon changed to card brand after the user input the card number */ icon: z .object({ color: z.string().optional(), }) .optional(), }); declare type CCSubmitParams = { paymentRouteId?: string; }; declare type CommonSubmitSettings = { defaultFieldValues?: DefaultFieldValues; }; declare interface CustomerResponse { /** * The unique identifier that represents the customer * @example "1234567890abcdef" */ customerId: string; /** * The external customer reference ID used to tie this customer to a customer in an external system. * @example "1234567890abcdef" */ customerRefId: string | null; /** * The payment methods configured for this customer to make payments with. */ paymentMethods: Omit<PaymentMethodResponse, 'entityId' | 'customer' | 'dateCreated'>[]; /** * The date the customer record was created, represented as a Unix timestamp in seconds. * @example 1716211200 */ dateCreated: number; } declare type CustomInitParams = { // You can put custom params for your init flows here // For stripe link stripeLink?: { /** * The height of the Stripe Link button. By default, the height of the buttons are 44px. * You can override this to specify a custom button height in the range of 40px-55px. * * See more: https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-buttonHeight */ buttonHeight?: number; /** * If this function returns false, the stripe link submit process is aborted. * This can be used for additional pre-submit checks (e.g. additional form validation). * Note that this function must complete within 1 second, or the submission will fail. */ overrideLinkSubmit?: () => Promise<boolean>; /** * By default, the stripe link button is mounted on OJS initialization. * If this value is true, the stripe link is not mounted on init, and should instead be manually mounted. */ doNotMountOnInit?: boolean; /** * If this value is true, the link authentication element is checked for login status silently. * * ⚠️ [**Warning**]: This is a workaround for checking Link authentication status without user gesture. * Stripe don't expose API for this and it's recommended to mount the `linkAuthenticationElement` manually and check the authentication status via `.on('change')` * You can mount the `linkAuthenticationElement` manually by calling `stripeLink.mountLinkAuthenticationElement(selector)` */ silentlyCheckAuthentication?: boolean; /** * This callback is called when the authentication status changes when `silentlyCheckAuthentication` is true, * * ⚠️ [**Warning**]: This is a workaround for checking authentication status without user gesture. * This is working with current version of Stripe element (v3). This is not guaranteed to work with future versions of Stripe element. */ onAuthenticationStatusChange?: (isAuthenticated: boolean) => void; /** * This will be called once the `linkAuthenticationElement` is ready. * This is just a wrapper for `linkAuthenticationElement.once('ready')`. */ onAuthenticationElementReady?: () => void; }; // For stripe klarna stripeKlarna?: { /** * Additional payment data to be passed to stripe.confirmKlarnaPayment * This will be merged with the billing details from the form */ paymentData?: { payment_method?: { billing_details?: { email?: string; name?: string; phone?: string; address?: { line1?: string; line2?: string; city?: string; state?: string; country?: string; postal_code?: string; }; }; }; return_url?: string; setup_future_usage?: 'off_session' | 'on_session'; save_payment_method?: boolean; }; /** * Options to be passed to stripe.confirmKlarnaPayment */ options?: { handleActions?: boolean; }; }; googlePay?: { env: 'demo' | 'prod'; doNotMountOnInit?: boolean; }; applePay?: { env: 'demo' | 'prod'; doNotMountOnInit?: boolean; }; }; declare type CustomStyles = string; declare type DefaultFieldValues = Partial<Record<FieldNameEnum, string>> & { payment_method?: string | SubmitMethod; // This is not coming from checkout setting. TODO: Define a type in future if there are more attrs show_all_prices?: boolean; exclusive_prices?: boolean; price_id_product_mapping?: Record<string, string>; require_zip_code?: boolean; require_full_billing_address?: boolean; require_full_shipping_address?: boolean; }; export declare type DynamicPreview = { amount: Amount | null; isLoading: boolean; error: string | null; }; export declare type ElementProps<T extends ElementType> = { styles?: ElementsStyle<T>; }; declare type ElementsContextValue = { formId: string; formHeight: string; referrer?: string; checkoutSecureToken?: string; registerIframe: (type: ElementType_2, iframe: HTMLIFrameElement) => void; baseUrl: string; }; export declare const ElementsForm: FC<ElementsFormProps>; export declare type ElementsFormChildrenProps = { submit: (params?: CCSubmitParams) => void; submitWith: GeneralSubmit; applePay: ApplePayProcessors; googlePay: GooglePayProcessors; stripeLink: StripeLinkController | null; klarna: KlarnaProcessors | null; affirm: AffirmProcessors | null; afterpay: AfterpayProcessors | null; /** * @deprecated Use applePay and googlePay instead */ airwallex: { /** * @deprecated Use googlePay.startFlow({ processor: 'airwallex' }) instead */ googlePay: InitAirwallexGooglePayFlowResult; /** * @deprecated Use applePay.startFlow({ processor: 'airwallex' }) instead */ applePay: InitAirwallexApplePayFlowResult; }; loop: LoopConfig; loaded: boolean; preview: DynamicPreview; }; export declare type ElementsFormProps = ElementsFormProps_2 & { children: (props: ElementsFormChildrenProps) => JSX.Element; } & AllCallbacks; declare type ElementsFormProps_2 = { className?: string; checkoutSecureToken: string; baseUrl?: string; formTarget?: string; customInitParams?: CustomInitParams; /** * Whether to enable tracing. Defaults to false. * Set to true to opt-in to tracing functionality. */ allowTracing?: boolean; preventNavigationDuringSubmission?: boolean; }; declare type ElementsStyle<T extends ElementType = ElementType> = { card: z.infer<typeof CardElementStyle>; 'card-number': z.infer<typeof CardNumberElementStyle>; 'card-expiry': z.infer<typeof CardExpiryElementStyle>; 'card-cvc': z.infer<typeof CardCvcElementStyle>; 'cde-bridge': z.infer<typeof BaseElementsStyle>; }[T]; declare type ElementType = z.infer<typeof _ElementTypeEnumZod>; declare const _ElementTypeEnumZod = z.enum(['card', 'card-number', 'card-expiry', 'card-cvc', 'cde-bridge']); declare interface ExchangableToken extends Omit<TokenExchangeDetailsResponse, 'exchangeRates'> { wrapsTo?: string; exchange: ExchangeRateDetails; } declare interface ExchangeRateDetails { currency: string; rate: number; updated: number; provider: string; } /** * Expected input fields */ // Supplied by the user export declare enum FieldName { FIRST_NAME = 'firstName', LAST_NAME = 'lastName', PHONE = 'phone', EMAIL = 'email', LINE1 = 'line1', LINE2 = 'line2', LINE3 = 'line3', CITY = 'city', STATE = 'state', COUNTRY = 'country', ZIP_CODE = 'zipCode', SHIPPING_LINE1 = 'shippingAddressLine1', SHIPPING_LINE2 = 'shippingAddressLine2', SHIPPING_LINE3 = 'shippingAddressLine3', SHIPPING_CITY = 'shippingAddressCity', SHIPPING_STATE = 'shippingAddressState', SHIPPING_COUNTRY = 'shippingAddressCountry', SHIPPING_ZIP_CODE = 'shippingAddressZipCode', IS_SHIPPING_SAME_AS_BILLING = 'isShippingSameAsBilling', PROMOTION_CODE = 'promotionCode', IS_BUSINESS_PURCHASE = 'isBusinessPurchase', BUSINESS_NAME = 'businessName', TAX_ID = 'taxId', TAX_ID_TYPE = 'taxIdType', } declare const FieldNameEnum = z.nativeEnum(FieldName); declare type FieldNameEnum = z.infer<typeof FieldNameEnum>; declare interface FormattedError { [key: string]: { _errors: string[] } | string[]; } declare type GeneralSubmit = typeof _generalSubmit; declare const _generalSubmit = async <T extends SubmitMethod>(method: T, settings?: SubmitSettings<T>) => { console.log('generalSubmit', method, settings); }; declare type GooglePayFlowCustomParams = { /** * In case of multiple processors available for GooglePay, the processor setting will * determine which processor to use. * If `processor` is not set or is not available, the first available processor will be used * * **Note**: this processor choice is for the whole process of showing PaymentRequest UI, verification and charging. * It won't perform fallback processor charging when payment failed. */ processor?: PaymentProcessor; overridePaymentRequest?: { amount?: Amount; pending?: boolean; label?: string; googlePayPaymentRequest?: GooglePayPaymentRequest; }; defaultFieldValues?: DefaultFieldValues; }; declare type GooglePayPaymentRequest = | ((current: PaymentDataRequest) => Partial<PaymentDataRequest>) | Partial<PaymentDataRequest>; export declare type GooglePayProcessors = { processors: PaymentProcessor[]; isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: GooglePayFlowCustomParams) => Promise<void>; }; export declare type InitAirwallexApplePayFlowResult = { isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: AirwallexApplePayFlowCustomParams) => Promise<void>; }; export declare type InitAirwallexGooglePayFlowResult = { isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: AirwallexGooglePayFlowCustomParams) => Promise<void>; }; declare interface InitFailedEvent { type: 'initFailed'; message: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any data: Record<string, any>; } declare interface InitializedEvent { entityId: string; } declare type KlarnaFlowCustomParams = { /** * In case of multiple processors available for Klarna, the processor setting will * determine which processor to use. * If `processor` is not set or is not available, the first available processor will be used * * **Note**: this processor choice is for the whole process of showing payment UI, verification and charging. * It won't perform fallback processor charging when payment failed. */ processor?: PaymentProcessor; isAnonymous?: boolean; useRedirectFlow?: boolean; }; declare type KlarnaProcessors = { processors: PaymentProcessor[]; isAvailable: boolean; isLoading: boolean; startFlow: (customParams?: KlarnaFlowCustomParams) => Promise<void>; }; export declare type LoopConfig = | { isAvailable: true; isLoading: boolean; widget: LoopCryptoWidgetProps; config: LoopConnectConfig; } | { isAvailable: false; isLoading: boolean; widget: null; config: null; }; export declare interface LoopConnectConfig { apiToken: string; entityId: string; merchantId?: string; environment?: LoopEnvironment | `${LoopEnvironment}`; customStyles?: CustomStyles; onInitialized?: (detail: InitializedEvent) => void; onInitFailed?: (detail: InitFailedEvent) => void; onWalletChange?: (detail: WalletChangeEvent) => void; onNetworkChange?: (detail: NetworkChangeEvent) => void; } declare type LoopConnectToken = ExchangableToken; declare type LoopCryptoFlowCustomParams = | { customer: Omit<CustomerResponse, 'paymentMethods' | 'merchants' | 'dateCreated'>; paymentMethod: Omit<PaymentMethodResponse, 'customer' | 'dateCreated'>; mode: 'setup' | 'payment' | 'subscription'; success: true; payinId?: string; } | { failureDetails: PayInFailedEvent; // eslint-disable-next-line @typescript-eslint/no-explicit-any debugInfo?: Record<string, any>; success: false; } | undefined; export declare type LoopCryptoWidgetProps = { paymentUsdAmount: number; suggestedAuthorizationUsdAmount: number; minAuthorizationUsdAmount: number; subscriptionRefId?: string; customerRefId?: string; invoiceRefId?: string; allowCustomerToChooseAuth?: boolean; }; export declare enum LoopEnvironment { Local = 'local', Development = 'development', Staging = 'staging', Demo = 'demo', Production = 'production', } declare interface NetworkChangeEvent { id: number; name: string; chain: BlockchainNetwork; } declare type OnCheckoutError = (message: string, errorCode?: string) => void; declare type OnCheckoutStarted = () => void; declare type OnCheckoutSuccess = ( invoiceUrls: string[], subscriptionIds: string[], customerId: string, processorsUsed: string[], paymentMethodId: string ) => void; declare type OnSetupPaymentMethodSuccess = (paymentMethodId: string) => void; declare type OnValidationError = (field: AllFieldNames, errors: string[], elementId?: string) => void; export declare enum PayInFailed { // Create payment method METHOD_CREATION_FAILED = 'methodCreationFailed', INSUFFICIENT_BALANCE = 'insufficientBalance', INSUFFICIENT_AUTHORIZATION = 'insufficientAuthorization', SIGNED_MESSAGE_REQUIRED = 'signedMessageRequired', CUSTOMER_CREATION_FAILED = 'customerCreationFailed', // Create pay-in PAYMENT_FAILED = 'paymentFailed', TRANSACTION_FAILED = 'transactionFailed', } declare interface PayInFailedData { // eslint-disable-next-line @typescript-eslint/no-explicit-any error: Record<string, any> | undefined; } declare interface PayInFailedEvent { type: PayInFailed; message: string; data: PayInFailedData; } declare interface PayinPaymentMethodResponse extends Omit<PaymentMethodResponse, 'merchantId' | 'entityId' | 'dateCreated'> { /** * The status of the payment method */ status: 'ok' | 'insufficient_balance' | 'insufficient_authorization' | 'insufficient_balance_authorization'; } declare interface PayinPayoutDestinationResponse extends Omit<PayoutDestinationResponse, 'merchantId' | 'entityId' | 'isDefault' | 'dateCreated'> {} declare interface PayinResponse { /** * The unique identifier for the payin * @example "8f47c6e9-2b3a-4d5c-9f8e-1a2b3c4d5e6f" */ payinId: string; /** * The unique identifier of the merchant this payin is associated with * @example "67e55044-10b1-426f-9247-bb680e5fe0c8" */ merchantId: string; /** * The amount to be paid, specified in either fiat or crypto based on amountType * @example "100.00" */ amount: string; /** * The type of the amount, either "fiat" or "token" * @example "fiat" */ amountType: 'fiat' | 'token'; /** * The date the payment will take place, represented as a Unix timestamp * @example 1716211200 */ billDate: number; /** * The unique invoice identifier representing this payin transaction * @example "1234567890abcdef" */ invoiceId: string; /** * (Optional) A description or note that provides additional context about this payin. This can be used to help identify or provide details about the payment for internal reference or customer communications. * @example "Payment for Developer plan" */ description: string | null; /** * (Optional) The external invoice ID used to tie this payin to an invoice in an external system * @example "1234567890abcdef" */ externalInvoiceRef: string | null; /** * The type of the payin, either "subscription" or "invoice" * @example "subscription" */ payinType: 'subscription' | 'invoice'; /** * The status of the payin, can be "scheduled", "pending", "completed", or "failed" * @example "scheduled" */ payinStatus: 'scheduled' | 'pending' | 'completed' | 'failed' | 'canceled' | 'uncollectible' | 'draft'; /** * The transaction details for the payin */ transaction: PayinTransactionResponse | null; /** * The payment method used for this payin */ paymentMethod: PayinPaymentMethodResponse; /** * The payout destination used for this payin */ payoutDestination: PayinPayoutDestinationResponse; /** * The date the payin record was created, represented as a Unix timestamp in seconds. * @example 1716211200 */ dateCreated: number; } export declare enum PayInState { IDLE = 'idle', CONFIRMING_BALANCE = 'confirmingBalance', CONFIRMING_AUTHORIZATION = 'confirmingAuthorization', UPDATING_AUTHORIZATION = 'updatingAuthorization', SIGNING_MESSAGE = 'signingMessage', CREATING_CUSTOMER = 'creatingCustomer', CREATING_PAYMENT_METHOD = 'creatingPaymentMethod', /** * @deprecated State CREATING_PAYMENT is used when a payment is awaiting creation confirmation */ PROCESSING_PAYMENT = 'processingPayment', CREATING_PAYMENT = 'creatingPayment', CONFIRMING_PAYMENT = 'confirmingPayment', COMPLETE = 'complete', AUTHORIZED = 'authorized', } export declare type PayInStateChangeEvent = { [K in keyof PayInStateDataMap]: { state: K; message: string; data: PayInStateDataMap[K]; }; }[keyof PayInStateDataMap]; declare interface PayInStateChangeEventAuthorized {} declare interface PayInStateChangeEventComplete extends PayinResponse {} declare interface PayInStateChangeEventConfirmingAuthorization { token: LoopConnectToken; minimumAuthorization: string | undefined; contractAddress: string; walletAddress: string; chain: BlockchainNetwork; networkName: string; } declare interface PayInStateChangeEventConfirmingBalance { token: LoopConnectToken; amount: string; walletAddress: string; chain: BlockchainNetwork; networkName: string; } declare interface PayInStateChangeEventConfirmingPayment extends PayinResponse {} declare interface PayInStateChangeEventCreatingCustomer { token: LoopConnectToken; walletAddress: string; chain: BlockchainNetwork; networkName: string; } declare interface PayInStateChangeEventCreatingPayment { token: LoopConnectToken; amount: string; walletAddress: string; chain: BlockchainNetwork; networkName: string; customerId: string; paymentMethodId: string; } declare interface PayInStateChangeEventCreatingPaymentMethod { token: LoopConnectToken; walletAddress: string; chain: BlockchainNetwork; networkName: string; customerId: string; customerRefId?: string; } declare type PayInStateChangeEventIdle = unknown; /** * @deprecated Use PayInStateChangeEventCreatingPayment for data */ declare interface PayInStateChangeEventProcessingPayment { token: LoopConnectToken; amount: string; walletAddress: string; chain: BlockchainNetwork; networkName: string; customerId: string; paymentMethodId: string; } declare interface PayInStateChangeEventSigningMessage { walletAddress: string; chain: BlockchainNetwork; networkName: string; networkId: number; } declare interface PayInStateChangeEventUpdatingAuthorization { token: LoopConnectToken; suggestedAuthorization: string | undefined; contractAddress: string; walletAddress: string; chain: BlockchainNetwork; networkName: string; } declare type PayInStateDataMap = { [PayInState.IDLE]: PayInStateChangeEventIdle; [PayInState.CONFIRMING_BALANCE]: PayInStateChangeEventConfirmingBalance; [PayInState.CONFIRMING_AUTHORIZATION]: PayInStateChangeEventConfirmingAuthorization; [PayInState.UPDATING_AUTHORIZATION]: PayInStateChangeEventUpdatingAuthorization; [PayInState.SIGNING_MESSAGE]: PayInStateChangeEventSigningMessage; [PayInState.CREATING_CUSTOMER]: PayInStateChangeEventCreatingCustomer; [PayInState.CREATING_PAYMENT_METHOD]: PayInStateChangeEventCreatingPaymentMethod; [PayInState.PROCESSING_PAYMENT]: PayInStateChangeEventProcessingPayment; [PayInState.CREATING_PAYMENT]: PayInStateChangeEventCreatingPayment; [PayInState.CONFIRMING_PAYMENT]: PayInStateChangeEventConfirmingPayment; [PayInState.COMPLETE]: PayInStateChangeEventComplete; [PayInState.AUTHORIZED]: PayInStateChangeEventAuthorized; }; declare interface PayinTransactionResponse { /** * The transaction id generated by the blockchain network when the transaction is processed * @example "0xcfdfbb523c079e47e9a17ba236fa978257d4331e96ec43997e974b97522047fe" */ transactionId: string; /** * The URL to view this transaction in a blockchain explorer. The specific explorer URL depends on the blockchain network the transaction was processed on * @example "https://etherscan.io/tx/0xcfdfbb523c079e47e9a17ba236fa978257d4331e96ec43997e974b97522047fe" */ transactionUrl: string; /** * The actual token amount that was transferred including all decimal places. For example - an amount of 1.99 USDC will result in a `amountTransferred` of "1990000" * @example "1990000" */ amountTransferred: string | null; /** * The exchange rate that was applied when the payment was processed on the blockchain */ exchangeRate: PaymentMethodTokenExchangeRate | null; } declare type PaymentDataRequest = google.payments.api.PaymentDataRequest; declare interface PaymentMethodPreAuthorization { /** * The balance of the payment method formatted in the token amount * @example "100" */ balance: string; /** * The authorization amount of the payment method formatted in the token amount * @example "49.9" */ authorization: string; } export declare interface PaymentMethodResponse { /** * The unique identifier for the payment method * @example "1234567890abcdef" */ paymentMethodId: string; /** * The unique identifier of the merchant this payment method is associated with * @example "67e55044-10b1-426f-9247-bb680e5fe0c8" */ merchantId: string; /** * The name of the payment method * @example "My Crypto Wallet" */ paymentMethodName: string; /** * The customers that are associated with the payment method */ customer: Omit<CustomerResponse, 'paymentMethods' | 'merchants' | 'dateCreated'>; /** * The blockchain network ID the payment method is associated with * @example 1 */ networkId: number; /** * The blockchain wallet address where payments will be sent from * @example "0x1234567890abcdef" */ walletAddress: string; /** * Whether the payment method is the default payment method for wallet address * @example true */ isDefault: boolean; /** * The token associated with the payment method */ token: PaymentMethodToken; /** * The status of the payment method, including the wallet's balance and authorization status */ preAuthorization: PaymentMethodPreAuthorization | null; /** * The date the payment method record was created, represented as a Unix timestamp in seconds. * @example 1716211200 */ dateCreated: number; } declare interface PaymentMethodToken extends Omit<TokenResponse, 'networkId'> { /** * The exchange rate of the token */ exchangeRates: PaymentMethodTokenExchangeRate[]; } declare interface PaymentMethodTokenExchangeRate { /** * The currency code. Only "USD" is supported at this time. * @example "USD" */ currency: string; /** * The price of the token in the specified currency code. Accurate to 4 decimal places, e.g. a price of "1.9900" represents $1.99 * @example "10000" */ price: string; /** * The Unix timestamp (in seconds) when this exchange rate was last updated * @example 1715731200 */ timestamp: number; } declare const PaymentProcessor = z.enum(['stripe', 'airwallex', 'authorize_net', 'adyen', 'paypal', 'pockyt', 'loop']); declare type PaymentProcessor = z.infer<typeof PaymentProcessor>; declare const PaymentRequestProvider = z.enum(['apple_pay', 'google_pay']); declare type PaymentRequestProvider = z.infer<typeof PaymentRequestProvider>; export declare type PaymentRequestStartParams = { overridePaymentRequest?: { amount?: Amount; pending?: boolean; label?: string; applePayPaymentRequest?: ApplePayPaymentRequest; }; }; export declare type PaymentRequestStatus = { isLoading: boolean; isAvailable: boolean; startFlow: (params?: PaymentRequestStartParams) => Promise<void>; }; declare interface PayoutDestinationResponse { /** * The unique identifier for the payout destination * @example "1234567890abcdef" */ payoutDestinationId: string; /** * The merchant ID associated with this payout destination * @example "1234567890abcdef" */ merchantId: string; /** * The blockchain network ID the payout destination is associated with * @example 1 */ networkId: number; /** * The blockchain wallet address where payments will be sent. Must be a valid address for the specified network. * @example "0x1234567890abcdef" */ walletAddress: string; /** * Whether the payout destination is the default payout destination for the merchant. * @example true */ isDefault: boolean; /** * The date the payout destination record was created, represented as a Unix timestamp in seconds. * @example 1716211200 */ dateCreated: number; } declare type PaypalFlowCustomParams = { isAnonymous?: boolean; useRedirectFlow?: boolean; }; declare type ProcessorSpecificSubmitSettings<T extends SubmitMethod = SubmitMethod> = { [SubmitMethods.card]: CCSubmitParams; [SubmitMethods.pockytPaypal]: { useRedirectFlow?: boolean }; [SubmitMethods.applePay]: ApplePayFlowCustomParams; [SubmitMethods.googlePay]: GooglePayFlowCustomParams; [SubmitMethods.loopCrypto]: LoopCryptoFlowCustomParams; [SubmitMethods.paypal]: PaypalFlowCustomParams; [SubmitMethods.klarna]: KlarnaFlowCustomParams; [SubmitMethods.affirm]: AffirmFlowCustomParams; [SubmitMethods.afterpay]: AfterpayFlowCustomParams; [SubmitMethods.stripeLink]: unknown; // TODO: The following methods are deprecated and will be removed in the future. // Use googlePay/applePay instead [SubmitMethods.airwallexGooglePay]: GooglePayFlowCustomParams; [SubmitMethods.airwallexApplePay]: ApplePayFlowCustomParams; [SubmitMethods.authorizenetGooglePay]: GooglePayFlowCustomParams; [SubmitMethods.authorizenetApplePay]: ApplePayFlowCustomParams; [SubmitMethods.adyenGooglePay]: GooglePayFlowCustomParams; [SubmitMethods.adyenApplePay]: ApplePayFlowCustomParams; [SubmitMethods.airwallexACH]: AirwallexACHFlowParams; [SubmitMethods.airwallexEFT]: AirwallexEFTFlowParams; [SubmitMethods.airwallexBACS]: AirwallexBACSFlowParams; [SubmitMethods.airwallexSEPA]: AirwallexSEPAFlowParams; }[T]; declare type PRStatuses = Record<PaymentRequestProvider, PaymentRequestStatus>; declare const RequiredFormFields = z.object({ [FieldName.EMAIL]: RequiredString.email({ message: 'Please enter a valid email address' }), [FieldName.FIRST_NAME]: RequiredString, [FieldName.LAST_NAME]: RequiredString, [FieldName.PHONE]: OptionalString, [FieldName.PROMOTION_CODE]: OptionalString, [FieldName.LINE1]: OptionalString, [FieldName.LINE2]: OptionalString, [FieldName.LINE3]: OptionalString, [FieldName.CITY]: OptionalString, [FieldName.STATE]: OptionalString, [FieldName.COUNTRY]: RequiredString, [FieldName.ZIP_CODE]: OptionalString, [FieldName.IS_SHIPPING_SAME_AS_BILLING]: z.custom<boolean>().optional().default(true), [FieldName.SHIPPING_LINE1]: OptionalString, [FieldName.SHIPPING_LINE2]: OptionalString, [FieldName.SHIPPING_LINE3]: OptionalString, [FieldName.SHIPPING_CITY]: OptionalString, [FieldName.SHIPPING_STATE]: OptionalString, [FieldName.SHIPPING_COUNTRY]: OptionalString, [FieldName.SHIPPING_ZIP_CODE]: OptionalString, [FieldName.BUSINESS_NAME]: OptionalString, [FieldName.TAX_ID]: OptionalString, [FieldName.TAX_ID_TYPE]: OptionalString, }); declare type RequiredFormFields = z.infer<typeof RequiredFormFields>; export declare type StripeLinkController = { mountButton: (selector?: string) => void; dismountButton: () => void; waitForButtonToMount: () => Promise<HTMLElement>; mountLinkAuthenticationElement: (selector: string) => StripeLinkAuthenticationElement; }; declare const SubmitMethod = z.nativeEnum(SubmitMethods); declare type SubmitMethod = z.infer<typeof SubmitMethod>; export declare enum SubmitMethods { card = 'card', pockytPaypal = 'pockyt-paypal', applePay = 'apple-pay', googlePay = 'google-pay', loopCrypto = 'loop-crypto', paypal = 'paypal', klarna = 'klarna', affirm = 'affirm', afterpay = 'afterpay', /** * This submit method only for Available payment methods. * Manual submission for StripeLink is not available */ stripeLink = 'stripe-link', // TODO: The following methods are deprecated and will be removed in the future. /** * @deprecated Use googlePay instead */ airwallexGooglePay = 'airwallex-google-pay', /** * @deprecated Use applePay instead */ airwallexApplePay = 'airwallex-apple-pay', /** * @deprecated Use googlePay instead */ authorizenetGooglePay = 'authorizenet-google-pay', /** * @deprecated Use applePay instead */ authorizenetApplePay = 'authorizenet-apple-pay', /** * @deprecated Use googlePay instead */ adyenGooglePay = 'adyen-google-pay', /** * @deprecated Use applePay instead */ adyenApplePay = 'adyen-apple-pay', // DD airwallexACH = 'airwallex-ach', airwallexEFT = 'airwallex-eft', airwallexBACS = 'airwallex-bacs', airwallexSEPA = 'airwallex-sepa', } export declare type SubmitSettings<T extends SubmitMethod = SubmitMethod> = ProcessorSpecificSubmitSettings<T> & CommonSubmitSettings; declare interface TokenExchangeDetailsResponse { name: string; logoUrl: string; symbol: string; decimals: number; address: string; networkId: number; exchangeRates: ExchangeRateDetails[]; } declare interface TokenResponse { /** * The unique identifier for the token used by the payment type. * @example "123e4567-e89b-12d3-a456-426614174000" */ tokenId: string; /** * The blockchain network ID the token is associated with * @example 1 */ networkId: number; /** * The token symbol that identifies the token on the blockchain network * @example "USDC" */ symbol: string; /** * The token contract address for the payment type * @example "0x1234567890abcdef" */ address: string; /** * The number of decimal places used to represent token amounts * @example 6 */ decimals: number; } export declare const useOpenPayElements: () => ElementsContextValue; /** * Validates the non-CDE (non-sensitive) form fields for credit card flows */ export declare const validateNonCdeFormFields = ( nonCdeFormInputs: Record<string, unknown>, onValidationError: OnValidationError, defaultFieldValues: DefaultFieldValues = {} ): RequiredFormFields => { // Apply default field values if (defaultFieldValues) { log__(`Received default field values: ${JSON.stringify(defaultFieldValues)}`); const keys = Object.keys(defaultFieldValues); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = (defaultFieldValues as Record<string, unknown>)[key]; if (!nonCdeFormInputs[key]) { nonCdeFormInputs[key] = value; } } } nonCdeFormInputs[FieldName.IS_SHIPPING_SAME_AS_BILLING] = !!nonCdeFormInputs[FieldName.IS_SHIPPING_SAME_AS_BILLING]; if (nonCdeFormInputs[FieldName.IS_SHIPPING_SAME_AS_BILLING]) { nonCdeFormInputs[FieldName.SHIPPING_LINE1] = nonCdeFormInputs[FieldName.LINE1]; nonCdeFormInputs[FieldName.SHIPPING_LINE2] = nonCdeFormInputs[FieldName.LINE2]; nonCdeFormInputs[FieldName.SHIPPING_LINE3] = nonCdeFormInputs[FieldName.LINE3]; nonCdeFormInputs[FieldName.SHIPPING_CITY] = nonCdeFormInputs[FieldName.CITY]; nonCdeFormInputs[FieldName.SHIPPING_STATE] = nonCdeFormInputs[FieldName.STATE]; nonCdeFormInputs[FieldName.SHIPPING_COUNTRY] = nonCdeFormInputs[FieldName.COUNTRY]; nonCdeFormInputs[FieldName.SHIPPING_ZIP_CODE] = nonCdeFormInputs[FieldName.ZIP_CODE]; } // Create dynamic schema based on requirements const validationSchema = createDynamicValidationSchema(defaultFieldValues, nonCdeFormInputs); // Perform single validation with the dynamic schema const result = validationSchema.safeParse(nonCdeFormInputs); if (!result.success) { const formatted = result.error.format(); const issues = extractIssuesPerField(formatted as FormattedError); const issueKeys = Object.keys(issues); for (let i = 0; i < issueKeys.length; i++) { const fieldName = issueKeys[i]; const errors = (issues as Record<string, string[]>)[fieldName]; onValidationError(fieldName as FieldName, errors, fieldName); } err__('Got validation errors in non-CDE form fields', issues); throw new Error('Almost there! Just a few things highlighted above to fix before you can submit.'); } return result.data as RequiredFormFields; }; declare interface WalletChangeEvent { address: string; ens: string | undefined; } export { }