Mon - Fri (8am-8pm)

08149734028 Calls/WhatsApp Only

How to Fetch Account Unit Balance via REST API in PHP

How to Fetch Account Unit Balance via REST API in PHP

How to Fetch Account Unit Balance via REST API in PHP

When integrating third-party messaging or SMS APIs, fetching your current unit balance programmatically helps monitor account limits and trigger automated low-balance alerts.

This guide demonstrates how to authenticate with a REST API using Bearer tokens and extract the unit balance payload using PHP cURL.

Endpoint Specifications

Endpoint URL: [https://api.example.com/v2/app/balance](https://api.example.com/v2/app/balance)

HTTP Method: POST

Authentication Header: Authorization: Bearer <YOUR_API_TOKEN>

Content-Type: application/json

Sample API Response Payload

The API returns account balance details in the following JSON structure:

JSON

{

"amount": "1000.00",

"userbalance": {

"amount": "1000.00",

"status": 1

},

"status": 1

}

PHP Implementation Example

The function below sends a POST request with the required headers, handles HTTP and cURL execution errors, validates the JSON parsing step, and extracts the top-level "amount" field directly.

PHP

<?php

function fetchAccountBalance(): string

{

// Define your API endpoint and bearer token securely via environment variables

$url = defined('API_BALANCE_URL') ? API_BALANCE_URL : 'https://api.example.com/v2/app/balance';

$token = defined('API_BEARER_TOKEN') ? API_BEARER_TOKEN : 'YOUR_API_TOKEN_HERE';

$curl = curl_init($url);

curl_setopt_array($curl, [

CURLOPT_RETURNTRANSFER => true,

CURLOPT_TIMEOUT => 30,

CURLOPT_FOLLOWLOCATION => true,

CURLOPT_POST => true,

CURLOPT_HTTPHEADER => [

'Authorization: Bearer ' . $token,

'Content-Type: application/json',

'Accept: application/json',

],

CURLOPT_POSTFIELDS => json_encode(['format' => true]),

]);

$response = curl_exec($curl);

$curlError = curl_error($curl);

$httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);

curl_close($curl);

// 1. Handle transport-level errors

if ($response === false) {

return 'cURL Error: ' . $curlError;

}

// 2. Handle non-2xx HTTP responses

if ($httpStatus < 200 || $httpStatus >= 300) {

return 'HTTP Error ' . $httpStatus . ': ' . $response;

}

$data = json_decode($response, true);

// 3. Validate JSON output

if (json_last_error() !== JSON_ERROR_NONE) {

return 'JSON Error: ' . json_last_error_msg() . ' | Response: ' . $response;

}

// 4. Extract and return the target attribute

return isset($data['amount']) ? (string) $data['amount'] : 'Amount field missing in response';

}

Usage Summary

Replace API_BEARER_TOKEN with your active API credential.

Ensure your server environment has the php-curl extension enabled.

Call fetchAccountBalance() in your application to receive either the numeric string balance or a descriptive error message if the call fails.