> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oneclickdz.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Account Balance

> Retrieve your current account balance

## Overview

Get your current account balance in Algerian Dinar (DZD). The balance represents available funds that can be used for top-ups, orders, and other services.

<Info>
  When your balance reaches a low threshold, a notification will be sent to your
  registered email address.
</Info>

## Response

<ResponseField name="success" type="boolean" required>
  `true` for successful requests
</ResponseField>

<ResponseField name="data" type="object" required>
  <Expandable title="properties">
    <ResponseField name="balance" type="number">
      Current account balance in DZD
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="meta" type="object">
  <Expandable title="properties">
    <ResponseField name="timestamp" type="string">
      Response timestamp (ISO 8601 format)
    </ResponseField>
  </Expandable>
</ResponseField>

## Example Request

<CodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url https://api.oneclickdz.com/v3/account/balance \
    --header 'X-Access-Token: YOUR_API_KEY'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch("https://api.oneclickdz.com/v3/account/balance", {
    headers: {
      "X-Access-Token": process.env.ONECLICKDZ_API_KEY,
    },
  });

  const data = await response.json();

  if (data.success) {
    console.log(`Balance: ${data.data.balance} DZD`);
  }
  ```

  ```python Python theme={null}
  import requests
  import os

  response = requests.get(
      'https://api.oneclickdz.com/v3/account/balance',
      headers={'X-Access-Token': os.getenv('ONECLICKDZ_API_KEY')}
  )

  data = response.json()

  if data['success']:
      print(f"Balance: {data['data']['balance']} DZD")
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'https://api.oneclickdz.com/v3/account/balance');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'X-Access-Token: ' . getenv('ONECLICKDZ_API_KEY')
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);

  if ($data['success']) {
      echo "Balance: " . $data['data']['balance'] . " DZD\n";
  }
  ?>
  ```
</CodeGroup>

## Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "balance": 1326.13
  },
  "meta": {
    "timestamp": "2025-10-29T00:35:58.710Z"
  }
}
```

## Use Cases

<CardGroup cols={2}>
  <Card title="Pre-Transaction Check" icon="check-circle">
    Verify sufficient funds before processing orders
  </Card>

  {" "}

  <Card title="Balance Display" icon="wallet">
    Show current balance in your application UI
  </Card>

  {" "}

  <Card title="Low Balance Alerts" icon="bell">
    Monitor balance and alert when running low
  </Card>

  <Card title="Financial Reports" icon="chart-line">
    Track balance changes over time
  </Card>
</CardGroup>

## Integration Examples

### Pre-Transaction Validation

```javascript theme={null}
async function canProcessTransaction(amount) {
  const response = await fetch(
    "https://api.oneclickdz.com/v3/account/balance",
    {
      headers: { "X-Access-Token": API_KEY },
    }
  );

  const data = await response.json();

  if (!data.success) {
    throw new Error("Failed to check balance");
  }

  const balance = data.data.balance;

  if (balance < amount) {
    throw new Error(
      `Insufficient balance. Required: ${amount} DZD, Available: ${balance} DZD`
    );
  }

  return true;
}

// Usage
try {
  await canProcessTransaction(500);
  // Proceed with transaction
} catch (error) {
  console.error(error.message);
  // Show error to user
}
```

### Balance Monitoring

```javascript theme={null}
class BalanceMonitor {
  constructor(apiKey, lowBalanceThreshold = 1000) {
    this.apiKey = apiKey;
    this.lowBalanceThreshold = lowBalanceThreshold;
    this.lastBalance = null;
  }

  async checkBalance() {
    const response = await fetch(
      "https://api.oneclickdz.com/v3/account/balance",
      {
        headers: { "X-Access-Token": this.apiKey },
      }
    );

    const data = await response.json();

    if (!data.success) {
      console.error("Failed to check balance:", data.error);
      return;
    }

    const currentBalance = data.data.balance;

    // Check for low balance
    if (currentBalance < this.lowBalanceThreshold) {
      this.onLowBalance(currentBalance);
    }

    // Check for significant changes
    if (this.lastBalance !== null) {
      const change = currentBalance - this.lastBalance;

      if (Math.abs(change) > 100) {
        this.onBalanceChange(change, currentBalance);
      }
    }

    this.lastBalance = currentBalance;
    return currentBalance;
  }

  onLowBalance(balance) {
    console.warn(`⚠️ Low balance alert: ${balance} DZD`);
    // Send notification to admin
    this.sendNotification({
      type: "low_balance",
      balance: balance,
      threshold: this.lowBalanceThreshold,
    });
  }

  onBalanceChange(change, newBalance) {
    const changeType = change > 0 ? "increased" : "decreased";
    console.log(
      `Balance ${changeType} by ${Math.abs(
        change
      )} DZD. New balance: ${newBalance} DZD`
    );
  }

  sendNotification(data) {
    // Implement your notification logic
    console.log("Notification:", data);
  }

  startMonitoring(intervalMinutes = 5) {
    // Initial check
    this.checkBalance();

    // Periodic checks
    setInterval(() => {
      this.checkBalance();
    }, intervalMinutes * 60 * 1000);
  }
}

// Usage
const monitor = new BalanceMonitor(API_KEY, 1000);
monitor.startMonitoring(5); // Check every 5 minutes
```

