import {z} from 'zod' export type EmbeddedPaymentRequestInput = {merchant_id?: string | undefined, customer: {name: string, email: string, phone: string, country: string}, order: {order_id: string, amount: number, currency: string, payment_reference: string, locale: string, test_transaction?: boolean | undefined, rewards?: ({extra_rewards: number, total_rewards?: number | undefined, description?: string | undefined}) | undefined}, device_type?: ('web' | 'ios' | 'android') | undefined, billing_address?: ({address_line1: string, address_line2?: string | undefined, apartment?: string | undefined, city: string, state_province?: string | undefined, country: string, postal_code: string, company_name?: string | undefined}) | undefined, simulation?: ({straddle?: ({customer_outcome?: ('standard' | 'verified' | 'rejected' | 'review') | undefined, paykey_outcome?: ('standard' | 'active' | 'rejected') | undefined, charge_outcome?: ('standard' | 'paid' | 'on_hold_daily_limit' | 'cancelled_for_fraud_risk' | 'cancelled_for_balance_check' | 'failed_insufficient_funds' | 'reversed_insufficient_funds' | 'failed_customer_dispute' | 'reversed_customer_dispute' | 'failed_closed_bank_account' | 'reversed_closed_bank_account') | undefined, balance_check?: ('required' | 'enabled' | 'disabled') | undefined}) | undefined, flinks?: ({outcome?: ('happy' | 'async' | 'no_us_account' | 'partial_data' | 'webhook_only' | 'rate_limit' | 'unreachable') | undefined, account?: ({total: number, existing?: Array | undefined}) | undefined, mfa?: ('skip' | 'correct' | 'wrong') | undefined}) | undefined}) | undefined, redirect_urls: {success_url: string, failure_url: string}, webhook_endpoints?: Array | undefined}; export type CreateApiApiV1EmbeddedPaymentRequestsArgs = {body: EmbeddedPaymentRequestInput}; export type CreateApiApiV1EmbeddedPaymentRequestsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const embeddedPaymentRequestResponse = z.object({success: z.boolean(), data: z.object({payment_token: z.string(), expires_in: z.number().int().gte(1)})}); 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 payment request and return a payment_token for iframe flow * * POST /api/v1/embedded/payment-requests */ export const createApiApiV1EmbeddedPaymentRequests = async (args: CreateApiApiV1EmbeddedPaymentRequestsArgs, options?: CreateApiApiV1EmbeddedPaymentRequestsOptions) => { const {baseUrl = "https://core.quidkey.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/embedded/payment-requests${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(embeddedPaymentRequestResponse, await res.json()) };