import {z} from 'zod' export type MerchantPaymentStatus = 'PENDING' | 'IDENTIFIED' | 'AUTHORIZED' | 'AUTHORIZATION_FAILED' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED' | 'EXPIRED' | 'PENDING_MERCHANT_ACKNOWLEDGEMENT' | 'VOIDED'; export type PaymentSearchQuery = {from?: string | undefined, to?: string | undefined, paymentStatuses?: Array | undefined, reference?: string | undefined}; export type CreateApiV3PaymentsSearchArgs = {page?: number | undefined, size?: number | undefined, body: PaymentSearchQuery}; export type CreateApiV3PaymentsSearchOptions = {baseUrl?: string | undefined, apiKeyPaymentProfile?: string | undefined, fetch?: typeof fetch | undefined}; export const currency = z.literal("EUR"); export const merchantPaymentStatus = z.enum(["PENDING", "IDENTIFIED", "AUTHORIZED", "AUTHORIZATION_FAILED", "SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED", "PENDING_MERCHANT_ACKNOWLEDGEMENT", "VOIDED"]); export const paymentCreditorResponse = z.object({profileId: z.string().optional(), merchantId: z.string().optional(), name: z.string().optional(), iban: z.string().optional(), identifyCallbackUrl: z.string().optional(), callbackUrl: z.string().optional()}); export const link = z.object({href: z.string()}); export const links = z.object({self: link, deeplink: link, qrcode: link, cancel: link.optional(), refund: link.optional(), checkout: link.optional()}); export const getPaymentResponse = z.object({paymentId: z.string().min(24).max(24), createdAt: z.string(), expireAt: z.string(), succeededAt: z.string().optional(), currency: currency, status: merchantPaymentStatus, creditor: paymentCreditorResponse, debtor: z.object({name: z.string().optional(), iban: z.string().optional()}).optional(), amount: z.number().int(), description: z.string().optional(), message: z.string().optional(), reference: z.string().optional(), bulkId: z.string().optional(), _links: links.optional()}); export const paymentSearchResponse = z.object({size: z.number().int().gte(0), totalPages: z.number().int(), totalElements: z.number().int(), number: z.number().int(), details: z.array(getPaymentResponse).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 }; /** * search payments * * POST /v3/payments/search * * Also accepts auth: JWS-Request-Signature-Payment */ export const createApiV3PaymentsSearch = async (args: CreateApiV3PaymentsSearchArgs, options?: CreateApiV3PaymentsSearchOptions) => { const {baseUrl = "https://merchant.api.preprod.bancontact.net", fetch: fetchFn = fetch, apiKeyPaymentProfile} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.size != null) query.append("size", String(args.size)) if (apiKeyPaymentProfile !== undefined) headers.set("Authorization", apiKeyPaymentProfile) const url = `${baseUrl.replace(/\/+$/, '')}/v3/payments/search${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(paymentSearchResponse, await res.json()) };