API Examples
Complete Workflow Example
This section provides practical examples of using the Zafira API for common operations.
Authentication
Login and Get Token
bash
# Login to get authentication token
curl -X POST https://zafira-app.vratts.com/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "admin@local.com",
"password": "admin@2025"
}'Response:
json
{
"status": "success",
"message": "Login successful",
"data": {
"token": "1|abcdef1234567890...",
"user": {
"id": 1,
"email": "admin@local.com",
"name": "Admin User"
}
}
}Wallet Operations
1. Get Wallet Details
bash
# Get wallet information
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
https://zafira-app.vratts.com/api/wallet/12. Get Wallet Balance
bash
# Get wallet balance and tokens
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
https://zafira-app.vratts.com/api/wallet/1/balance3. Get Wallet Tokens
bash
# Get all tokens in wallet
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
https://zafira-app.vratts.com/api/wallet/1/tokensCharge Management
Create a Payment Charge
bash
# Create a charge for 0.1 ETH
curl -X POST \
-H "Authorization: Bearer 1|abcdef1234567890..." \
-H "Content-Type: application/json" \
-d '{
"token": "ETH",
"amount": 0.1,
"expires": 600,
"mode": "dynamic"
}' \
https://zafira-app.vratts.com/api/wallet/1/charge/createResponse:
json
{
"status": "success",
"message": "Wallet charge made successfully",
"data": {
"id": 1,
"amount": "0.100000000000000000",
"status": "pending",
"mode": "dynamic",
"expires": 600,
"content": "ethereum:0x0b88b41fdc5b2127c4082145fc34828b7d20a301@97?data=0xa9059cbb...",
"uuid": "550e8400-e29b-41d4-a716-446655440000",
"created_at": "2024-01-01 00:00:00"
}
}Generate Payment Link
javascript
// Generate payment link from UUID
const chargeUuid = "550e8400-e29b-41d4-a716-446655440000";
const paymentLink = `https://zafira-app.domain.com/wallet/pay/${chargeUuid}`;
console.log(paymentLink);
// Output: https://zafira-app.domain.com/wallet/pay/550e8400-e29b-41d4-a716-446655440000Generate QR Code
javascript
// Generate QR code from charge content
const QRCode = require('qrcode');
const chargeContent = "ethereum:0x0b88b41fdc5b2127c4082145fc34828b7d20a301@97?data=0xa9059cbb...";
QRCode.toDataURL(chargeContent, function (err, url) {
if (err) throw err;
console.log('QR Code:', url);
});Transaction Management
Get Transaction History
bash
# Get paginated transaction history
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
"https://zafira-app.vratts.com/api/wallet/1/transaction?page=1&limit=10&token=ETH"Create Transaction
bash
# Create a transaction to send 0.05 ETH
curl -X POST \
-H "Authorization: Bearer 1|abcdef1234567890..." \
-H "Content-Type: application/json" \
-d '{
"amount": 0.05,
"token": "ETH",
"address": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6"
}' \
https://zafira-app.vratts.com/api/wallet/1/transaction/createGet Transaction Details
bash
# Get specific transaction details
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
https://zafira-app.vratts.com/api/wallet/1/transaction/show/1Webhook Management
Create Webhook
bash
# Create webhook for charge events
curl -X POST \
-H "Authorization: Bearer 1|abcdef1234567890..." \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-app.com/webhooks/zafira",
"type": "charge",
"events": ["created", "paid", "expired"],
"signature": "your-webhook-secret-key",
"with_headers": {
"Authorization": "Bearer your-app-token",
"X-Custom-Header": "custom-value"
}
}' \
https://zafira-app.vratts.com/api/wallet/1/webhook/createGet Webhook Details
bash
# Get all webhooks for wallet
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
https://zafira-app.vratts.com/api/wallet/1/webhookGet Available Webhook Types
bash
# Get available webhook types
curl -H "Authorization: Bearer 1|abcdef1234567890..." \
https://zafira-app.vratts.com/api/wallet/1/webhook/typesJavaScript Integration Examples
Complete Payment Flow
javascript
class ZafiraAPI {
constructor(baseURL, token) {
this.baseURL = baseURL;
this.token = token;
}
async request(endpoint, options = {}) {
const response = await fetch(`${this.baseURL}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
...options.headers
}
});
return response.json();
}
// Create payment charge
async createCharge(walletId, token, amount, expires = 300) {
return this.request(`/api/wallet/${walletId}/charge/create`, {
method: 'POST',
body: JSON.stringify({
token,
amount,
expires,
mode: 'dynamic'
})
});
}
// Get wallet balance
async getWalletBalance(walletId) {
return this.request(`/api/wallet/${walletId}/balance`);
}
// Get transaction history
async getTransactions(walletId, page = 1, limit = 10, token = null) {
const params = new URLSearchParams({ page, limit });
if (token) params.append('token', token);
return this.request(`/api/wallet/${walletId}/transaction?${params}`);
}
// Create webhook
async createWebhook(walletId, url, type, events, signature = null) {
return this.request(`/api/wallet/${walletId}/webhook/create`, {
method: 'POST',
body: JSON.stringify({
url,
type,
events,
signature,
with_headers: {
'Authorization': `Bearer ${this.token}`
}
})
});
}
}
// Usage example
const api = new ZafiraAPI('https://zafira-app.vratts.com', 'your-token');
// Create a charge
api.createCharge(1, 'ETH', 0.1, 600)
.then(response => {
if (response.status === 'success') {
const charge = response.data;
const paymentLink = `https://zafira-app.domain.com/wallet/pay/${charge.uuid}`;
console.log('Payment link:', paymentLink);
}
})
.catch(error => console.error('Error:', error));Webhook Handler Example
javascript
// Express.js webhook handler
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
// Verify webhook signature
function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return `sha256=${expectedSignature}` === signature;
}
// Webhook endpoint
app.post('/webhooks/zafira', (req, res) => {
const signature = req.headers['x-webhook-signature'];
const payload = JSON.stringify(req.body);
const secret = 'your-webhook-secret';
// Verify signature
if (!verifyWebhookSignature(payload, signature, secret)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const { event, data } = req.body;
switch (event) {
case 'charge.created':
console.log('New charge created:', data);
// Handle charge creation
break;
case 'charge.paid':
console.log('Charge paid:', data);
// Handle successful payment
break;
case 'charge.expired':
console.log('Charge expired:', data);
// Handle expired charge
break;
case 'transaction.confirmed':
console.log('Transaction confirmed:', data);
// Handle transaction confirmation
break;
default:
console.log('Unknown event:', event);
}
res.status(200).json({ received: true });
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});Python Integration Examples
Python Client
python
import requests
import json
from typing import Dict, List, Optional
class ZafiraAPI:
def __init__(self, base_url: str, token: str):
self.base_url = base_url
self.token = token
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def request(self, endpoint: str, method: str = 'GET', data: Dict = None) -> Dict:
url = f"{self.base_url}{endpoint}"
if method == 'GET':
response = requests.get(url, headers=self.headers)
elif method == 'POST':
response = requests.post(url, headers=self.headers, json=data)
return response.json()
def create_charge(self, wallet_id: int, token: str, amount: float, expires: int = 300) -> Dict:
return self.request(
f"/api/wallet/{wallet_id}/charge/create",
method='POST',
data={
'token': token,
'amount': amount,
'expires': expires,
'mode': 'dynamic'
}
)
def get_wallet_balance(self, wallet_id: int) -> Dict:
return self.request(f"/api/wallet/{wallet_id}/balance")
def get_transactions(self, wallet_id: int, page: int = 1, limit: int = 10, token: str = None) -> Dict:
params = f"?page={page}&limit={limit}"
if token:
params += f"&token={token}"
return self.request(f"/api/wallet/{wallet_id}/transaction{params}")
def create_webhook(self, wallet_id: int, url: str, webhook_type: str, events: List[str], signature: str = None) -> Dict:
data = {
'url': url,
'type': webhook_type,
'events': events
}
if signature:
data['signature'] = signature
return self.request(
f"/api/wallet/{wallet_id}/webhook/create",
method='POST',
data=data
)
# Usage example
api = ZafiraAPI('https://zafira-app.vratts.com', 'your-token')
# Create a charge
charge_response = api.create_charge(1, 'ETH', 0.1, 600)
if charge_response['status'] == 'success':
charge = charge_response['data']
payment_link = f"https://zafira-app.domain.com/wallet/pay/{charge['uuid']}"
print(f"Payment link: {payment_link}")Flask Webhook Handler
python
from flask import Flask, request, jsonify
import hashlib
import hmac
import json
app = Flask(__name__)
def verify_webhook_signature(payload: str, signature: str, secret: str) -> bool:
expected_signature = hmac.new(
secret.encode('utf-8'),
payload.encode('utf-8'),
hashlib.sha256
).hexdigest()
return f"sha256={expected_signature}" == signature
@app.route('/webhooks/zafira', methods=['POST'])
def webhook_handler():
signature = request.headers.get('X-Webhook-Signature')
payload = request.get_data(as_text=True)
secret = 'your-webhook-secret'
# Verify signature
if not verify_webhook_signature(payload, signature, secret):
return jsonify({'error': 'Invalid signature'}), 401
data = request.get_json()
event = data.get('event')
event_data = data.get('data')
if event == 'charge.created':
print(f"New charge created: {event_data}")
# Handle charge creation
elif event == 'charge.paid':
print(f"Charge paid: {event_data}")
# Handle successful payment
elif event == 'charge.expired':
print(f"Charge expired: {event_data}")
# Handle expired charge
elif event == 'transaction.confirmed':
print(f"Transaction confirmed: {event_data}")
# Handle transaction confirmation
else:
print(f"Unknown event: {event}")
return jsonify({'received': True})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)System Monitoring
Supervisor Endpoint
bash
# Check system health (for cronjobs)
wget -O /dev/null https://zafira-app.vratts.com/api/supervisorHealth Check Script
bash
#!/bin/bash
# health_check.sh
API_URL="https://zafira-app.vratts.com/api/supervisor"
LOG_FILE="/var/log/zafira-health.log"
# Check supervisor endpoint
response=$(curl -s -o /dev/null -w "%{http_code}" "$API_URL")
if [ "$response" -eq 200 ]; then
echo "$(date): System healthy" >> "$LOG_FILE"
exit 0
else
echo "$(date): System unhealthy (HTTP $response)" >> "$LOG_FILE"
exit 1
fiError Handling Best Practices
Retry Logic
javascript
async function apiCallWithRetry(apiCall, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await apiCall();
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
// Wait before retry (exponential backoff)
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
}
}
}
// Usage
apiCallWithRetry(() => api.createCharge(1, 'ETH', 0.1))
.then(response => console.log(response))
.catch(error => console.error('Failed after retries:', error));Rate Limiting Handling
javascript
async function handleRateLimit(apiCall) {
try {
return await apiCall();
} catch (error) {
if (error.status === 429) {
// Rate limited, wait and retry
const retryAfter = error.headers['retry-after'] || 60;
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
return apiCall();
}
throw error;
}
}Next Steps
- API Overview - Return to API documentation overview
- Getting Started - Installation and setup
- Features Guide - Explore application features