Skip to main content

Overview

Retrieve SMS and OTP balances and feature limits for your project.

Endpoint

curl --request GET \
  "https://sms.lamah.com/api/project/balance" \
  --header "Authorization: Bearer YOUR_API_TOKEN"

Response

Success Response (200 OK)

{
  "SMS": { "balance": 980, "limit": 1000 },
  "OTP": { "balance": 120, "limit": 200 }
}

Response Fields

FieldTypeDescription
SMS.balancenumberRemaining SMS credits or parts available
SMS.limitnumberSMS monthly/project limit
OTP.balancenumberRemaining OTP credits
OTP.limitnumberOTP plan limit

Payment Methods Array

Each payment method object contains:
FieldTypeDescription
typestringPayment type: wallet or subscription
balancenumberAvailable balance (wallet only)
remaining_smsintegerRemaining SMS credits (subscription only)
total_smsintegerTotal SMS in plan (subscription only)
statusstringStatus: active, inactive, expired
renewal_datestringNext renewal date (subscription only)

Recent Transactions Array

Each transaction object contains:
FieldTypeDescription
transaction_idstringUnique transaction identifier
typestringTransaction type
amountnumberTransaction amount (negative for charges)
descriptionstringHuman-readable description
timestampstringWhen the transaction occurred
message_idstringRelated message ID (for SMS charges)
payment_methodstringPayment method used (for top-ups)

Transaction Types

TypeDescription
sms_chargeCharge for sending SMS
otp_chargeCharge for OTP service
top_upManual balance top-up
auto_rechargeAutomatic balance recharge
refundRefund for failed messages
adjustmentManual balance adjustment

Error Responses

401 Unauthorized

{ "message": "Unauthenticated." }

403 Forbidden

{ "message": "Forbidden" }

Use Cases

Balance Monitoring

Monitor account balance to ensure uninterrupted service

Cost Tracking

Track SMS costs and usage patterns

Billing Integration

Integrate balance information into billing systems

Auto-Recharge Setup

Configure automatic balance top-ups

Implementation Examples

Balance Monitoring

class BalanceMonitor {
  constructor(apiToken, lowBalanceThreshold = 10) {
    this.apiToken = apiToken;
    this.lowBalanceThreshold = lowBalanceThreshold;
    this.baseUrl = 'https://sms.lamah.com/api';
  }

