SimPayDocs

    Quick Start Guide

    Get up and running with the API in 5 minutes

    This guide will help you make your first API call in just a few minutes.

    Prerequisites

    Before you begin, ensure you have:

    • ✅ A registered account
    • ✅ API credentials (Access Token and Secret Key)
    • ✅ Basic understanding of REST APIs
    • ✅ A tool to make HTTP requests (curl, Postman, or your preferred programming language)

    Step 1: Get Your Credentials

    1. Log in to your dashboard
    2. Navigate to Settings → API Keys
    3. Generate a new API key if you haven't already
    4. Save your:
      • Access Token (for Authorization header)
      • Secret Key (for HMAC signature)

    ⚠️ Important: Keep your credentials secure! Never commit them to version control.

    Step 2: Calculate HMAC Signature

    The HMAC signature ensures request authenticity. Here's how to generate it:

    Python Example

    import hmac
    import hashlib
    import json
    
    def generate_hmac(secret_key, method, url, body=None):
        # Prepare the message
        message = f"{method.upper()}{url}"
        if body:
            message += json.dumps(body, separators=(',', ':'))
        
        # Generate HMAC
        signature = hmac.new(
            secret_key.encode('utf-8'),
            message.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        
        return signature
    
    # Example usage
    secret_key = "your_secret_key_here"
    method = "GET"
    url = "/v3/account/5001/balance"
    
    hmac_signature = generate_hmac(secret_key, method, url)
    print(f"HMAC Signature: {hmac_signature}")

    JavaScript Example

    const crypto = require('crypto');
    
    function generateHMAC(secretKey, method, url, body = null) {
      // Prepare the message
      let message = `${method.toUpperCase()}${url}`;
      if (body) {
        message += JSON.stringify(body);
      }
      
      // Generate HMAC
      const signature = crypto
        .createHmac('sha256', secretKey)
        .update(message)
        .digest('hex');
      
      return signature;
    }
    
    // Example usage
    const secretKey = 'your_secret_key_here';
    const method = 'GET';
    const url = '/v3/account/5001/balance';
    
    const hmacSignature = generateHMAC(secretKey, method, url);
    console.log(`HMAC Signature: ${hmacSignature}`);

    Step 3: Make Your First Request

    Let's query an account balance!

    Using curl

    curl -X GET \
      'https://api.somossimpay.com.br/v3/account/5001/balance' \
      -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
      -H 'hmac: YOUR_HMAC_SIGNATURE' \
      -H 'Content-Type: application/json'

    Using Python (requests)

    import requests
    import hmac
    import hashlib
    
    # Configuration
    API_BASE = "https://api.somossimpay.com.br"
    ACCESS_TOKEN = "your_access_token_here"
    SECRET_KEY = "your_secret_key_here"
    ACCOUNT_ID = 5001
    
    # Generate HMAC
    method = "GET"
    url = f"/v3/account/{ACCOUNT_ID}/balance"
    message = f"{method}{url}"
    hmac_signature = hmac.new(
        SECRET_KEY.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()
    
    # Make request
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "hmac": hmac_signature,
        "Content-Type": "application/json"
    }
    
    response = requests.get(f"{API_BASE}{url}", headers=headers)
    data = response.json()
    
    print("Account Balance:")
    print(f"Total: R$ {data['amount_total']:.2f}")
    print(f"Blocked: R$ {data['amount_blocked']:.2f}")
    print(f"Available: R$ {data['amount_available']:.2f}")

    Using JavaScript (fetch)

    const crypto = require('crypto');
    
    const API_BASE = 'https://api.somossimpay.com.br';
    const ACCESS_TOKEN = 'your_access_token_here';
    const SECRET_KEY = 'your_secret_key_here';
    const ACCOUNT_ID = 5001;
    
    // Generate HMAC
    const method = 'GET';
    const url = `/v3/account/${ACCOUNT_ID}/balance`;
    const message = `${method}${url}`;
    const hmacSignature = crypto
      .createHmac('sha256', SECRET_KEY)
      .update(message)
      .digest('hex');
    
    // Make request
    fetch(`${API_BASE}${url}`, {
      method: method,
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'hmac': hmacSignature,
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      console.log('Account Balance:');
      console.log(`Total: R$ ${data.amount_total.toFixed(2)}`);
      console.log(`Blocked: R$ ${data.amount_blocked.toFixed(2)}`);
      console.log(`Available: R$ ${data.amount_available.toFixed(2)}`);
    })
    .catch(error => console.error('Error:', error));

    Step 4: Understand the Response

    A successful response looks like:

    {
      "worked": true,
      "amount_total": 15000.50,
      "amount_blocked": 499.25,
      "amount_available": 14501.25
    }

    Response Fields:

    • worked: Boolean indicating success
    • amount_total: Total balance (including blocked)
    • amount_blocked: Amount reserved for pending transactions
    • amount_available: Amount available for operations

    Step 5: Handle Errors

    If something goes wrong, you'll receive an error response:

    {
      "worked": false,
      "error": "Account not found"
    }

    Common Errors:

    HTTP CodeErrorSolution
    401UnauthorizedCheck your access token
    403ForbiddenVerify HMAC signature
    404Not FoundCheck account ID
    422Validation ErrorReview request parameters

    Next Steps

    Congratulations! You've made your first API call. Here's what to explore next:

    1. Create a PIX Transfer

    # Send R$ 100.00 to a PIX key
    curl -X POST \
      'https://api.somossimpay.com.br/v3/cashout/create-cashout' \
      -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
      -H 'hmac: YOUR_HMAC_SIGNATURE' \
      -H 'Content-Type: application/json' \
      -d '{
        "source_account_branch_identifier": "0001",
        "source_account_number": "123456",
        "amount": 100.00,
        "key": "recipient@example.com"
      }'

    2. List PIX Keys

    # List all PIX keys for an account
    curl -X GET \
      'https://api.somossimpay.com.br/v3/account/list-my-pix-keys?account_branch_identifier=0001&account_number=123456' \
      -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
      -H 'hmac: YOUR_HMAC_SIGNATURE'

    3. Generate a QR Code

    # Create a PIX QR code for receiving R$ 50.00
    curl -X POST \
      'https://api.somossimpay.com.br/v3/pix/create-pix-copy-and-paste-web' \
      -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
      -H 'hmac: YOUR_HMAC_SIGNATURE' \
      -H 'Content-Type: application/json' \
      -d '{
        "amount": 50.00,
        "source_account_branch_identifier": "0001",
        "source_account_number": "123456",
        "base_64_image": true
      }'

    Best Practices

    1. Use Environment Variables

    Never hardcode credentials:

    import os
    
    ACCESS_TOKEN = os.getenv('API_ACCESS_TOKEN')
    SECRET_KEY = os.getenv('API_SECRET_KEY')

    2. Implement Retry Logic

    import time
    
    def make_request_with_retry(url, max_retries=3):
        for attempt in range(max_retries):
            try:
                response = requests.get(url, headers=headers)
                if response.status_code == 200:
                    return response.json()
                elif response.status_code >= 500:
                    # Retry on server errors
                    time.sleep(2 ** attempt)  # Exponential backoff
                    continue
                else:
                    # Don't retry on client errors
                    return response.json()
            except requests.RequestException:
                if attempt == max_retries - 1:
                    raise
                time.sleep(2 ** attempt)

    3. Log Requests (Without Sensitive Data)

    import logging
    
    logging.info(f"API Request: {method} {url}")
    logging.info(f"Status Code: {response.status_code}")
    # Never log: access tokens, HMAC signatures, or sensitive data

    4. Use Webhooks for Real-Time Updates

    Instead of polling for transaction status, set up webhooks:

    # Configure a webhook to receive notifications
    webhook_data = {
        "url": "https://your-app.com/webhook",
        "events": ["pix.received", "transaction.completed"]
    }
    
    response = requests.post(
        f"{API_BASE}/v3/account/webhook",
        headers=headers,
        json=webhook_data
    )

    Sandbox Environment

    Test your integration without real money:

    # Change base URL for testing
    API_BASE = "https://sandbox-api.example.com"

    Sandbox Features:

    • Same API structure as production
    • Fake money for testing
    • No rate limits
    • Reset data anytime

    Common Use Cases

    Check Balance Before Transfer

    # 1. Check balance
    balance = get_account_balance(account_id)
    
    # 2. Verify sufficient funds
    if balance['amount_available'] >= transfer_amount:
        # 3. Create transfer
        create_cashout(amount=transfer_amount, key=recipient_key)
    else:
        print("Insufficient funds")

    Monitor Transaction Status

    # Create transaction
    transaction = create_cashout(amount=100, key="user@example.com")
    transaction_id = transaction['id']
    
    # Poll for status
    while True:
        status = get_transaction_status(transaction_id)
        if status in ['COMPLETED', 'FAILED', 'CANCELLED']:
            break
        time.sleep(5)  # Wait 5 seconds before checking again

    Troubleshooting

    HMAC Signature Mismatch

    Problem: Getting 403 Forbidden with "Invalid HMAC signature"

    Solutions:

    1. Verify the message format: {METHOD}{URL}{BODY}
    2. Ensure URL includes path only (no domain)
    3. JSON body must be compact (no spaces)
    4. Check secret key is correct
    5. Ensure UTF-8 encoding

    Token Expired

    Problem: Getting 401 Unauthorized

    Solution: Generate a new access token from the dashboard

    Rate Limit Exceeded

    Problem: Getting 429 Too Many Requests

    Solution: Implement exponential backoff and respect rate limits

    Get Help

    Need assistance?

    Next Topics


    Congratulations! You're now ready to build with the API 🎉