import {z} from 'zod' export type CheckoutId = string; export type GetApiV2CheckoutsCheckoutIdArgs = {checkout_id: CheckoutId}; export type GetApiV2CheckoutsCheckoutIdOptions = {baseUrl?: string | undefined, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const checkoutId = z.string().min(30).max(50); export const checkoutStatus = z.enum(["initiated", "started", "in_progress", "completed", "failed", "unattempted"]); export const reference = z.string().min(1).max(50); export const createdAt = z.string().min(24).max(24); export const updatedAt = z.string().min(24).max(24); export const checkoutExpiresAt = z.string().min(24).max(24); export const checkoutIsExpired = z.boolean(); export const amountMinor = z.number().int(); export const currency = z.string().min(3).max(3); export const checkoutDescription = z.string().min(1).max(250); export const checkoutFlow = z.object({next_step: z.object({type: z.literal("redirect"), url: z.string().max(1024)})}); export const paymentMethodType = z.enum(["card", "sepa_direct_debit"]); export const paymentMethodBase = z.object({type: paymentMethodType}); export const cardScheme = z.enum(["visa", "mastercard"]); export const cardPaymentMethodDescriptor = z.object({type: paymentMethodType, scheme: cardScheme}); export const paymentMethodDescriptor = z.discriminatedUnion("type", [paymentMethodBase, cardPaymentMethodDescriptor]); export const cardDynamicDescriptor = z.string().min(1).max(18); export const checkoutCardPaymentMethodOptions = z.object({dynamic_descriptor: cardDynamicDescriptor}); export const sddRemittanceInfo = z.string().min(1).max(140); export const checkoutSepaDirectDebitPaymentMethodOptions = z.object({remittance_info: sddRemittanceInfo}); export const checkoutPaymentMethodsOptions = z.object({cards: checkoutCardPaymentMethodOptions.optional(), sepa_direct_debit: checkoutSepaDirectDebitPaymentMethodOptions.optional()}); export const checkoutPaymentMethodsAvailable = z.object({type: z.enum(["default", "explicit"]), available: z.array(paymentMethodDescriptor), options: checkoutPaymentMethodsOptions.optional()}); export const splitsType = z.literal("per_transaction"); export const splitsAccountType = z.enum(["platform", "seller", "other"]); export const accountId = z.string().min(30).max(50); export const accountVersion = z.string().min(1).max(50); export const accountLegalName = z.string().min(1).max(250); export const splitAmountMinor = z.number().int(); export const splitFixedAmount = z.object({type: z.enum(["fixed", "percentage", "remaining"]), amount: splitAmountMinor}); export const splitPercentageAmountCalculated = z.object({type: z.enum(["fixed", "percentage", "remaining"]), percentage: z.number().gte(0).lte(100).multipleOf(0.1), amount: splitAmountMinor}); export const splitRemainingAmountCalculated = z.object({type: z.enum(["fixed", "percentage", "remaining"]), amount: splitAmountMinor}); export const processingFeeRequest = z.object({percentage: z.number().gte(0).lte(100).multipleOf(0.1)}); export const splitsCalculated = z.object({type: splitsType, accounts: z.array(z.object({type: splitsAccountType, id: accountId, version: accountVersion, legal_name: accountLegalName, split: z.discriminatedUnion("type", [splitFixedAmount, splitPercentageAmountCalculated, splitRemainingAmountCalculated]), processing_fee: processingFeeRequest}))}); export const standingInstructionStatus = z.enum(["new", "active"]); export const standingInstructionTerms = z.object({type: z.enum(["recurring", "unscheduled"])}); export const newStandingInstruction = z.object({status: standingInstructionStatus, terms: standingInstructionTerms}); export const index = z.number().int().gte(0); export const paymentId = z.string().min(30).max(50); export const paymentStatusPhase = z.enum(["in_progress", "succeeded", "failed"]); export const checkoutPayments = z.array(z.object({index: index, id: paymentId, status: paymentStatusPhase, created_at: createdAt, updated_at: updatedAt, method: z.object({type: paymentMethodType, scheme: cardScheme.optional(), display_hint: z.string().max(50)})})); export const themeId = z.string().min(30).max(50); export const checkoutInitiatedStarted = z.object({id: checkoutId, status: checkoutStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, is_expired: checkoutIsExpired, amount: amountMinor, currency: currency, description: checkoutDescription.optional(), flow: checkoutFlow, payment_methods: checkoutPaymentMethodsAvailable, splits: splitsCalculated, standing_instruction: newStandingInstruction.optional(), payments: checkoutPayments, theme: z.object({id: themeId, name: z.string().min(1).max(250)})}); export const checkoutPaymentMethodsWithSelected = z.object({type: z.enum(["default", "explicit"]), selected: paymentMethodDescriptor, available: z.array(paymentMethodDescriptor), options: checkoutPaymentMethodsOptions.optional()}); export const checkoutInProgress = z.object({id: checkoutId, status: checkoutStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, is_expired: checkoutIsExpired, amount: amountMinor, currency: currency, description: checkoutDescription.optional(), flow: checkoutFlow, payment_methods: checkoutPaymentMethodsWithSelected, splits: splitsCalculated, standing_instruction: newStandingInstruction.optional(), payments: checkoutPayments, theme: z.object({id: themeId, name: z.string().min(1).max(250)})}); export const processingFeeAmount = z.number().int(); export const processingFeeCalculated = z.object({percentage: z.number().gte(0).lte(100).multipleOf(0.1), amount: processingFeeAmount}); export const splitsAndFeesCalculated = z.object({type: splitsType, accounts: z.array(z.object({type: splitsAccountType, id: accountId, version: accountVersion, legal_name: accountLegalName, split: z.discriminatedUnion("type", [splitFixedAmount, splitPercentageAmountCalculated, splitRemainingAmountCalculated]), processing_fee: processingFeeCalculated}))}); export const standingInstructionId = z.string().min(30).max(50); export const activeStandingInstruction = z.object({id: standingInstructionId, status: standingInstructionStatus, terms: standingInstructionTerms}); export const checkoutCompleted = z.object({id: checkoutId, status: checkoutStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, is_expired: checkoutIsExpired, amount: amountMinor, currency: currency, description: checkoutDescription.optional(), payment_methods: checkoutPaymentMethodsWithSelected, splits: splitsAndFeesCalculated, standing_instruction: activeStandingInstruction.optional(), payments: checkoutPayments, theme: z.object({id: themeId, name: z.string().min(1).max(250)})}); export const checkoutFailed = z.object({id: checkoutId, status: checkoutStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, is_expired: checkoutIsExpired, amount: amountMinor, currency: currency, description: checkoutDescription.optional(), payment_methods: checkoutPaymentMethodsAvailable, splits: splitsCalculated, standing_instruction: newStandingInstruction.optional(), payments: checkoutPayments, theme: z.object({id: themeId, name: z.string().min(1).max(250)})}); export const checkoutUnattempted = z.object({id: checkoutId, status: checkoutStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, is_expired: checkoutIsExpired, amount: amountMinor, currency: currency, description: checkoutDescription.optional(), payment_methods: checkoutPaymentMethodsAvailable, splits: splitsCalculated, standing_instruction: newStandingInstruction.optional(), payments: checkoutPayments, theme: z.object({id: themeId, name: z.string().min(1).max(250)})}); export const getCheckoutResponse = z.discriminatedUnion("status", [checkoutInitiatedStarted, checkoutInProgress, checkoutCompleted, checkoutFailed, checkoutUnattempted]); 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 }; /** * Get a checkout * * GET /v2/checkouts/{checkout_id} * * Also accepts auth: OAuth */ export const getApiV2CheckoutsCheckoutId = async (args: GetApiV2CheckoutsCheckoutIdArgs, options?: GetApiV2CheckoutsCheckoutIdOptions) => { const {baseUrl = "https://api.getpaid.io", fetch: fetchFn = fetch, OAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/checkouts/${encodeURIComponent(String(args.checkout_id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getCheckoutResponse, await res.json()) };