import {z} from 'zod' export type ExternalIdPayments = string; export type CustomerObject = {identifier: string, name: string, external_id?: ExternalIdPayments | undefined}; export type CustomerId = string; export type MetadataPayments = {[key: string]: string}; export type BankAccountObject = {holder: {identifier: string, name: string}, details: {account_type: 'CHECKINGS' | 'SAVINGS' | 'PAYMENTS', agency: string, institution: string, number: string}, external_id?: ExternalIdPayments | undefined, metadata?: MetadataPayments | undefined}; export type BankAccountId = string; export type CreatePaymentAuthorizationImmediate = {payment_method: 'PIX_OF_IMMEDIATE', description: string, external_id?: string | undefined, return_url: string, payer: {customer: CustomerObject | CustomerId, institution?: string | undefined, representative_identifier?: string | undefined}, beneficiary: {type: 'BANK_ACCOUNT', target: BankAccountObject | BankAccountId}, payment_method_configuration: {amount: number, statement_description: string}, metadata?: MetadataPayments | undefined}; export type CreatePaymentAuthorizationScheduled = {payment_method: 'PIX_OF_SCHEDULED', description: string, external_id?: string | undefined, return_url: string, payer: {customer: CustomerObject | CustomerId, institution?: string | undefined, representative_identifier?: string | undefined}, beneficiary: {type: 'BANK_ACCOUNT', target: BankAccountObject | BankAccountId}, payment_method_configuration: {amount: number, statement_description: string, dates: Array}, metadata?: MetadataPayments | undefined}; export type PeriodLimitSmartTransfers = {quantity_limit?: number | undefined, transaction_limit?: string | undefined}; export type PeriodicLimitsSmartTransfers = {day?: PeriodLimitSmartTransfers | undefined, week?: PeriodLimitSmartTransfers | undefined, month?: PeriodLimitSmartTransfers | undefined, year?: PeriodLimitSmartTransfers | undefined}; export type CreatePaymentAuthorizationSmartTransfers = {payment_method: 'PIX_OF_SMART_TRANSFERS', description: string, external_id?: (string | null) | undefined, return_url: string, expiration_date_time?: (string | null) | undefined, payer: {customer: CustomerObject | CustomerId, institution: string, representative_identifier?: (string | null) | undefined, account_details?: ({account_type: 'CACC' | 'SVGS' | 'SLRY' | 'TRAN', ispb: string, issuer: string, number: string}) | undefined}, beneficiary: {type: 'BANK_ACCOUNT', target: BankAccountObject | BankAccountId}, payment_method_configuration: {total_allowed_amount?: string | undefined, payment_transaction_limit?: string | undefined, periodic_limits?: PeriodicLimitsSmartTransfers | undefined, start_date_time?: string | undefined}, metadata?: MetadataPayments | undefined}; export type CreateApiPaymentsBrPaymentAuthorizationsArgs = {'X-Belvo-API-Resource-Version'?: 'Payments-BR.V2' | undefined, body: CreatePaymentAuthorizationImmediate | CreatePaymentAuthorizationScheduled | CreatePaymentAuthorizationSmartTransfers}; export type CreateApiPaymentsBrPaymentAuthorizationsOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const periodLimitSmartTransfers = z.object({quantity_limit: z.number().int().gte(1).optional(), transaction_limit: z.string().optional()}); export const periodicLimitsSmartTransfers = z.object({day: periodLimitSmartTransfers.optional(), week: periodLimitSmartTransfers.optional(), month: periodLimitSmartTransfers.optional(), year: periodLimitSmartTransfers.optional()}); export const metadataPayments = z.record(z.string(), z.string().max(500)); export const paymentAuthorization = z.object({id: z.string(), created_at: z.string(), updated_at: z.string(), status: z.enum(["AWAITING_AUTHORIZATION", "PARTIALLY_ACCEPTED", "AUTHORIZED", "FAILED", "CONSUMED", "REVOKED"]), status_reason_code: z.string().nullable(), status_reason_message: z.string().nullable(), status_updated_at: z.string(), authorized_at: z.string().nullable(), external_id: z.string().nullable(), description: z.string().min(1).max(140), return_url: z.string().min(1).max(2048), expiration_date_time: z.string().nullable().optional(), payment_method: z.enum(["PIX_OF_IMMEDIATE", "PIX_OF_SCHEDULED", "PIX_OF_SMART_TRANSFERS"]), payer: z.object({customer: z.string().optional(), institution: z.string().optional(), representative_identifier: z.string().min(11).max(14).nullable().optional(), bank_account: z.object({holder: z.object({identifier: z.string().optional()}).optional(), details: z.object({account_type: z.enum(["CHECKINGS", "SAVINGS", "SALARY", "PAYMENTS"]).optional(), agency: z.string().optional(), code: z.string().optional(), number: z.string().optional()}).optional()}).nullable().optional()}), beneficiary: z.object({type: z.literal("BANK_ACCOUNT").optional(), target: z.string().optional()}), payment_method_configuration: z.union([z.object({amount: z.string().optional(), statement_description: z.string().min(1).max(140).optional(), authorization_url: z.string().min(1).max(2048).optional()}), z.object({amount: z.string().optional(), statement_description: z.string().min(1).max(140).optional(), dates: z.array(z.string()).optional(), authorization_url: z.string().min(1).max(2048).optional()}), z.object({total_allowed_amount: z.string().optional(), payment_transaction_limit: z.string().optional(), periodic_limits: periodicLimitsSmartTransfers.optional(), start_date_time: z.string().optional(), authorization_url: z.string().min(1).max(2048).optional()})]), charges: z.array(z.string()), metadata: metadataPayments.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 a new Payment Authorization * * POST /payments/br/payment-authorizations/ */ export const createApiPaymentsBrPaymentAuthorizations = async (args: CreateApiPaymentsBrPaymentAuthorizationsArgs, options?: CreateApiPaymentsBrPaymentAuthorizationsOptions) => { const {baseUrl = "https://sandbox.belvo.com", 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 (args['X-Belvo-API-Resource-Version'] != null) headers.set("X-Belvo-API-Resource-Version", String(args['X-Belvo-API-Resource-Version'])) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/payments/br/payment-authorizations/${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(paymentAuthorization, await res.json()) };