import {z} from 'zod' export type PaginationFirst = number; export type PaginationAfter = string; export type PaymentId = string; export type Reference = string; export type AccountLegalName = string; export type PaymentStatus = 'initiated' | 'action_required' | 'submitted' | 'authorized' | 'captured' | 'declined' | 'failed' | 'partially_refunded' | 'refunded'; export type QueryPaymentsRequest = {type: 'payments', first?: PaginationFirst | undefined, after?: PaginationAfter | undefined, filters?: ({id?: PaymentId | undefined, reference?: Reference | undefined, seller_legal_name?: AccountLegalName | undefined, statuses?: Array | undefined}) | undefined, sorts?: (Array<{field: 'created_at' | 'amount' | 'seller_legal_name', direction: 'ascending' | 'descending'}>) | undefined}; export type CreateApiV2PaymentsQueryArgs = {'Getpaid-Idempotency-Key': string, body: QueryPaymentsRequest}; export type CreateApiV2PaymentsQueryOptions = {baseUrl?: string | undefined, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const paymentId = z.string().min(30).max(50); export const reference = z.string().min(1).max(50); export const paymentStatus = z.enum(["initiated", "action_required", "submitted", "authorized", "captured", "declined", "failed", "partially_refunded", "refunded"]); 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 paymentMethodType = z.enum(["card", "sepa_direct_debit"]); export const paymentMethodDisplayHint = z.string().min(1).max(50); export const basePaymentMethodHint = z.object({type: paymentMethodType, display_hint: paymentMethodDisplayHint}); export const cardScheme = z.enum(["visa", "mastercard"]); export const cardPaymentMethodHint = z.object({type: z.enum(["card", "sepa_direct_debit"]), scheme: cardScheme, display_hint: paymentMethodDisplayHint}); export const paymentMethodHint = z.discriminatedUnion("type", [basePaymentMethodHint, cardPaymentMethodHint]); 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 queryPaymentsResponse = z.object({type: z.literal("payments"), cursor: z.string().max(250).optional(), data: z.array(z.object({id: paymentId, reference: reference, status: paymentStatus, amount: amountMinor, currency: currency, created_at: createdAt, updated_at: updatedAt, method: paymentMethodHint, 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 payments * * POST /v2/payments/query * * Also accepts auth: OAuth */ export const createApiV2PaymentsQuery = async (args: CreateApiV2PaymentsQueryArgs, options?: CreateApiV2PaymentsQueryOptions) => { 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/payments/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(queryPaymentsResponse, await res.json()) };