Avistadocs
Integration Guides

Quickstart

Prerequisites

Before you begin, you need to have:

X.509 certificate (.pem file) linked to your account
OAuth credentials (clientId and clientSecret)

Request your credentials and certificate through the Avista Dashboard.

1. Set Up Environment

Create a .env file with your credentials:

AVISTA_CLIENT_ID=account-93-your-id
AVISTA_CLIENT_SECRET=your-secret-password
AVISTA_API_URL=https://api.avista.global

Save your certificate as client-cert.pem in the project directory.

2. Install Dependencies

npm install axios dotenv
pip install requests python-dotenv

3. Complete Code

The example below authenticates, checks the balance, and creates a PIX charge:

require('dotenv').config();
const axios = require('axios');
const fs = require('fs');

const API_URL = process.env.AVISTA_API_URL;
const certificate = fs.readFileSync('./client-cert.pem', 'utf8');
const encodedCert = encodeURIComponent(certificate);

// 1. Get token
async function getToken() {
  const response = await axios.post(`${API_URL}/api/auth/token`, {
    clientId: process.env.AVISTA_CLIENT_ID,
    clientSecret: process.env.AVISTA_CLIENT_SECRET
  }, {
    headers: {
      'Content-Type': 'application/json',
      'X-SSL-Client-Cert': encodedCert
    }
  });
  return response.data.access_token;
}

// 2. Check balance
async function getBalance(token) {
  const response = await axios.get(`${API_URL}/api/balance`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  return response.data;
}

// 3. Create PIX charge
async function createPixCharge(token, value, description, externalId, payer) {
  const response = await axios.post(`${API_URL}/api/pix/cash-in`, {
    transaction: {
      value,
      description,
      externalId,
      expirationTime: 3600, // 1 hour
      generateQrCode: true
    },
    payer: {
      fullName: payer.name,
      document: payer.document
    }
  }, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });
  return response.data;
}

// Run
async function main() {
  try {
    // Authenticate
    console.log('Authenticating...');
    const token = await getToken();
    console.log('Token obtained successfully!');

    // Check balance
    console.log('\nChecking balance...');
    const balance = await getBalance(token);
    console.log(`Available balance: R$ ${balance.netBalance.toFixed(2)}`);

    // Create charge
    console.log('\nCreating PIX charge...');
    const charge = await createPixCharge(token, 100.00, 'Integration test', 'ORDER-001', {
      name: 'John Smith',
      document: '12345678901'
    });

    console.log(`\nCharge created!`);
    console.log(`ID: ${charge.transactionId}`);
    console.log(`Status: ${charge.status}`);
    console.log(`PIX Copy and Paste: ${charge.pixCode}`);
    console.log(`Expires at: ${charge.expirationDate}`);

  } catch (error) {
    console.error('Error:', error.response?.data || error.message);
  }
}

main();
import os
import urllib.parse
import requests
from dotenv import load_dotenv

load_dotenv()

API_URL = os.getenv('AVISTA_API_URL')

# Load certificate
with open('client-cert.pem', 'r') as f:
    certificate = f.read()
    encoded_cert = urllib.parse.quote(certificate)

# 1. Get token
def get_token():
    response = requests.post(f'{API_URL}/api/auth/token',
        json={
            'clientId': os.getenv('AVISTA_CLIENT_ID'),
            'clientSecret': os.getenv('AVISTA_CLIENT_SECRET')
        },
        headers={
            'Content-Type': 'application/json',
            'X-SSL-Client-Cert': encoded_cert
        }
    )
    response.raise_for_status()
    return response.json()['access_token']

# 2. Check balance
def get_balance(token):
    response = requests.get(f'{API_URL}/api/balance',
        headers={'Authorization': f'Bearer {token}'}
    )
    response.raise_for_status()
    return response.json()

# 3. Create PIX charge
def create_pix_charge(token, value, description, external_id, payer_name, payer_document):
    response = requests.post(f'{API_URL}/api/pix/cash-in',
        json={
            'transaction': {
                'value': value,
                'description': description,
                'externalId': external_id,
                'expirationTime': 3600,
                'generateQrCode': True
            },
            'payer': {
                'fullName': payer_name,
                'document': payer_document
            }
        },
        headers={
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }
    )
    response.raise_for_status()
    return response.json()

# Run
def main():
    try:
        # Authenticate
        print('Authenticating...')
        token = get_token()
        print('Token obtained successfully!')

        # Check balance
        print('\nChecking balance...')
        balance = get_balance(token)
        print(f"Available balance: R$ {balance['netBalance']:.2f}")

        # Create charge
        print('\nCreating PIX charge...')
        charge = create_pix_charge(
            token,
            100.00,
            'Integration test',
            'ORDER-001',
            'John Smith',
            '12345678901'
        )

        print(f"\nCharge created!")
        print(f"ID: {charge['transactionId']}")
        print(f"Status: {charge['status']}")
        print(f"PIX Copy and Paste: {charge['pixCode']}")
        print(f"Expires at: {charge['expirationDate']}")

    except requests.exceptions.RequestException as e:
        print(f'Error: {e.response.json() if e.response else e}')

if __name__ == '__main__':
    main()

4. Run

node quickstart.js
python quickstart.py

Expected output:

Authenticating...
Token obtained successfully!

Checking balance...
Available balance: R$ 48734.90

Creating PIX charge...

Charge created!
ID: 7845
Status: PENDING
PIX Copy and Paste: 00020126580014br.gov.bcb.pix...
Expires at: 2024-01-20T14:30:00.000Z

5. Receive Notifications (Webhook)

Set up an endpoint to receive notifications when a payment is confirmed:

// Express.js
app.post('/webhook/avista', (req, res) => {
  const { event, transactionId, status, finalAmount } = req.body;

  if (event === 'CashIn' && status === 'CONFIRMED') {
    console.log(`Payment ${transactionId} confirmed: R$ ${finalAmount}`);
    // Update order in your system
  }

  res.status(200).send('OK');
});

Configure the webhook URL in the Avista Dashboard. See the Webhooks Guide for more details.

Next Steps

Troubleshooting

On this page