import {z} from 'zod' export type AuthorizationRequest = {amount?: number | undefined, reference?: string | undefined, metadata?: Record | undefined}; export type CreateApiPaymentsIdAuthorizationsArgs = {'Cko-Idempotency-Key'?: string | undefined, id: string, body: AuthorizationRequest}; export type CreateApiPaymentsIdAuthorizationsOptions = {baseUrl: string, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const actionId = z.string().min(30).max(30); export const paymentResponseBalances = z.object({total_authorized: z.number().int().optional(), total_voided: z.number().int().optional(), available_to_void: z.number().int().optional(), total_captured: z.number().int().optional(), available_to_capture: z.number().int().optional(), total_refunded: z.number().int().optional(), available_to_refund: z.number().int().optional()}); export const serverTimestamp = z.string(); export const link = z.object({href: z.string()}); export const authorizationResponse = z.object({action_id: actionId, amount: z.number().int(), currency: z.string().min(3).max(3), approved: z.boolean(), status: z.enum(["Authorized", "Declined"]), auth_code: z.string().optional(), response_code: z.string(), response_summary: z.string().optional(), expires_on: z.string().optional(), balances: paymentResponseBalances.optional(), processed_on: serverTimestamp, reference: z.string().optional(), processing: z.object({retrieval_reference_number: z.string().optional(), acquirer_transaction_id: z.string().optional(), recommendation_code: z.string().optional(), surcharge_amount: z.number().int().gte(0).optional(), scheme_transaction_link_id: z.string().optional()}).optional(), eci: z.string().optional(), scheme_id: z.string().optional(), _links: z.object({self: link, actions: link, authorize: link.optional(), void: link.optional(), capture: link.optional(), refund: link.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 }; /** * Increment authorization * * POST /payments/{id}/authorizations * * Also accepts auth: ApiSecretKey */ export const createApiPaymentsIdAuthorizations = async (args: CreateApiPaymentsIdAuthorizationsArgs, options: CreateApiPaymentsIdAuthorizationsOptions) => { const {baseUrl, 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['Cko-Idempotency-Key'] != null) headers.set("Cko-Idempotency-Key", String(args['Cko-Idempotency-Key'])) if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/payments/${encodeURIComponent(String(args.id))}/authorizations${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(authorizationResponse, await res.json()) };