import {z} from 'zod' export type Currency = 'mxn' | 'cop' | 'brl' | 'usd' | 'eur' | 'gbp'; export type InstrumentType = 'mx_direct_debit_card' | 'mx_clabe'; export type ChargeCreateInlineInstrument = {type: InstrumentType, identifier: string, bank?: (string | null) | undefined}; export type DocumentType = 'mx_rfc' | 'mx_curp' | 'passport'; export type ChargeCreateInlineCustomer = {name: string, document_type: DocumentType, document_number: string, email?: (string | null) | undefined, phone_number?: (string | null) | undefined}; export type ChargeCreate = {currency: Currency, instrument_id?: (string | null) | undefined, customer_id?: (string | null) | undefined, amount: number, reference?: (string | null) | undefined, inline_instrument?: (ChargeCreateInlineInstrument | null) | undefined, inline_customer?: (ChargeCreateInlineCustomer | null) | undefined}; export type CreateApiChargesArgs = {'X-API-Key'?: (string | null) | undefined, 'Idempotency-Key'?: (string | null) | undefined, body: ChargeCreate}; export type CreateApiChargesOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const currency = z.enum(["mxn", "cop", "brl", "usd", "eur", "gbp"]); export const chargeStatus = z.enum(["verification_in_progress", "pending", "processing", "confirmed", "declined", "chargeback", "canceled"]); export const declinedReason = z.enum(["insufficient_funds", "account_blocked", "undetermined", "risk_engine", "account_does_not_exist", "account_canceled", "account_in_other_currency", "account_not_belongs_to_bank", "transaction_duplicated", "client_order_declined_pay_to_issuer", "client_order_amount_is_more_than_authorized", "client_order_canceled", "client_service_not_authorized", "payment_order_expired", "client_rejected_charge"]); export const chargeRiskStatus = z.enum(["pending", "ok", "cancelled_by_risk"]); export const chargeResponse = z.object({org_id: z.string(), instrument_id: z.string().nullable().optional(), customer_id: z.string().nullable().optional(), amount: z.number().gt(0), currency: currency.nullable().optional(), reference: z.string().max(255).nullable().optional(), inline_instrument: z.object({}).nullable().optional(), inline_customer: z.object({}).nullable().optional(), id: z.string(), status: chargeStatus, declined_reason: declinedReason.nullable().optional(), declined_reason_rail: z.string().nullable().optional(), created_at: z.string(), updated_at: z.string().nullable().optional(), chargeback_at: z.string().nullable().optional(), result_at: z.string().nullable().optional(), risk_status: chargeRiskStatus.nullable().optional(), risk_evaluated_at: z.string().nullable().optional(), risk_reasons: z.array(z.string()).nullable().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 Charge * * POST /charges */ export const createApiCharges = async (args: CreateApiChargesArgs, options: CreateApiChargesOptions) => { const {baseUrl, 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['X-API-Key'] != null) headers.set("X-API-Key", String(args['X-API-Key'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) const url = `${baseUrl.replace(/\/+$/, '')}/charges${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(chargeResponse, await res.json()) };