import {z} from 'zod' export type CreateApiPaymentArgs = {echo?: boolean | undefined, includeCustomerMatches?: boolean | undefined, body: {merchantId: string, amount: number, paymentType?: string | undefined, authOnly?: boolean | undefined, isAuth?: boolean | undefined, tenderType?: string | undefined, cardPresent?: boolean | undefined, 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}) | undefined, bankAccount?: ({accountNumber?: string | undefined, routingNumber?: string | undefined, type?: string | undefined, name?: string | undefined, alias?: string | undefined, isDefault?: string | undefined, checkNumber?: string | undefined, individualId?: string | undefined, token?: string | undefined}) | undefined, entryClass?: string | undefined, isSettleFunds?: boolean | undefined, customer?: ({id?: string | undefined, firstName?: string | undefined, lastName?: string | undefined, type?: string | undefined}) | undefined, customerName?: string | undefined, customerCode?: string | undefined, meta?: string | undefined, replayId?: number | undefined, source?: string | undefined, clientReference?: string | undefined, invoice?: string | undefined, invoiceIds?: Array | undefined, orderIds?: Array | undefined, tax?: number | undefined, taxExempt?: boolean | undefined, cardPresentType?: string | undefined, posData?: Record | undefined, device?: string | undefined, purchases?: Array | undefined, shipAmount?: number | undefined, shipToCountry?: string | undefined, shipToZip?: string | undefined, shouldVaultCard?: boolean | undefined, tip?: number | undefined, vatAmount?: number | undefined, vatRate?: number | undefined, tags?: Array | undefined, surchargeAmount?: string | undefined, surchargeLabel?: string | undefined, surchargeRate?: string | undefined, mxAdvantageEnabled?: boolean | undefined, mxAdvantageFeeLabel?: string | undefined, mxAdvantageFeeType?: string | undefined, mxAdvantageFeeAmount?: string | undefined}}; export type CreateApiPaymentOptions = {baseUrl?: string | undefined, sec0?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const createApiPaymentResponse = z.object({created: z.string().optional(), paymentToken: z.string().optional(), id: z.number().int().optional(), creatorName: z.string().optional(), isDuplicate: z.boolean().optional(), shouldVaultCard: z.boolean().optional(), merchantId: z.number().int().optional(), batch: z.string().optional(), batchId: z.number().int().optional(), tenderType: z.string().optional(), currency: z.string().optional(), amount: z.string().optional(), cardAccount: z.object({cardType: z.string().optional(), entryMode: z.string().optional(), last4: z.string().optional(), cardId: z.string().optional(), token: z.string().optional(), expiryMonth: z.string().optional(), expiryYear: z.string().optional(), hasContract: z.boolean().optional(), cardPresent: z.boolean().optional(), isDebit: z.boolean().optional(), isCorp: z.boolean().optional()}).optional(), posData: z.object({panCaptureMethod: z.string().optional()}).optional(), authOnly: z.boolean().optional(), authCode: z.string().optional(), status: z.string().optional(), risk: z.object({cvvResponseCode: z.string().optional(), cvvResponse: z.string().optional(), cvvMatch: z.boolean().optional(), avsResponse: z.string().optional(), avsAddressMatch: z.boolean().optional(), avsZipMatch: z.boolean().optional()}).optional(), requireSignature: z.boolean().optional(), settledAmount: z.string().optional(), settledCurrency: z.string().optional(), cardPresent: z.boolean().optional(), authMessage: z.string().optional(), availableAuthAmount: z.string().optional(), reference: z.string().optional(), surchargeAmount: z.string().optional(), surchargeRate: z.string().optional(), surchargeLabel: z.string().optional(), type: z.string().optional(), taxExempt: z.boolean().optional(), reviewIndicator: z.number().int().optional(), source: z.string().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 }; /** * Make a Payment with Surcharge * * POST /payment */ export const createApiPayment = async (args: CreateApiPaymentArgs, options?: CreateApiPaymentOptions) => { const {baseUrl = "https://sandbox.api.mxmerchant.com/checkout", fetch: fetchFn = fetch, sec0} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.echo != null) query.append("echo", String(args.echo)) if (args.includeCustomerMatches != null) query.append("includeCustomerMatches", String(args.includeCustomerMatches)) if (sec0 !== undefined) headers.set('authorization', `Basic ${btoa(`${sec0.username}:${sec0.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/payment${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(createApiPaymentResponse, await res.json()) };