import {z} from 'zod' export type ExternalMetadata = {metadata?: {[key: string]: Record} | undefined}; export type Address = {city?: string | undefined, country?: string | undefined, line1?: string | undefined, line2?: string | undefined, postcode?: string | undefined}; export type PrefilledCardholderDetails = {billing_address?: Address | undefined, cardholder_name?: string | undefined}; export type CreateCardPaymentRequest = {agreement_id?: string | undefined, agreement_payment_type?: ('instalment' | 'recurring' | 'unscheduled') | undefined, amount: number, authorisation_mode?: ('web' | 'agreement' | 'moto_api') | undefined, delayed_capture?: boolean | undefined, description: string, email?: string | undefined, language?: ('en' | 'cy') | undefined, metadata?: ExternalMetadata | undefined, moto?: boolean | undefined, prefilled_cardholder_details?: PrefilledCardholderDetails | undefined, reference: string, return_url: string, set_up_agreement?: string | undefined}; export type CreateApiV1PaymentsArgs = {'Idempotency-Key'?: string | undefined, body: CreateCardPaymentRequest}; export type CreateApiV1PaymentsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const postLink = z.object({href: z.string().optional(), method: z.string().optional(), params: z.record(z.string(), z.object({})).optional(), type: z.string().optional()}); export const link = z.object({href: z.string().optional(), method: z.string().optional()}); export const paymentLinks = z.object({auth_url_post: postLink.optional(), cancel: postLink.optional(), capture: postLink.optional(), events: link.optional(), next_url: link.optional(), next_url_post: postLink.optional(), refunds: link.optional(), self: link.optional()}); export const address = z.object({city: z.string().max(255).optional(), country: z.string().optional(), line1: z.string().max(255).optional(), line2: z.string().max(255).optional(), postcode: z.string().max(25).optional()}); export const cardDetailsFromResponse = z.object({billing_address: address.optional(), card_brand: z.string().optional(), card_type: z.string().optional(), cardholder_name: z.string().optional(), expiry_date: z.string().optional(), first_digits_card_number: z.string().optional(), last_digits_card_number: z.string().optional()}); export const externalMetadata = z.object({metadata: z.record(z.string(), z.object({})).optional()}); export const refundSummary = z.object({amount_available: z.number().int().optional(), amount_submitted: z.number().int().optional(), status: z.string().optional()}); export const paymentSettlementSummary = z.object({capture_submit_time: z.string().optional(), captured_date: z.string().optional(), settled_date: z.string().optional()}); export const paymentState = z.object({can_retry: z.boolean().nullable().optional(), code: z.string().optional(), finished: z.boolean().optional(), message: z.string().optional(), status: z.string().optional()}); export const createPaymentResult = z.object({_links: paymentLinks.optional(), amount: z.number().int().optional(), card_details: cardDetailsFromResponse.optional(), created_date: z.string().optional(), delayed_capture: z.boolean().optional(), description: z.string().optional(), email: z.string().optional(), language: z.enum(["en", "cy"]).optional(), metadata: externalMetadata.optional(), moto: z.boolean().optional(), payment_id: z.string().optional(), payment_provider: z.string().optional(), provider_id: z.string().optional(), reference: z.string().optional(), refund_summary: refundSummary.optional(), return_url: z.string().optional(), settlement_summary: paymentSettlementSummary.optional(), state: paymentState.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 }; /** * Create a payment * * POST /v1/payments */ export const createApiV1Payments = async (args: CreateApiV1PaymentsArgs, options?: CreateApiV1PaymentsOptions) => { const {baseUrl = "https://publicapi.payments.service.gov.uk", 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 (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/payments${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(createPaymentResult, await res.json()) };