Avistadocs
Integration Guides

Balance Query

Overview

The balance query endpoint allows you to obtain detailed information about the authenticated account balance in real time. The response includes three types of balance:

  • Gross Balance: Total amount available in the account
  • Blocked Balance: Amounts reserved for pending operations
  • Net Balance: Amount available for immediate use

This endpoint requires a valid Bearer token. See the authentication documentation for more details.

Endpoint

GET /api/balance

Returns the current balance of the authenticated account.

Required Headers

Authorization: Bearer {token}

Request

curl -X GET https://api.avista.global/api/balance \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Response (200 OK)

{
  "grossBalance": 48734.90,
  "blockedBalance": 0.00,
  "netBalance": 48734.90,
  "consultedAt": "2025-11-19T20:18:29.384Z"
}

Response Structure

grossBalancenumbersempre presente

Total gross balance of the account (net balance + blocked balance)

Example: 48734.90

blockedBalancenumbersempre presente

Amount blocked by pending operations (payments being processed, charges awaiting confirmation)

Example: 0.00

netBalancenumbersempre presente

Net balance available for immediate use (grossBalance - blockedBalance)

Example: 48734.90

consultedAtstringsempre presente

Date and time of the query in ISO 8601 format (UTC)

Example: 2025-11-19T20:18:29.384Z

Implementation Examples

Node.js / TypeScript

import axios from 'axios';

interface BalanceResponse {
  grossBalance: number;
  blockedBalance: number;
  netBalance: number;
  consultedAt: string;
}

async function getBalance(token: string): Promise<BalanceResponse> {
  try {
    const response = await axios.get<BalanceResponse>(
      'https://api.avista.global/api/balance',
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    );

    console.log('=== Account Balance ===');
    console.log(`Gross Balance: R$ ${response.data.grossBalance.toFixed(2)}`);
    console.log(`Blocked Balance: R$ ${response.data.blockedBalance.toFixed(2)}`);
    console.log(`Net Balance: R$ ${response.data.netBalance.toFixed(2)}`);
    console.log(`Queried at: ${new Date(response.data.consultedAt).toLocaleString('pt-BR')}`);

    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.error('Error querying balance:', error.response?.data);
      throw new Error(error.response?.data?.message || 'Error querying balance');
    }
    throw error;
  }
}

// Usage
const token = 'your_token_here';
getBalance(token);

Python

import requests
from datetime import datetime
from typing import Dict

def get_balance(token: str) -> Dict:
    """
    Query the account balance

    Args:
        token: Valid Bearer token

    Returns:
        Dictionary with balance information
    """
    url = 'https://api.avista.global/api/balance'
    headers = {
        'Authorization': f'Bearer {token}'
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()

        data = response.json()

        print('=== Account Balance ===')
        print(f"Gross Balance: R$ {data['grossBalance']:.2f}")
        print(f"Blocked Balance: R$ {data['blockedBalance']:.2f}")
        print(f"Net Balance: R$ {data['netBalance']:.2f}")

        consulted_at = datetime.fromisoformat(data['consultedAt'].replace('Z', '+00:00'))
        print(f"Queried at: {consulted_at.strftime('%d/%m/%Y %H:%M:%S')}")

        return data

    except requests.exceptions.RequestException as e:
        print(f'Error querying balance: {e}')
        if hasattr(e.response, 'json'):
            print(f'Details: {e.response.json()}')
        raise

# Usage
token = 'your_token_here'
balance = get_balance(token)

PHP

<?php

function getBalance(string $token): array
{
    $url = 'https://api.avista.global/api/balance';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new Exception("Error querying balance: HTTP $httpCode");
    }

    $data = json_decode($response, true);

    echo "=== Account Balance ===" . PHP_EOL;
    echo "Gross Balance: R$ " . number_format($data['grossBalance'], 2, ',', '.') . PHP_EOL;
    echo "Blocked Balance: R$ " . number_format($data['blockedBalance'], 2, ',', '.') . PHP_EOL;
    echo "Net Balance: R$ " . number_format($data['netBalance'], 2, ',', '.') . PHP_EOL;
    echo "Queried at: " . date('d/m/Y H:i:s', strtotime($data['consultedAt'])) . PHP_EOL;

    return $data;
}

