import {z} from 'zod' export type Address = {street: string, number: string, complement?: string | undefined, neighborhood: string, city: string, state: 'AC' | 'AL' | 'AP' | 'AM' | 'BA' | 'CE' | 'DF' | 'ES' | 'GO' | 'MA' | 'MS' | 'MT' | 'MG' | 'PA' | 'PB' | 'PR' | 'PE' | 'PI' | 'RJ' | 'RN' | 'RS' | 'RO' | 'RR' | 'SC' | 'SP' | 'SE' | 'TO', zip_code: string}; export type TransactionClient = {first_name: string, last_name?: string | undefined, document: string, phone?: string | undefined, email: string, address?: Address | undefined}; export type TransactionCard = {holder_name: string, holder_document: string, card_number: string, expiration_month: number, expiration_year: number, security_code: string, create_token?: boolean | undefined, token?: string | undefined}; export type BilletDiscountItem = {limit_date: string, value: number}; export type BilletDiscount = {type: 'VALOR_DATA_FIXA', items: Array}; export type BilletFine = {percentage: string, quantity_days: number}; export type TransactionBilletDto = {due_date: string, issue_date: string, document_kind?: string | undefined, days_until_expiration?: number | undefined, iof_percentage?: string | undefined, messages?: Array | undefined, discount?: BilletDiscount | undefined, fine?: BilletFine | undefined, interest_percentage?: string | undefined}; export type InfoAdditionalDto = {key: string, value: string}; export type SplitEstablishmentDto = {id: number, value: number}; export type SplitDto = {title: string, division: 'PERCENTAGE' | 'CURRENCY', establishments: Array}; export type CreateTransactionDto = {payment_type: 'CREDIT' | 'PIX' | 'BILLET', amount: number, installments?: number | undefined, interest: 'STORE' | 'CLIENT', client?: TransactionClient | undefined, card?: TransactionCard | undefined, billet?: TransactionBilletDto | undefined, session_id?: string | undefined, info_additional?: Array | undefined, split?: SplitDto | undefined, reference_id?: (string | number) | undefined, antifraud_type?: ('THREEDS' | 'IDPAY') | undefined}; export type CreateApiV1MarketplaceTransactionsArgs = {'integration-key': string, 'x-token': string, establishment_id: string, body: CreateTransactionDto}; export type CreateApiV1MarketplaceTransactionsOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const establishment = z.object({first_name: z.string(), last_name: z.string(), document: z.string(), type: z.enum(["INDIVIDUAL", "BUSINESS"]), access_type: z.enum(["ACQUIRER", "BANKING"]), id: z.number()}); export const marketplace = z.object({id: z.number(), type: z.enum(["WHITELABEL", "LICENSED", "REPRESENTATIVE"]), nickname: z.string(), active: z.boolean(), first_name: z.string(), last_name: z.string(), document: z.string()}); export const representative = z.object({id: z.number(), marketplace_id: z.number(), active: z.boolean(), first_name: z.string(), last_name: z.string(), document: z.string()}); export const card = z.object({brand_name: z.string(), first4_digits: z.string(), last4_digits: z.string(), expiration_month: z.string(), expiration_year: z.string(), holder_name: z.string(), token: z.string()}); export const customer = z.object({first_name: z.string(), last_name: z.string().optional(), document: z.string(), phone: z.string().optional(), email: z.string().optional()}); export const pointOfSale = z.object({type: z.enum(["ONLINE", "CHIP", "TAP", "SMART"]), identification_type: z.enum(["CHIP", "CONTACTLESS", "MAGNETIC", "LINK", "API", "CHECKOUT"]).optional(), identification_number: z.string().optional()}); export const acquirer = z.object({name: z.string(), nsu: z.number(), acquirer_nsu: z.number(), end_to_end: z.string(), key: z.string(), gateway_key: z.string(), authorization_number: z.string()}); export const expectedOn = z.object({installment: z.number(), date: z.string(), paid_at: z.string().optional(), amount: z.number(), status: z.enum(["PENDING", "PAID", "CANCELED", "REFUNDED", "FAILED"])}); export const antifraudSession = z.object({analyse_required: z.enum(["THREEDS", "CLEARSALE", "IDPAY"]), analyse_status: z.enum(["APPROVED", "PROCESSING", "WAITING_AUTH", "FAILED", "NO_ANALYSED"]), antifraud_id: z.string().optional(), session: z.string().optional()}); export const paymentResponse = z.object({code: z.string(), message: z.string(), reference: z.string().optional(), authorization_code: z.string().optional(), nsu: z.string().optional(), reason_code: z.string().optional()}); export const infoAdditionalResponse = z.object({key: z.string(), value: z.string()}); export const transactionSplitResponse = z.object({active: z.boolean(), is_origin: z.boolean(), processing: z.boolean(), initial_amount: z.number().optional()}); export const billetDiscountItemResponse = z.object({value: z.number(), limit_date: z.string()}); export const billetDiscountResponse = z.object({type: z.literal("VALOR_DATA_FIXA"), items: z.array(billetDiscountItemResponse)}); export const billetFineResponse = z.object({percentage: z.string(), quantity_days: z.number().gte(1).lte(99)}); export const billetPaymentResponse = z.object({paid_via: z.enum(["QRCODE", "BARCODE"]), date: z.string(), paid_amount: z.number(), interest_value: z.number(), fine: z.number(), deduction_value: z.number(), iof_value: z.number()}); export const billetResponse = z.object({due_date: z.string(), issue_date: z.string(), entry_date: z.string().optional(), document_kind: z.enum(["DUPLICATA_MERCANTIL", "DUPLICATA_SERVICO", "NOTA_PROMISSORIA", "NOTA_PROMISSORIA_RURAL", "RECIBO", "APOLICE_SEGURO", "BOLETO_CARTAO_CREDITO", "BOLETO_PROPOSTA", "BOLETO_DEPOSITO_APORTE", "CHEQUE", "NOTA_PROMISSORIA_DIRETA", "OUTROS"]).optional(), iof_percentage: z.string().optional(), messages: z.array(z.string()).optional(), digitable_line: z.string().optional(), barcode: z.string().optional(), qr_code_pix: z.string().optional(), qr_code_url: z.string().optional(), pdf_url: z.string().optional(), configured_amount: z.number().optional(), configured_original_amount: z.number().optional(), discount: billetDiscountResponse.optional(), fine: billetFineResponse.optional(), interest_percentage: z.string().optional(), payment: billetPaymentResponse.optional()}); export const createTransactionClientResponse = z.object({_id: z.string(), status: z.enum(["CREATED", "PENDING", "APPROVED", "PAID", "FAILED", "REFUNDED", "DISPUTED", "CANCELED", "CHARGEBACK"]), amount: z.number(), original_amount: z.number(), interest: z.enum(["STORE", "CLIENT"]), fees: z.number(), establishment: establishment, marketplace: marketplace, representative: representative, type: z.enum(["CREDIT", "DEBIT", "PIX", "BILLET"]), gateway_authorization: z.enum(["PAYTIME", "ZOOP", "PAGSEGURO"]), card: card, installments: z.number(), customer: customer, point_of_sale: pointOfSale, acquirer: acquirer, expected_on: z.array(expectedOn), created_at: z.string(), emv: z.string().optional(), antifraud: z.array(antifraudSession).optional(), payment_response: paymentResponse.optional(), info_additional: z.array(infoAdditionalResponse).optional(), split: transactionSplitResponse.optional(), reference_id: z.string().optional(), billet: billetResponse.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 }; /** * Criar transação * * POST /v1/marketplace/transactions */ export const createApiV1MarketplaceTransactions = async (args: CreateApiV1MarketplaceTransactionsArgs, options?: CreateApiV1MarketplaceTransactionsOptions) => { const {baseUrl = "https://api.sandbox.paytime.com.br", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['integration-key'] != null) headers.set("integration-key", String(args['integration-key'])) if (args['x-token'] != null) headers.set("x-token", String(args['x-token'])) if (args.establishment_id != null) headers.set("establishment_id", String(args.establishment_id)) if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/marketplace/transactions${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(createTransactionClientResponse, await res.json()) };