import {z} from 'zod' export type ProductTypeEnum = 'vehicle_debt' | 'other' | 'batch_payment' | 'insurance' | 'debt_search'; export type VehicleProductTypeEnum = 'services' | 'ticket' | 'ipva' | 'licensing' | 'ipva-unique' | 'ipva-installment' | 'insurance' | 'expired_insurance'; export type OrderItemRequestDTO = {product_id: string, amount: number | string, description: string | null, type: ProductTypeEnum | VehicleProductTypeEnum | null, metadata?: (Record | null) | undefined}; export type PaymentMethodEnum = 'credit_card' | 'debit_card' | 'voucher' | 'bank_slip' | 'pix' | 'cash' | 'tokenized_credit_card'; export type CardOperationTypeEnum = 'authorize_and_capture' | 'authorize_only' | 'pre_authorize' | 'capture' | 'cancel'; export type BrandEnum = 'visa' | 'mastercard' | 'elo' | 'hipercard' | 'unionpay' | 'maestro' | 'dinersclub' | 'discover' | 'sorocred' | 'jcb' | 'ticketlog'; export type CustomerAddressRequestDTO = {zip_code: string, line_1: string, line_2?: (string | null) | undefined, state: string, city: string}; export type CardRequestDTO = {number: string, holder_name: string, holder_document: string, exp_month: number, exp_year: number, cvv: string, brand: BrandEnum, billing_address: CustomerAddressRequestDTO}; export type CreditCardRequestDTO = {installments?: number | undefined, statement_descriptor?: (string | null) | undefined, operation_type?: (CardOperationTypeEnum | null) | undefined, card?: (CardRequestDTO | null) | undefined, card_token?: (string | null) | undefined, card_hash?: (string | null) | undefined}; export type BankSlipRequestDTO = {name?: (string | null) | undefined, document: string}; export type AdditionalInformationRequestDTO = {name: string, document: string}; export type PixRequestDTO = {expires_in: string, expires_at: string, additional_information: AdditionalInformationRequestDTO}; export type VoucherRequestDTO = {statement_descriptor?: (string | null) | undefined, card: CardRequestDTO}; export type PaymentRequestDTO = {payment_method: PaymentMethodEnum, amount?: (number | string | null) | undefined, credit_card?: (CreditCardRequestDTO | null) | undefined, bank_slip?: (BankSlipRequestDTO | null) | undefined, pix?: (PixRequestDTO | null) | undefined, voucher?: (VoucherRequestDTO | null) | undefined}; export type CustomerRequestDTO = {name: string, email: string, phone: string, document: string, address?: (CustomerAddressRequestDTO | null) | undefined, metadata?: (Record | null) | undefined}; export type AntifraudLastPurchaseDecisionEnum = 'approved' | 'denied'; export type AntifraudFirstPurchaseTypeEnum = 'credit_card' | 'debit_card' | 'voucher'; export type OrderRequestAntifraudInfo = {last_purchase_decision?: (AntifraudLastPurchaseDecisionEnum | null) | undefined, days_since_first_purchase?: (number | null) | undefined, first_purchase_amount?: (number | null) | undefined, first_purchase_payment_type?: (AntifraudFirstPurchaseTypeEnum | null) | undefined, purchase_history_count?: (number | null) | undefined, was_chargeback?: (boolean | null) | undefined, days_since_last_purchase?: (number | null) | undefined, cards_used_last_year?: (number | null) | undefined, customer_purchase_history_count?: (number | null) | undefined, customer_account_age?: (number | null) | undefined, metadata?: (Record | null) | undefined}; export type OrderRequestDTO = {items: Array, payments: Array, customer?: (CustomerRequestDTO | null) | undefined, discount_code?: (string | null) | undefined, customer_id?: (string | null) | undefined, closed?: boolean | undefined, ip_address?: (string | null) | undefined, session_id?: (string | null) | undefined, device?: (Record | null) | undefined, metadata?: (Record | null) | undefined, antifraud_enabled?: boolean | undefined, external_id?: (string | null) | undefined, antifraud_info?: (OrderRequestAntifraudInfo | null) | undefined, amount?: (number | string | null) | undefined}; export type CreateApiOrderArgs = {body: OrderRequestDTO}; export type CreateApiOrderOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const orderResponseDTO = z.object({order_id: z.string()}); export const orderItemStatusEnum = z.enum(["pending", "processing", "paid", "canceled", "failed", "settled"]); export const itemResponseDTO = z.object({product_id: z.string(), amount: z.number(), type: z.string().nullable().optional(), status: orderItemStatusEnum, description: z.string().nullable().optional(), metadata: z.object({}).nullable().optional()}); export const v2PackagesEnterpriseSchemasOrderOrderResponseSchemasAddressResponseDTO = z.object({zip_code: z.string().nullable().optional(), state: z.string().nullable().optional(), city: z.string().nullable().optional(), line_1: z.string().nullable().optional(), line_2: z.string().nullable().optional(), metadata: z.object({}).optional()}); export const customerResponseDTO = z.object({name: z.string(), phone: z.string().nullable().optional(), email: z.string().nullable().optional(), document: z.string().nullable().optional(), address: v2PackagesEnterpriseSchemasOrderOrderResponseSchemasAddressResponseDTO.nullable().optional(), metadata: z.object({}).optional()}); export const orderStatusEnum = z.enum(["pending", "processing", "paid", "canceled", "cancellation_requested", "failed"]); export const v2PackagesEnterpriseSchemasOrderOrderResponseSchemasCardResponseDTO = z.object({last_four_digits: z.union([z.string(), z.number().int()]).nullable().optional(), brand: z.string().nullable().optional(), holder_name: z.string().nullable().optional(), exp_month: z.number().int().nullable().optional(), exp_year: z.number().int().nullable().optional(), status: z.string().nullable().optional(), billing_address: v2PackagesEnterpriseSchemasOrderOrderResponseSchemasAddressResponseDTO.nullable().optional(), type: z.string().nullable().optional(), created_at: z.string().optional(), updated_at: z.string().optional()}); export const bankSlipResponseDTO = z.object({line: z.string().nullable().optional(), barcode: z.string().nullable().optional(), url: z.string().nullable().optional(), pdf: z.string().nullable().optional(), qr_code: z.string().nullable().optional(), nosso_numero: z.string().nullable().optional(), document_number: z.string().nullable().optional(), instructions: z.string().nullable().optional(), due_at: z.string().nullable().optional()}); export const pixResponseDTO = z.object({qr_code: z.string().nullable().optional(), qr_code_url: z.string().nullable().optional(), additional_information: z.object({}).nullable().optional()}); export const v2PackagesEnterpriseSchemasOrderOrderResponseSchemasGatewayResponseDTO = z.object({name: z.string().nullable().optional(), message: z.string().nullable().optional(), code: z.string().nullable().optional(), metadata: z.object({}).nullable().optional()}); export const v2PackagesEnterpriseSchemasOrderOrderResponseSchemasAntifraudResponseDTO = z.object({name: z.string().nullable().optional(), status: z.string().nullable().optional(), message: z.string().nullable().optional(), code: z.string().nullable().optional(), score: z.number().int().nullable().optional(), metadata: z.object({}).nullable().optional()}); export const v2PackagesEnterpriseSchemasOrderOrderResponseSchemasLastTransactionResponseDTO = z.object({transaction_id: z.string(), transaction_type: z.string(), amount: z.number(), status: z.string().nullable().optional(), success: z.boolean().nullable().optional(), installments: z.number().int().nullable().optional(), operation_type: z.string().nullable().optional(), gateway_id: z.string().nullable().optional(), acquirer_name: z.string().nullable().optional(), acquirer_transaction_id: z.string().nullable().optional(), acquirer_nsu: z.string().nullable().optional(), acquirer_auth_code: z.string().nullable().optional(), acquirer_message: z.string().nullable().optional(), acquirer_return_code: z.string().nullable().optional(), card: v2PackagesEnterpriseSchemasOrderOrderResponseSchemasCardResponseDTO.nullable().optional(), bank_slip: bankSlipResponseDTO.nullable().optional(), pix: pixResponseDTO.nullable().optional(), created_at: z.string().optional(), updated_at: z.string().optional(), gateway_response: v2PackagesEnterpriseSchemasOrderOrderResponseSchemasGatewayResponseDTO.nullable().optional(), antifraud_response: v2PackagesEnterpriseSchemasOrderOrderResponseSchemasAntifraudResponseDTO.nullable().optional()}); export const chargebackReasonDTO = z.object({chageback_date: z.string().nullable().optional(), reason: z.string().nullable().optional(), code: z.string().nullable().optional(), justification: z.string().nullable().optional()}); export const v2PackagesEnterpriseSchemasOrderOrderResponseSchemasChargeResponseDTO = z.object({charge_id: z.string(), code: z.string().nullable().optional(), gateway_id: z.string().nullable().optional(), amount: z.number(), original_amount: z.number().nullable().optional(), status: z.string(), payment_method: z.string().nullable().optional(), paid_at: z.string().nullable().optional(), last_transaction: v2PackagesEnterpriseSchemasOrderOrderResponseSchemasLastTransactionResponseDTO.nullable().optional(), chargeback_reason: chargebackReasonDTO.nullable().optional(), created_at: z.string().optional(), updated_at: z.string().optional()}); export const orderDetailResponseDTO = z.object({order_id: z.string(), closed: z.boolean(), items: z.array(itemResponseDTO), customer: customerResponseDTO.nullable().optional(), status: orderStatusEnum, closed_at: z.string().nullable().optional(), external_id: z.string().nullable().optional(), charges: z.array(v2PackagesEnterpriseSchemasOrderOrderResponseSchemasChargeResponseDTO), created_at: z.string().nullable().optional(), updated_at: z.string().nullable().optional(), metadata: z.object({}).optional()}); export const createApiOrderResponse = z.union([orderResponseDTO, orderDetailResponseDTO]); 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 }; /** * Criar Pedido de Pagamento * * POST /order/ */ export const createApiOrder = async (args: CreateApiOrderArgs, options?: CreateApiOrderOptions) => { const {baseUrl = "https://api.b2b.usezapay.com.br/v2", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/order/${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(createApiOrderResponse, await res.json()) };