### Balance Caching

```javascript theme={null}
class BalanceCache {
  constructor(apiKey, cacheSeconds = 30) {
    this.apiKey = apiKey;
    this.cacheSeconds = cacheSeconds;
    this.cache = {
      balance: null,
      timestamp: 0,
    };
  }

  async getBalance(forceRefresh = false) {
    const now = Date.now();
    const cacheAge = (now - this.cache.timestamp) / 1000;

    // Return cached value if valid
    if (
      !forceRefresh &&
      this.cache.balance !== null &&
      cacheAge < this.cacheSeconds
    ) {
      return this.cache.balance;
    }

    // Fetch fresh balance
    const response = await fetch(
      "https://api.oneclickdz.com/v3/account/balance",
      {
        headers: { "X-Access-Token": this.apiKey },
      }
    );

    const data = await response.json();

    if (!data.success) {
      throw new Error(`Failed to fetch balance: ${data.error.message}`);
    }

    // Update cache
    this.cache = {
      balance: data.data.balance,
      timestamp: now,
    };

    return this.cache.balance;
  }

  invalidateCache() {
    this.cache.timestamp = 0;
  }
}

// Usage
const balanceCache = new BalanceCache(API_KEY, 30);

// First call - fetches from API
const balance1 = await balanceCache.getBalance();

// Second call within 30 seconds - returns cached value
const balance2 = await balanceCache.getBalance();

// Force refresh
const balance3 = await balanceCache.getBalance(true);
```

## Best Practices

<AccordionGroup>
  <Accordion title="Check Before Transactions" icon="shield-check">
    Always verify sufficient balance before initiating transactions

    ```javascript theme={null}
    // ✅ Good
    const balance = await getBalance();
    if (balance >= requiredAmount) {
      await sendTopUp(...);
    }

    // ❌ Bad
    await sendTopUp(...); // Might fail with NO_BALANCE error
    ```
  </Accordion>

  {" "}

  <Accordion title="Cache Wisely" icon="database">
    Cache balance for 30-60 seconds to reduce API calls `javascript // Cache
          balance but invalidate after transactions const balance = await
          balanceCache.getBalance(); await sendTopUp(...);
          balanceCache.invalidateCache(); // Refresh after transaction `
  </Accordion>

  <Accordion title="Handle Errors Gracefully" icon="triangle-exclamation">
    Implement proper error handling

    ```javascript theme={null}
    async function getSafeBalance() {
      try {
        const response = await fetch('https://api.oneclickdz.com/v3/account/balance', {
          headers: { 'X-Access-Token': API_KEY }
        });
        
        const data = await response.json();
        
        if (!data.success) {
          console.error('Balance check failed:', data.error);
          return null;
        }
        
        return data.data.balance;
      } catch (error) {
        console.error('Network error:', error);
        return null;
      }
    }
    ```
  </Accordion>

  <Accordion title="Monitor Low Balance" icon="bell">
    Set up alerts for low balance

    ```javascript theme={null}
    const LOW_BALANCE_THRESHOLD = 1000;

    async function checkAndAlert() {
      const balance = await getBalance();
      
      if (balance < LOW_BALANCE_THRESHOLD) {
        await sendAlert({
          type: 'low_balance',
          balance: balance,
          message: `Balance is low: ${balance} DZD`
        });
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Error Responses

<AccordionGroup>
  <Accordion title="401 - Unauthorized">
    ```json theme={null}
    {
      "success": false,
      "error": {
        "code": "INVALID_ACCESS_TOKEN",
        "message": "The provided access token is invalid"
      },
      "requestId": "req_abc123"
    }
    ```
  </Accordion>

  <Accordion title="500 - Internal Server Error">
    ```json theme={null}
    {
      "success": false,
      "error": {
        "code": "INTERNAL_SERVER_ERROR",
        "message": "Developer was notified and will check shortly"
      },
      "requestId": "req_abc123"
    }
    ```
  </Accordion>
</AccordionGroup>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="List Transactions" icon="list" href="/en/api-reference/account/list-transactions">
    View transaction history
  </Card>

  <Card title="Send Mobile Top-Up" icon="mobile" href="/en/api-reference/mobile/send-topup">
    Send a mobile top-up
  </Card>
</CardGroup>
