import {z} from 'zod' export type PaginationFirst = number; export type PaginationAfter = string; export type CheckoutId = string; export type Reference = string; export type CheckoutStatus = 'initiated' | 'started' | 'in_progress' | 'completed' | 'failed' | 'unattempted'; export type AccountLegalName = string; export type QueryCheckoutsRequest = {type: 'checkouts', first?: PaginationFirst | undefined, after?: PaginationAfter | undefined, filters?: ({id?: CheckoutId | undefined, reference?: Reference | undefined, statuses?: Array | undefined, seller_legal_name?: AccountLegalName | undefined}) | undefined, sorts?: (Array<{field: 'created_at' | 'amount' | 'seller_legal_name', direction: 'ascending' | 'descending'}>) | undefined}; export type CreateApiV2CheckoutsQueryArgs = {'Getpaid-Idempotency-Key': string, body: QueryCheckoutsRequest}; export type CreateApiV2CheckoutsQueryOptions = {baseUrl?: string | undefined, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const checkoutId = z.string().min(30).max(50); export const reference = z.string().min(1).max(50); export const checkoutStatus = z.enum(["initiated", "started", "in_progress", "completed", "failed", "unattempted"]); export const amountMinor = z.number().int(); export const currency = z.string().min(3).max(3); 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 queryPaymentMethodHint = z.object({type: z.enum(["card", "sepa_direct_debit"]), scheme: z.string().optional()}); export const accountId = z.string().min(30).max(50); export const accountLegalName = z.string().min(1).max(250); export const sellerRef = z.object({id: accountId, legal_name: accountLegalName}); export const partyRef = z.object({id: accountId, type: z.enum(["platform", "other"]), legal_name: accountLegalName}); export const queryCheckoutsResponse = z.object({type: z.literal("checkouts"), cursor: z.string().max(250).optional(), data: z.array(z.object({id: checkoutId, reference: reference, status: checkoutStatus, amount: amountMinor, currency: currency, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, payment_methods: z.array(queryPaymentMethodHint), seller: sellerRef, parties: z.array(partyRef)}))}); 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 }; /** * Query checkouts * * POST /v2/checkouts/query * * Also accepts auth: OAuth */ export const createApiV2CheckoutsQuery = async (args: CreateApiV2CheckoutsQueryArgs, options?: CreateApiV2CheckoutsQueryOptions) => { const {baseUrl = "https://api.getpaid.io", 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 (args['Getpaid-Idempotency-Key'] != null) headers.set("Getpaid-Idempotency-Key", String(args['Getpaid-Idempotency-Key'])) if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/checkouts/query${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(queryCheckoutsResponse, await res.json()) };