import {z} from 'zod' export type PostChargeRequest = {payment_method: 'card', amount: number, currency_code?: string | undefined, initiator_id: string, reference_id?: string | undefined, local_datetime: unknown, channel?: ('standalone_device' | 'standalone_mobile' | 'website' | 'app' | 'payment_link') | undefined, card_transaction?: ({type: 'credit' | 'debit' | 'voucher', operation_type: 'pre-auth' | 'auth_only' | 'auth_and_capture', installments?: number | undefined, installments_type?: ('none' | 'issuer' | 'merchant') | undefined, statement_descriptor?: string | undefined, currency_conversion?: {token: string, currency_code: string, converted_amount: number} | undefined, card: {number: unknown, expiration_date: unknown, entry_mode: 'magstripe' | 'emv' | 'emv_contacless' | 'contactless' | 'qr_code' | 'manual' | 'credentials_on_file', holder_name?: string | undefined, holder_document_number?: string | undefined, cvv?: unknown | undefined, emv_data?: string | undefined, track_1?: string | undefined, track_2?: string | undefined, track_3?: string | undefined, sequence_number?: string | undefined, fallback?: boolean | undefined, token: {number: string, expiration_date: unknown, cryptogram?: string | undefined, eci?: string | undefined, requestor_id?: string | undefined}, brand?: ('visa' | 'mastercard' | 'amex' | 'hipercard' | 'elo' | 'jcb' | 'aura' | 'dinners') | undefined}, authentication?: ({type: 'offline_pin' | 'online_pin' | 'wallet' | 'emv_3ds', online_pin?: ({algorithm: 'dukpt_3des', ksi?: string | undefined, ksn?: string | undefined, pin_block?: string | undefined}) | undefined, wallet?: ({cryptogram?: string | undefined, eci?: ('00' | '01' | '02' | '05' | '06' | '07') | undefined, type?: ('applepay' | 'googlepay' | 'clicktopay') | undefined}) | undefined, emv_3ds?: ({directory_server_id: string, cryptogram: string, eci?: ('00' | '01' | '02' | '05' | '06' | '07' | 'DATA_ONLY') | undefined, status?: ('Y' | 'N' | 'U' | 'A' | 'R' | 'I') | undefined, version?: string | undefined, xid?: string | undefined}) | undefined}) | undefined, merchant_category_code?: string | undefined}) | undefined, sub_merchant?: ({id: string, payment_facilitator_id?: string | undefined, name?: string | undefined, document: string, document_type: 'cpf' | 'cnpj' | 'passport', email?: string | undefined, phone_number?: string | undefined, site?: string | undefined, legal_name?: string | undefined, address?: ({street?: string | undefined, number?: string | undefined, complement?: string | undefined, city?: string | undefined, state?: string | undefined, district?: string | undefined, country_code?: string | undefined, zip_code?: string | undefined}) | undefined, gateway_id?: string | undefined}) | undefined, initiator?: ({initiating_entity?: ('account_holder' | 'merchant') | undefined, initiating_reason?: ('credentials_on_file' | 'standing_order' | 'subscription' | 'installment' | 'partial_shipment' | 'delayed_charge' | 'no_show' | 'retry' | 'deferred_payment' | 'debit_recovery' | 'installment_payment' | 'marketplace' | 'peer_to_peer' | 'stage_back_to_back' | 'stored_value' | 'bill_payment' | 'card_funds_transfer') | undefined}) | undefined, first_transaction?: ({brand_transaction_id?: string | undefined, transaction_id?: string | undefined}) | undefined, partner_platform_id?: string | undefined, print_line_size?: number | undefined, payee?: ({destination_type?: 'digital_wallet' | undefined, destination_name?: string | undefined, name?: string | undefined, document?: string | undefined, document_type?: ('cpf' | 'cnpj') | undefined}) | undefined, customer?: ({name?: string | undefined, document?: string | undefined, document_type?: ('cpf' | 'cnpj' | 'passport') | undefined, email?: string | undefined, phone?: ({country?: string | undefined, area?: string | undefined, number?: string | undefined, type?: ('home' | 'work' | 'mobile') | undefined}) | undefined}) | undefined, items?: (Array<{amount?: number | undefined, description?: string | undefined, quantity?: number | undefined, code?: string | undefined}>) | undefined}; export type CreateApiChargesArgs = {Host: string, body: PostChargeRequest}; export type CreateApiChargesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const postChargeResponse = z.object({id: z.string(), initiator_id: z.string(), reference_id: z.string().optional(), amount: z.number().int(), payment_method: z.literal("card"), status: z.enum(["authorized", "paid", "canceled", "declined"]), created_at: z.string(), card_transaction: z.object({type: z.enum(["credit", "debit", "voucher"]), funding_source: z.enum(["credit", "debit", "prepaid"]).optional(), result: z.enum(["success", "failed"]), transaction_id: z.string(), operation_id: z.string(), brand_transaction_id: z.string().optional(), authorization_code: z.string().min(6).max(6).optional(), acquirer_message: z.string().optional(), acquirer_return_code: z.string().min(2).max(4), brand_return_code: z.string().optional(), merchant_advice_code: z.string().optional(), additional_data: z.array(z.object({name: z.string(), value: z.string()})).optional(), card: z.object({brand: z.string(), remaining_balance: z.number().int().optional(), emv_response: z.string().optional(), payment_account_reference: z.string().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 }; /** * Criação de uma nova cobrança.

A autenticação no endpoint é feita da seguinte forma: * * POST /charges */ export const createApiCharges = async (args: CreateApiChargesArgs, options?: CreateApiChargesOptions) => { const {baseUrl = "https://payments.stone.com.br/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Host != null) headers.set("Host", String(args.Host)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) 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(postChargeResponse, await res.json()) };