import {z} from 'zod' export type ProvisionNetworkToken = boolean; export type CreditCard = {first_name: string, last_name: string, full_name?: string | undefined, number: string, verification_value?: string | undefined, month: string, year: string, company?: string | undefined, address1?: string | undefined, address2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, country?: string | undefined, phone_number?: string | undefined, house_number_or_name?: string | undefined, street?: string | undefined, street_line2?: string | undefined, phone_number_country_code?: string | undefined, phone_number_area_code?: string | undefined, shipping_address1?: string | undefined, shipping_address2?: string | undefined, shipping_city?: string | undefined, shipping_state?: string | undefined, shipping_zip?: string | undefined, shipping_country?: string | undefined, shipping_phone_number?: string | undefined, shipping_house_number_or_name?: string | undefined, shipping_street?: string | undefined, shipping_street_line2?: string | undefined, shipping_phone_number_country_code?: string | undefined, shipping_phone_number_area_code?: string | undefined}; export type BankAccount = {first_name: string, last_name: string, bank_routing_number: string, bank_account_number: string, bank_account_type?: ('checking' | 'savings') | undefined, bank_account_holder_type?: ('business' | 'personal') | undefined, full_name?: string | undefined}; export type ApplePay = {payment_data: {version: unknown, data: unknown, signature: unknown, header?: {ephemeralPublicKey: unknown, transactionId: unknown, publicKeyHash: unknown} | undefined}, test_card_number: unknown}; export type GooglePay = {payment_data: {signature?: string | undefined, protocolVersion?: string | undefined, signedMessage?: string | undefined}, test_card_number?: string | undefined, first_name?: string | undefined, last_name?: string | undefined, address_1?: string | undefined, address_2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, country?: string | undefined}; export type RecoverParams = {gateway_tokens: Array, mode?: string | undefined, custom_errors?: ({error_codes?: Array | undefined, messages?: Array | undefined, additional_data?: Array | undefined, override_default_error_codes?: boolean | undefined}) | undefined}; export type ProtectionParameters = {test_scenario?: ({scenario?: ('protect_approved' | 'protect_sca_recommended_challenge' | 'protect_sca_recommended_authenticated' | 'protect_sca_recommended_not_authenticated' | 'protect_declined') | undefined}) | undefined, fraud_token?: string | undefined, forter_mobile_uid?: string | undefined, user_agent?: string | undefined, cart_items: Array<{name: string, quantity: number, type: 'TANGIBLE' | 'NON_TANGIBLE', price: string}>, delivery_type: 'PHYSICAL' | 'DIGITAL', delivery_method: string, customer_account_id?: string | undefined, customer_account_type?: ('GUEST' | 'PRIVATE' | 'BUSINESS' | 'VIP' | 'MERCHANT_OPERATED' | 'TRIAL' | 'MERCHANT_EMPLOYEE' | 'PREMIUM_PAID' | 'SMALL_BUSINESS' | 'AGENT' | 'BUSINESS_PRIVATE' | 'BUSINESS_PREMIUM_PAID') | undefined, customer_account_creation_date?: number | undefined, billing_name?: string | undefined, billing_first_name?: string | undefined, billing_last_name?: string | undefined, email?: string | undefined, billing_country?: string | undefined, billing_address1?: string | undefined, billing_address2?: string | undefined, billing_city?: string | undefined, billing_zip?: string | undefined, billing_state?: string | undefined, billing_phone_number?: string | undefined, billing_house_number_or_name?: string | undefined, billing_street?: string | undefined, billing_street_line2?: string | undefined, billing_phone_number_country_code?: string | undefined, billing_phone_number_area_code?: string | undefined, shipping_name?: string | undefined, shipping_first_name?: string | undefined, shipping_last_name?: string | undefined, shipping_email?: string | undefined, shipping_country?: string | undefined, shipping_address1?: string | undefined, shipping_address2?: string | undefined, shipping_city?: string | undefined, shipping_zip?: string | undefined, shipping_state?: string | undefined, shipping_phone_number?: string | undefined, shipping_house_number_or_name?: string | undefined, shipping_street?: string | undefined, shipping_street_line2?: string | undefined, shipping_phone_number_country_code?: string | undefined, shipping_phone_number_area_code?: string | undefined}; export type Purchase = {transaction?: ({amount: number, currency_code: string, order_id?: string | undefined, description?: string | undefined, retain_on_success?: string | undefined, ip?: string | undefined, browser_info?: string | undefined, email?: string | undefined, merchant_name_descriptor?: string | undefined, merchant_location_descriptor?: string | undefined, ach_description?: string | undefined, transaction_metadata?: Record | undefined, gateway_specific_fields?: Record | undefined, stored_credential_initiator?: string | undefined, stored_credential_reason_type?: string | undefined, sub_merchant_key?: string | undefined, sca_provider_key?: string | undefined, sca_authentication_parameters?: ({three_ds_requestor_challenge_ind?: string | undefined, test_scenario?: boolean | undefined, exemption_type?: Array | undefined, acquiring_bank_fraud_rate?: string | undefined}) | undefined, callback_url?: string | undefined, callback_format?: string | undefined, shipping_address?: ({name?: string | undefined, address1?: string | undefined, address2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, country?: string | undefined, phone_number?: string | undefined, house_number_or_name?: string | undefined, street?: string | undefined, street_line2?: string | undefined, phone_number_country_code?: string | undefined, phone_number_area_code?: string | undefined}) | undefined, billing_address?: ({name?: string | undefined, address1?: string | undefined, address2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, country?: string | undefined, phone_number?: string | undefined, house_number_or_name?: string | undefined, street?: string | undefined, street_line2?: string | undefined, phone_number_country_code?: string | undefined, phone_number_area_code?: string | undefined}) | undefined, ignore_failed_authentication_result?: string | undefined, workflow_key?: string | undefined, order_data?: Record | undefined, customer_data?: Record | undefined, risk_data?: Record | undefined, merchant_metadata?: Record | undefined, payment_method_token?: string | undefined, attempt_network_token?: boolean | undefined, provision_network_token?: ProvisionNetworkToken | undefined, credit_card?: CreditCard | undefined, bank_account?: BankAccount | undefined, apple_pay?: ApplePay | undefined, google_pay?: GooglePay | undefined, sca_authentication_token?: string | undefined, retry?: RecoverParams | undefined, protection_provider_key?: string | undefined, protection_parameters?: ProtectionParameters | undefined, allow_blank_name?: boolean | undefined, allow_expired_date?: boolean | undefined, allow_blank_date?: boolean | undefined, tlid?: string | undefined, customer_agreement_id?: string | undefined}) | undefined}; export type CreateApiTransactionsPurchaseArgs = {body: Purchase}; export type CreateApiTransactionsPurchaseOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const paymentSnapshot = z.object({gateway_tokens: z.array(z.string()).optional(), attempts: z.number().int().optional(), messages: z.object({}).optional(), mode: z.string().optional(), custom_error_used: z.boolean().optional(), override_default_error_codes: z.boolean().optional(), created_at: z.string().optional(), updated_at: z.string().optional(), payment_token: z.string().optional(), previous_transaction_tokens: z.array(z.string()).optional()}); export const protectionParameters = z.object({test_scenario: z.object({scenario: z.enum(["protect_approved", "protect_sca_recommended_challenge", "protect_sca_recommended_authenticated", "protect_sca_recommended_not_authenticated", "protect_declined"]).optional()}).optional(), fraud_token: z.string().optional(), forter_mobile_uid: z.string().optional(), user_agent: z.string().optional(), cart_items: z.array(z.object({name: z.string().max(500), quantity: z.number(), type: z.enum(["TANGIBLE", "NON_TANGIBLE"]), price: z.string()})), delivery_type: z.enum(["PHYSICAL", "DIGITAL"]), delivery_method: z.string().max(50), customer_account_id: z.string().optional(), customer_account_type: z.enum(["GUEST", "PRIVATE", "BUSINESS", "VIP", "MERCHANT_OPERATED", "TRIAL", "MERCHANT_EMPLOYEE", "PREMIUM_PAID", "SMALL_BUSINESS", "AGENT", "BUSINESS_PRIVATE", "BUSINESS_PREMIUM_PAID"]).optional(), customer_account_creation_date: z.number().optional(), billing_name: z.string().optional(), billing_first_name: z.string().optional(), billing_last_name: z.string().optional(), email: z.string().optional(), billing_country: z.string().optional(), billing_address1: z.string().optional(), billing_address2: z.string().optional(), billing_city: z.string().optional(), billing_zip: z.string().optional(), billing_state: z.string().optional(), billing_phone_number: z.string().optional(), billing_house_number_or_name: z.string().optional(), billing_street: z.string().optional(), billing_street_line2: z.string().optional(), billing_phone_number_country_code: z.string().optional(), billing_phone_number_area_code: z.string().optional(), shipping_name: z.string().optional(), shipping_first_name: z.string().optional(), shipping_last_name: z.string().optional(), shipping_email: z.string().optional(), shipping_country: z.string().optional(), shipping_address1: z.string().optional(), shipping_address2: z.string().optional(), shipping_city: z.string().optional(), shipping_zip: z.string().optional(), shipping_state: z.string().optional(), shipping_phone_number: z.string().optional(), shipping_house_number_or_name: z.string().optional(), shipping_street: z.string().optional(), shipping_street_line2: z.string().optional(), shipping_phone_number_country_code: z.string().optional(), shipping_phone_number_area_code: z.string().optional()}); export const gatewaySpecificFields = z.array(z.string()); export const protectFraudCheckResponse = z.object({updated_at: z.string().optional(), created_at: z.string().optional(), protection_provider_key: z.string().optional(), succeeded: z.boolean().optional(), state: z.string().optional(), token: z.string().optional(), message: z.string().optional(), amount: z.number().optional(), currency_code: z.string().optional(), ip: z.string().optional(), email: z.string().optional(), transaction_type: z.string().optional(), gateway_transaction_key: z.string().optional(), callback_url: z.string().optional(), test_scenario: z.string().optional(), acquiring_bank_fraud_rate: z.string().optional(), exemption_type: z.string().optional(), warning: z.string().optional(), managed_order_token: z.string().optional(), fraud_decision: z.string().optional(), fraud_recommendation: z.string().optional(), fraud_decision_reason: z.string().optional(), vendor_response: z.object({forterDecision: z.string().optional(), recommendation: z.string().optional(), verificationMethod: z.object({}).optional(), decisionReason: z.string().optional(), merchantPolicyId: z.string().optional(), orderId: z.string().optional(), linkToEventInDashboard: z.string().optional()}).optional()}); export const networkTokenization = z.object({provisioned: z.boolean().optional(), token_status: z.string().optional(), token_reference: z.string().optional(), token_first_six_digits: z.string().optional(), token_last_four_digits: z.string().optional(), token_created_at: z.string().optional(), token_updated_at: z.string().optional(), attempted: z.boolean().optional(), errors: z.array(z.object({key: z.string().optional(), message: z.string().optional(), action: z.string().optional()})).optional()}); export const purchaseResponse = z.object({transaction: z.object({token: z.string().optional(), succeeded: z.boolean().optional(), message: z.string().optional(), gateway_transaction_id: z.string().optional(), retain_on_success: z.boolean().optional(), payment_method_added: z.string().optional(), response: z.object({}).optional(), payment_method: z.object({token: z.string().optional(), created_at: z.string().optional(), updated_at: z.string().optional(), email: z.string().optional(), storage_state: z.string().optional(), test: z.boolean().optional(), metadata: z.object({}).optional(), callback_url: z.string().optional(), last_four_digits: z.string().optional(), first_six_digits: z.string().optional(), card_type: z.string().optional(), first_name: z.string().optional(), last_name: z.string().optional(), month: z.string().optional(), year: z.string().optional(), address1: z.string().optional(), address2: z.string().optional(), city: z.string().optional(), state: z.string().optional(), zip: z.string().optional(), country: z.string().optional(), phone_number: z.string().optional(), house_number_or_name: z.string().optional(), street: z.string().optional(), street_line2: z.string().optional(), phone_number_country_code: z.string().optional(), phone_number_area_code: z.string().optional(), company: z.string().optional(), full_name: z.string().optional(), eligible_for_card_updater: z.string().optional(), shipping_address1: z.string().optional(), shipping_address2: z.string().optional(), shipping_city: z.string().optional(), shipping_state: z.string().optional(), shipping_zip: z.string().optional(), shipping_country: z.string().optional(), shipping_house_number_or_name: z.string().optional(), shipping_street: z.string().optional(), shipping_street_line2: z.string().optional(), shipping_phone_number_country_code: z.string().optional(), shipping_phone_number_area_code: z.string().optional(), issuer_identification_number: z.string().optional(), click_to_pay: z.string().optional(), managed: z.string().optional(), payment_method_type: z.string().optional(), errors: z.string().optional(), fingerprint: z.string().optional(), verification_value: z.string().optional(), number: z.string().optional(), bin_metadata: z.object({card_brand: z.string().optional(), card_category: z.string().optional(), card_type: z.string().optional(), issuing_bank: z.string().optional(), issuing_country_iso_number: z.string().optional(), issuing_country_iso_a2_code: z.string().optional(), issuing_country_iso_a3_code: z.string().optional(), issuing_country_iso_name: z.string().optional(), issuing_bank_phone_number: z.string().optional(), issuing_bank_website: z.string().optional(), bin_type: z.string().optional(), regulated: z.string().optional(), max_pan_length: z.string().optional(), message: z.string().optional()}).optional(), subscribed_to_mastercard_abu: z.boolean().optional(), last_successfully_used: z.string().nullable().optional()}).optional(), merchant_profile_key: z.string().optional(), sub_merchant_key: z.string().optional(), gateway_specific_response_fields: z.object({}).optional(), transaction_metadata: z.object({}).optional(), sca_authentication: z.string().optional(), payment_snapshot: paymentSnapshot.optional(), protection_provider_key: z.string().optional(), protection_parameters: protectionParameters.optional(), order_id: z.string().optional(), ip: z.string().optional(), description: z.string().optional(), email: z.string().optional(), merchant_name_descriptor: z.string().optional(), merchant_location_descriptor: z.string().optional(), gateway_specific_fields: gatewaySpecificFields.optional(), gateway_latency_ms: z.string().optional(), warning: z.string().optional(), application_id: z.string().optional(), amount: z.number().int().optional(), local_amount: z.string().optional(), currency_code: z.string().optional(), stored_credential_initiator: z.string().optional(), stored_credential_reason_type: z.string().optional(), shipping_address: z.object({}).optional(), api_urls: z.array(z.unknown()).optional(), attempt_3dsecure: z.string().optional(), workflow_key: z.string().optional(), order_data: z.object({}).optional(), customer_data: z.object({}).optional(), risk_data: z.object({}).optional(), merchant_metadata: z.object({}).optional(), gateway_response: z.object({}).optional(), pan_retry: z.boolean().optional(), protect_fraud_check: protectFraudCheckResponse.optional(), message_key: z.string().optional(), billing_address: z.object({}).optional(), tlid: z.string().optional(), customer_agreement_id: z.string().optional(), network_tokenization: networkTokenization.optional()}).optional()}); 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 }; /** * Create a purchase with workflows * * POST /transactions/purchase */ export const createApiTransactionsPurchase = async (args: CreateApiTransactionsPurchaseArgs, options?: CreateApiTransactionsPurchaseOptions) => { const {baseUrl = "https://core.spreedly.com/v1", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/transactions/purchase${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(purchaseResponse, await res.json()) };