import {z} from 'zod' export type CreateApiV3VaultCustomerArgs = {token: string, body: {firstName: string, lastName: string, cardAccount: {number?: string | undefined, expiryMonth?: string | undefined, expiryYear?: string | undefined, token?: string | undefined, avsStreet?: string | undefined, avsZip?: string | undefined, cvv?: string | undefined, magstripe?: string | undefined, alias?: string | undefined, emvData?: string | undefined, emvDataKsn?: string | undefined, track1?: string | undefined, track2?: string | undefined, track1Ksn?: string | undefined, track2Ksn?: string | undefined}}}; export type CreateApiV3VaultCustomerOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV3VaultCustomerResponse = z.object({id: z.number().int().optional(), cardAccount: z.object({token: z.string().optional(), hasContract: z.boolean().optional()}).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 customer/vaulted card with token * * POST /v3/vault/customer */ export const createApiV3VaultCustomer = async (args: CreateApiV3VaultCustomerArgs, options?: CreateApiV3VaultCustomerOptions) => { const {baseUrl = "https://sandbox.api.mxmerchant.com/checkout", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.token != null) query.append("token", String(args.token)) const url = `${baseUrl.replace(/\/+$/, '')}/v3/vault/customer${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(createApiV3VaultCustomerResponse, await res.json()) };