How to Check Your Twilio Account Balance using PHP

January 13, 2021
Written by
Twilion
Reviewed by
Twilion

How to Check Your Twilio Account Balance using PHP

Developers often forget that when building a communication-based app it’s important for you to monitor costs in real time. Imagine you’ve built a bulk SMS application and need to send one message to 1,000 subscribers. You already know that (in the US) this SMS will cost you $7.50 USD ($.0075/msg), but are you aware of the available balance on your account to send it? The answer is in the console, but it’s tedious logging into your Twilio account every time you need to use the API within your app.

If you’re building a PHP application that needs to calculate API costs before use, this tutorial is for you! Maybe your application needs to check your balance before sending SMS or alert you when you’ve used too many voice minutes. Whatever the use case, this quick tutorial will help you integrate your balance into your PHP app.

Get Started

This tutorial aims to keep the steps as minimal as possible. Therefore, you won’t need many requirements or frameworks to install to get started. Just make sure that you have the following set up or installed:

  • A Twilio account (If you don’t have one, here’s $10 to get started). If you have already set up your account, login to grab your Account SID and Auth Token and copy to a secure location on your computer.
  • Composer (the PHP dependency manager), globally installed.

At this point the assumption is being made that you already have PHP installed locally.

Set Up the Project Folder

Organization is key to any successful project. Although this project only includes one file to actually check the balance, a folder will be needed to contain the supporting libraries. After completion of this tutorial, your folder will contain:

  • Balance.php - the file containing the script to request your balance.
  • composer.json - the Composer file.
  • Guzzle HTTP Client

In the command line, create a new directory called twilio-balance and change into the directory using the following commands:

$ mkdir twilio-balance
$ cd twilio-balance

Create the balance.php file to house your code:

$ touch balance.php

Composer will be required to manage the dependencies of this project. Install it by initializing a new composer.json file in the twilio-balance directory. Input n for "No" when questioned if you would "like to define your dependencies (require) interactively?"

$ composer init

Install Guzzle HTTP Client

The balance from your Twilio account would normally be retrieved using cURL, a library that allows you to communicate with different types of servers using various protocols. Manually running your cURL requests is always an option, but is usually labor intensive and harder to debug. Instead, we'll use a package called Guzzle that "uses the PHP stream wrapper to send HTTP requests if cURL is not installed."

$ composer require guzzlehttp/guzzle

Guzzle is now available within the project to make HTTP requests to the Twilio API.

Construct the Endpoint

While there is no official support within the SDKs, the Twilio API does provide a way to check your balance in real time using the Balances.json endpoint.

https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXX/Balance.json

This endpoint requires Basic Authentication using your Twilio Account SID and Auth Token as seen in the Twilio Console. It will also need to be customized to include the Account SID as a part of the URL.

Open balance.php in your preferred code editor ensure you have the following requirements:

  1. Require Composer's autoloader at the top of the file.
  2. Declare the GuzzleHttp\Client namespace for use later.
  3. Define a new variable called $account_sid which will store your Account SID and another named $auth_token which will hold your Auth Token.
  4. Replace the Account SID placeholder ACXXXXXXXXXXXXXXX in the endpoint string with $account_sid.

Here’s the code that outlines the preceding directions:

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$account_sid = "ACXXXXXXXXXXXXXXX";
$auth_token = "";
$endpoint = "https://api.twilio.com/2010-04-01/Accounts/$account_sid/Balance.json";

NOTE: Your Account SID and Auth Token should never be used in a production environment.

Request the Twilio Account Balance

Now that we're ready to connect to the endpoint you should do the following:

  1. Fill in the value for $auth_token.
  2. Define a new GuzzleHttp Client.
  3. Perform a basic authentication request to the $endpoint using the $account_sid and $auth_token as the credentials.
// Define the Guzzle Client
$client = new Client();
$response = $client->get($endpoint, [
   'auth' => [
       $account_sid,
       $auth_token
   ]
]);

Would you believe that we're almost done? It's true!

The last step is to read the $response and view your account balance. The Balance.json endpoint will return both the balance and currency for your use.

echo $response->getBody();

Open your command line again (or use a browser) and run the balance.php script to retrieve your balance.

$ php balance.php

The $response body will return JSON containing the currency, balance, and account_sid.

{"currency": "USD", "balance": "1.83164", "account_sid": "ACXXXXXXXXXXXXXX"}

Final Thoughts

From this tutorial you've learned how to:

  • Initialize Composer within a PHP project.
  • Use Basic Authentication with Guzzle to securely request data from an endpoint.
  • Retrieve your Twilio account balance.

You'll notice that the response was returned in JSON format. To use the data you will need to save the data to a variable using the json_decode() function. This will provide the current available balance in an object to run other calculations against or display in a dashboard.

Hope you have enough credit and I can’t wait to see what you build!

Marcus Battle is a Senior Manager of Developer Voices at Twilio where he prompts and rallies developers to build the future of communications by writing high quality tutorials. He can be reached via: