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:
SAFIRAPAY_CLIENT_ID=account-93-your-id
SAFIRAPAY_CLIENT_SECRET=your-secret-password
SAFIRAPAY_API_URL=https://api.safirapay.comSave your certificate as client-cert.pem in the project directory.
2. Install Dependencies
npm install axios dotenvpip install requests python-dotenv3. 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.SAFIRAPAY_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.SAFIRAPAY_CLIENT_ID,
clientSecret: process.env.SAFIRAPAY_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('SAFIRAPAY_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('SAFIRAPAY_CLIENT_ID'),
'clientSecret': os.getenv('SAFIRAPAY_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.jspython quickstart.pyExpected 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.000Z5. Receive Notifications (Webhook)
Set up an endpoint to receive notifications when a payment is confirmed:
// Express.js
app.post('/webhook/safirapay', (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
Authentication
Understand the authentication flow in detail
PIX Cash-In
Explore all PIX charge options
PIX Cash-Out
Send PIX payments
Cash-Out via QR Code
Pay via PIX QR Code
Webhooks
Set up real-time notifications