// Usage
$token = 'your_token_here';
$balance = getBalance($token);

Use Cases

1. Financial Management Dashboard

Display the balance in real time on an administrative dashboard:

// Update balance every 30 seconds
setInterval(async () => {
  const balance = await getBalance(token);

  // Update UI
  document.getElementById('gross-balance').textContent =
    `R$ ${balance.grossBalance.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;

  document.getElementById('net-balance').textContent =
    `R$ ${balance.netBalance.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;

  // Low balance alert
  if (balance.netBalance < 1000) {
    showLowBalanceAlert();
  }
}, 30000);

2. Pre-Payment Validation

Verify sufficient balance before making a payment:

async function processPayment(amount: number, token: string) {
  // Query current balance
  const balance = await getBalance(token);

  // Validate available balance
  if (balance.netBalance < amount) {
    throw new Error(
      `Insufficient balance. Available: R$ ${balance.netBalance.toFixed(2)} | ` +
      `Required: R$ ${amount.toFixed(2)}`
    );
  }

  // Proceed with payment
  return await createPixPayment(amount, token);
}

3. Reconciliation Report

Generate reconciliation reports with the current balance:

def generate_reconciliation_report(token: str):
    """Generate reconciliation report"""
    balance = get_balance(token)

    report = {
        'report_date': datetime.now().isoformat(),
        'balance_snapshot': balance,
        'status': 'OK' if balance['netBalance'] > 0 else 'ALERT',
        'blocked_percentage': (
            balance['blockedBalance'] / balance['grossBalance'] * 100
            if balance['grossBalance'] > 0 else 0
        )
    }

    # Save report
    with open(f"reconciliation_{datetime.now().strftime('%Y%m%d')}.json", 'w') as f:
        json.dump(report, f, indent=2)

    return report

Understanding Blocked Balance

The blocked balance represents amounts temporarily unavailable due to:

Response Codes

CodeDescriptionMeaning
200SuccessBalance queried successfully
401Invalid TokenToken not provided, expired, or invalid

See the API Reference for complete details of the response fields.

Considerations

The returned balance reflects the state at the exact moment of the query. For critical operations, always query the balance immediately before the transaction.

  • Cache: We do not recommend caching the balance for more than 1 minute
  • Precision: Values are returned with 2 decimal places
  • Currency: All values are in Brazilian Reais (BRL)

Monitoring and Alerts

Implementing Balance Alerts

class BalanceMonitor {
  constructor(token, thresholds) {
    this.token = token;
    this.thresholds = {
      critical: thresholds.critical || 500,
      warning: thresholds.warning || 2000,
      high: thresholds.high || 10000
    };
  }

  async checkAndAlert() {
    const balance = await getBalance(this.token);
    const netBalance = balance.netBalance;

    if (netBalance < this.thresholds.critical) {
      this.sendAlert('CRITICAL', `Critical balance: R$ ${netBalance.toFixed(2)}`);
    } else if (netBalance < this.thresholds.warning) {
      this.sendAlert('WARNING', `Low balance: R$ ${netBalance.toFixed(2)}`);
    }

    // High blocked balance alert
    const blockedPercentage = (balance.blockedBalance / balance.grossBalance) * 100;
    if (blockedPercentage > 50) {
      this.sendAlert('WARNING', `${blockedPercentage.toFixed(1)}% of balance is blocked`);
    }

    return balance;
  }

  sendAlert(level, message) {
    console.log(`[${level}] ${message}`);
    // Integrate with alerting system (email, SMS, Slack, etc.)
  }
}

// Usage
const monitor = new BalanceMonitor(token, {
  critical: 1000,
  warning: 5000
});

// Run every 5 minutes
setInterval(() => monitor.checkAndAlert(), 5 * 60 * 1000);

Next Steps

On this page