import {z} from 'zod' export type PaymentSessionsSessionData = string; export type PaymentSessionsAmount = number; export type PaymentSessionCurrency = string; export type PaymentSessionPaymentType = 'Regular' | 'Recurring' | 'MOTO' | 'Installment' | 'Unscheduled'; export type Address = {address_line1?: string | undefined, address_line2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, country?: string | undefined}; export type PaymentInterfacesPhoneNumber = {country_code?: string | undefined, number?: string | undefined}; export type PaymentSessionBilling = {address: Address, phone?: PaymentInterfacesPhoneNumber | undefined}; export type PaymentSessionsBillingDescriptor = {name: string, city: string, reference?: string | undefined}; export type PaymentInterfacesReference = string; export type PaymentInterfacesCustomerSummary = {registration_date?: string | undefined, first_transaction_date?: string | undefined, last_payment_date?: string | undefined, total_order_count?: number | undefined, last_payment_amount?: number | undefined, is_premium_customer?: boolean | undefined, is_returning_customer?: boolean | undefined, lifetime_value?: number | undefined}; export type PaymentSessionCustomer = {email?: string | undefined, name?: string | undefined, id?: string | undefined, phone?: PaymentInterfacesPhoneNumber | undefined, tax_number?: string | undefined, summary?: PaymentInterfacesCustomerSummary | undefined}; export type PaymentSessionShipping = {address?: Address | undefined, phone?: PaymentInterfacesPhoneNumber | undefined}; export type PaymentInterfacesRecipient = {dob?: string | undefined, account_number?: string | undefined, address?: Address | undefined, first_name?: string | undefined, last_name?: string | undefined}; export type PaymentInterfacesProcessingAirlinePassengerData = {first_name?: string | undefined, last_name?: string | undefined, date_of_birth?: string | undefined, address?: ({country?: string | undefined}) | undefined}; export type PaymentInterfacesProcessingAirlineData = Array<{ticket?: ({number?: string | undefined, issue_date?: string | undefined, issuing_carrier_code?: string | undefined, travel_package_indicator?: string | undefined, travel_agency_name?: string | undefined, travel_agency_code?: string | undefined}) | undefined, passenger?: (Array | PaymentInterfacesProcessingAirlinePassengerData) | undefined, flight_leg_details?: (Array<{flight_number?: string | undefined, carrier_code?: string | undefined, class_of_travelling?: string | undefined, departure_airport?: string | undefined, departure_date?: string | undefined, departure_time?: string | undefined, arrival_airport?: string | undefined, stop_over_code?: string | undefined, fare_basis_code?: string | undefined}>) | undefined}>; export type PaymentInterfacesProcessingAccommodationData = Array<{name?: string | undefined, booking_reference?: string | undefined, check_in_date?: string | undefined, check_out_date?: string | undefined, address?: ({address_line1?: string | undefined, zip?: string | undefined}) | undefined, state?: string | undefined, country?: string | undefined, city?: string | undefined, number_of_rooms?: number | undefined, guests?: (Array<{first_name?: string | undefined, last_name?: string | undefined, date_of_birth?: string | undefined}>) | undefined, room?: (Array<{rate?: string | undefined, number_of_nights_at_room_rate?: string | undefined}>) | undefined}>; export type PaymentInterfacesPanPreference = 'fpan' | 'dpan'; export type PaymentInterfacesProvisionNetworkToken = boolean; export type PaymentInterfacesProcessingAggregator = {sub_merchant_id?: string | undefined, aggregator_id_visa?: string | undefined, aggregator_id_mc?: string | undefined}; export type PaymentInterfacesProcessing = {aft?: boolean | undefined, discount_amount?: number | undefined, shipping_amount?: number | undefined, tax_amount?: number | undefined, invoice_id?: string | undefined, brand_name?: string | undefined, locale?: string | undefined, partner_customer_risk_data?: ({key?: string | undefined, value?: string | undefined}) | undefined, custom_payment_method_ids?: Array | undefined, airline_data?: PaymentInterfacesProcessingAirlineData | undefined, accommodation_data?: PaymentInterfacesProcessingAccommodationData | undefined, order_id?: string | undefined, surcharge_amount?: number | undefined, duty_amount?: number | undefined, shipping_tax_amount?: number | undefined, affiliate_id?: string | undefined, affiliate_url?: string | undefined, purchase_country?: string | undefined, merchant_initiated_reason?: ('Delayed_charge' | 'Resubmission' | 'No_show' | 'Reauthorization') | undefined, campaign_id?: number | undefined, original_order_amount?: number | undefined, receipt_id?: string | undefined, merchant_callback_url?: string | undefined, line_of_business?: string | undefined, pan_preference?: PaymentInterfacesPanPreference | undefined, provision_network_token?: PaymentInterfacesProvisionNetworkToken | undefined, reconciliation_id?: string | undefined, aggregator?: PaymentInterfacesProcessingAggregator | undefined}; export type Purpose = 'donations' | 'education' | 'emergency_need' | 'expatriation' | 'family_support' | 'financial_services' | 'gifts' | 'income' | 'insurance' | 'investment' | 'it_services' | 'leisure' | 'loan_payment' | 'medical_treatment' | 'other' | 'pension' | 'royalties' | 'savings' | 'travel_and_tourism'; export type PaymentSessionProcessingChannelId = string; export type PaymentSessionsItems = Array<{reference?: string | undefined, commodity_code?: string | undefined, unit_of_measure?: string | undefined, total_amount?: number | undefined, tax_amount?: number | undefined, discount_amount?: number | undefined, url?: string | undefined, image_url?: string | undefined, name: string, quantity: number, unit_price: number}>; export type PaymentSessionsSuccessUrl = string; export type PaymentSessionsFailureUrl = string; export type PaymentSessionMetadata = Record; export type PaymentSessions3DSAccountInfo = {purchase_count?: number | undefined, account_age?: ('no_account' | 'created_during_transaction' | 'less_than_thirty_days' | 'thirty_to_sixty_days' | 'more_than_sixty_days') | undefined, add_card_attempts?: number | undefined, shipping_address_age?: ('this_transaction' | 'less_than_thirty_days' | 'thirty_to_sixty_days' | 'more_than_sixty_days') | undefined, account_name_matches_shipping_name?: boolean | undefined, suspicious_account_activity?: boolean | undefined, transactions_today?: number | undefined, authentication_method?: ('no_authentication' | 'own_credentials' | 'federated_id' | 'issuer_credentials' | 'third_party_authentication' | 'fido') | undefined, cardholder_account_age_indicator?: ('no_account' | 'this_transaction' | 'less_than_thirty_days' | 'thirty_to_sixty_days' | 'more_than_sixty_days') | undefined, account_change?: string | undefined, account_change_indicator?: ('this_transaction' | 'less_than_thirty_days' | 'thirty_to_sixty_days' | 'more_than_sixty_days') | undefined, account_date?: string | undefined, account_password_change?: string | undefined, account_password_change_indicator?: ('no_change' | 'this_transaction' | 'less_than_thirty_days' | 'thirty_to_sixty_days' | 'more_than_sixty_days') | undefined, transactions_per_year?: number | undefined, payment_account_age?: string | undefined, shipping_address_usage?: string | undefined, account_type?: ('not_applicable' | 'credit' | 'debit') | undefined, account_id?: string | undefined}; export type PaymentSessions3DS = {enabled: 'false', challenge_indicator?: ('no_preference' | 'no_challenge_requested' | 'challenge_requested' | 'challenge_requested_mandate') | undefined, allow_upgrade?: boolean | undefined, exemption?: ('low_value' | 'trusted_listing' | 'trusted_listing_prompt' | 'transaction_risk_assessment' | '3ds_outage' | 'sca_delegation' | 'out_of_sca_scope' | 'low_risk_program' | 'recurring_operation' | 'data_share' | 'other') | undefined} | {enabled: 'true', challenge_indicator?: ('no_preference' | 'no_challenge_requested' | 'challenge_requested' | 'challenge_requested_mandate') | undefined, attempt_n3d?: boolean | undefined, exemption?: ('low_value' | 'trusted_listing' | 'trusted_listing_prompt' | 'transaction_risk_assessment' | 'data_share') | undefined, account_info?: PaymentSessions3DSAccountInfo | undefined} | {enabled: true, eci: string, cryptogram: string, xid: string, version: string, exemption?: ('low_value' | 'secure_corporate_payment' | 'trusted_listing' | 'transaction_risk_assessment' | '3ds_outage' | 'sca_delegation' | 'out_of_sca_scope' | 'other' | 'low_risk_program' | 'recurring_operation') | undefined}; export type PaymentInterfacesSender = Record; export type PaymentSessionCaptureFlag = boolean; export type PaymentSessionCaptureOn = string; export type PaymentSessionPaymentPlanRecurring = {amount_variability?: ('Fixed' | 'Variable') | undefined, days_between_payments?: number | undefined, total_number_of_payments?: number | undefined, current_payment_number?: number | undefined, expiry?: string | undefined, name?: string | undefined, start_date?: string | undefined, amount?: number | undefined}; export type CreateAndSubmitPaymentSessionsRequest = {session_data: PaymentSessionsSessionData, amount: PaymentSessionsAmount, currency: PaymentSessionCurrency, payment_type?: PaymentSessionPaymentType | undefined, authorization_type?: ('Final' | 'Estimated') | undefined, billing: PaymentSessionBilling, billing_descriptor?: PaymentSessionsBillingDescriptor | undefined, reference?: PaymentInterfacesReference | undefined, description?: string | undefined, customer?: PaymentSessionCustomer | undefined, shipping?: PaymentSessionShipping | undefined, recipient?: PaymentInterfacesRecipient | undefined, processing?: PaymentInterfacesProcessing | undefined, instruction?: ({purpose?: Purpose | undefined}) | undefined, processing_channel_id?: PaymentSessionProcessingChannelId | undefined, items?: PaymentSessionsItems | undefined, amount_allocations?: (Array<{id: string, amount: number, reference?: string | undefined, commission?: ({amount?: number | undefined, percentage?: number | undefined}) | undefined}>) | undefined, risk?: {enabled: boolean} | undefined, display_name?: string | undefined, success_url: PaymentSessionsSuccessUrl, failure_url: PaymentSessionsFailureUrl, metadata?: PaymentSessionMetadata | undefined, locale?: ('ar' | 'da-DK' | 'de-DE' | 'el' | 'en-GB' | 'es-ES' | 'fi-FI' | 'fil-PH' | 'fr-FR' | 'hi-IN' | 'id-ID' | 'it-IT' | 'ja-JP' | 'ko-KR' | 'ms-MY' | 'nb-NO' | 'nl-NL' | 'pt-PT' | 'sv-SE' | 'th-TH' | 'vi-VN' | 'zh-CN' | 'zh-HK' | 'zh-TW') | undefined, '3ds'?: PaymentSessions3DS | undefined, sender?: PaymentInterfacesSender | undefined, capture?: PaymentSessionCaptureFlag | undefined, capture_on?: PaymentSessionCaptureOn | undefined, payment_plan?: PaymentSessionPaymentPlanRecurring | undefined}; export type CreateApiPaymentSessionsCompleteArgs = {body: CreateAndSubmitPaymentSessionsRequest}; export type CreateApiPaymentSessionsCompleteOptions = {baseUrl: string, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const paymentId = z.string().min(30).max(30); export const paymentSessionId = z.string().min(30).max(30); export const paymentSessionSecret = z.string(); export const createAndSubmitPaymentSessionsProcessedResponse = z.discriminatedUnion("status", [z.object({id: paymentId, status: z.literal("Approved"), type: z.enum(["alipay_cn", "alipay_hk", "alma", "applepay", "bancontact", "benefit", "bizum", "card", "dana", "eps", "gcash", "googlepay", "ideal", "kakaopay", "klarna", "knet", "mbway", "mobilepay", "multibanco", "octopus", "p24", "paynow", "paypal", "plaid", "qpay", "sepa", "stcpay", "stored_card", "tabby", "tamara", "tng", "truemoney", "twint", "vipps", "wechatpay"]), payment_session_id: paymentSessionId, payment_session_secret: paymentSessionSecret}), z.object({id: paymentId, status: z.literal("Declined"), type: z.enum(["alipay_cn", "alipay_hk", "alma", "applepay", "bancontact", "benefit", "bizum", "card", "dana", "eps", "gcash", "googlepay", "ideal", "kakaopay", "klarna", "knet", "mbway", "mobilepay", "multibanco", "octopus", "p24", "paynow", "paypal", "plaid", "qpay", "sepa", "stcpay", "stored_card", "tabby", "tamara", "tng", "truemoney", "twint", "vipps", "wechatpay"]), decline_reason: z.string()})]); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Request a Payment Session with Payment * * POST /payment-sessions/complete * * Also accepts auth: ApiSecretKey */ export const createApiPaymentSessionsComplete = async (args: CreateApiPaymentSessionsCompleteArgs, options: CreateApiPaymentSessionsCompleteOptions) => { const {baseUrl, fetch: fetchFn = fetch, OAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/payment-sessions/complete${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createAndSubmitPaymentSessionsProcessedResponse, await res.json()) };