  async checkBalance() {
    try {
      const response = await fetch(`${this.baseUrl}/project/balance`, {
        headers: {
          'Authorization': `Bearer ${this.apiToken}`,
          'Accept': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch balance');
      }

      const balanceData = await response.json();
      this.analyzeBalance(balanceData);
      return balanceData;

    } catch (error) {
      console.error('Error checking balance:', error);
      return null;
    }
  }

  analyzeBalance(balanceData) {
    const { current_balance, auto_recharge } = balanceData;

    // Check for low balance
    if (current_balance < this.lowBalanceThreshold) {
      if (auto_recharge.enabled) {
        console.log(`💡 Low balance ($${current_balance}), but auto-recharge is enabled`);
      } else {
        console.warn(`🚨 Low balance alert: $${current_balance}`);
        this.sendLowBalanceAlert(current_balance);
      }
    }

    // Check subscription usage
    const subscription = balanceData.payment_methods.find(pm => pm.type === 'subscription');
    if (subscription) {
      const usagePercent = ((subscription.total_sms - subscription.remaining_sms) / subscription.total_sms) * 100;
      
      if (usagePercent > 90) {
        console.warn(`🚨 Subscription usage: ${usagePercent.toFixed(1)}% used`);
      }
    }

    return {
      isLowBalance: current_balance < this.lowBalanceThreshold,
      hasAutoRecharge: auto_recharge.enabled,
      subscriptionUsage: subscription ? ((subscription.total_sms - subscription.remaining_sms) / subscription.total_sms) * 100 : 0
    };
  }

  sendLowBalanceAlert(balance) {
    // Implement your alert mechanism (email, in-app notification, etc.)
    console.log(`Sending low balance alert: $${balance}`);
  }

  async getRecentTransactions(limit = 10) {
    const balanceData = await this.checkBalance();
    if (!balanceData) return [];

    return balanceData.recent_transactions.slice(0, limit);
  }

  async calculateDailyCost() {
    const balanceData = await this.checkBalance();
    if (!balanceData) return 0;

    return balanceData.usage_summary.today.total_cost;
  }
}

// Usage
const monitor = new BalanceMonitor('YOUR_API_TOKEN', 25);

// Check balance every hour
setInterval(async () => {
  await monitor.checkBalance();
}, 60 * 60 * 1000);

// Get daily cost
const dailyCost = await monitor.calculateDailyCost();
console.log(`Today's SMS cost: $${dailyCost}`);

Cost Tracking Dashboard

const createCostDashboard = async (apiToken) => {
  try {
    const response = await fetch('https://sms.lamah.com/api/project/balance', {
      headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Accept': 'application/json'
      }
    });

    const balanceData = await response.json();
    
    // Update dashboard elements
    document.getElementById('current-balance').textContent = `$${balanceData.current_balance}`;
    document.getElementById('today-cost').textContent = `$${balanceData.usage_summary.today.total_cost}`;
    document.getElementById('month-cost').textContent = `$${balanceData.usage_summary.this_month.total_cost}`;
    
    // Update subscription info if available
    const subscription = balanceData.payment_methods.find(pm => pm.type === 'subscription');
    if (subscription) {
      const usagePercent = ((subscription.total_sms - subscription.remaining_sms) / subscription.total_sms) * 100;
      document.getElementById('subscription-usage').textContent = `${usagePercent.toFixed(1)}%`;
      document.getElementById('remaining-sms').textContent = subscription.remaining_sms;
    }
    
    // Render recent transactions
    renderTransactions(balanceData.recent_transactions);
    
  } catch (error) {
    console.error('Failed to load cost dashboard:', error);
  }
};

const renderTransactions = (transactions) => {
  const container = document.getElementById('transactions-list');
  container.innerHTML = '';
  
  transactions.slice(0, 5).forEach(txn => {
    const div = document.createElement('div');
    div.className = 'transaction-item';
    
    const amount = txn.amount > 0 ? `+$${txn.amount}` : `-$${Math.abs(txn.amount)}`;
    const amountClass = txn.amount > 0 ? 'positive' : 'negative';
    
    div.innerHTML = `
      <div class="transaction-description">${txn.description}</div>
      <div class="transaction-amount ${amountClass}">${amount}</div>
      <div class="transaction-date">${new Date(txn.timestamp).toLocaleDateString()}</div>
    `;
    
    container.appendChild(div);
  });
};

// Load dashboard on page load
document.addEventListener('DOMContentLoaded', () => {
  createCostDashboard('YOUR_API_TOKEN');
});

Best Practices

Regular Monitoring

Check balance regularly to avoid service interruption

Set Up Alerts

Configure low balance alerts and auto-recharge

Track Spending

Monitor spending patterns to optimize costs

Backup Payment

Have backup payment methods configured

Balance Alerts

const setupBalanceAlerts = (apiToken, alertThreshold = 20) => {
  const checkAndAlert = async () => {
    try {
      const response = await fetch('https://sms.lamah.com/api/project/balance', {
        headers: {
          'Authorization': `Bearer ${apiToken}`,
          'Accept': 'application/json'
        }
      });

      const balanceData = await response.json();
      
      if (balanceData.current_balance < alertThreshold) {
        // Send alert (implement your preferred method)
        console.warn(`🚨 Low balance: $${balanceData.current_balance}`);
        // Example: trigger email or in-app alert here
      }
      
    } catch (error) {
      console.error('Balance check failed:', error);
    }
  };

  // Check every 30 minutes
  setInterval(checkAndAlert, 30 * 60 * 1000);
  
  // Initial check
  checkAndAlert();
};