Paramclasses Academy - Blog

Tutorials Details

←
Post 16 of 19
→

How to Integrate Bulk SMS API into a Website or Application ?

How to Integrate Bulk SMS API into a Website or Application ?

November 27, 2026

1. Introduction

Modern websites and applications require automated communication systems to provide customers with timely notifications, transaction confirmations, appointment reminders, and verification messages.

Manually sending these messages through a Bulk SMS dashboard becomes inefficient when a business processes hundreds of customer activities every day.

Bulk SMS API integration allows websites, mobile applications, CRM systems, and business management software to communicate directly with an SMS service provider.

For example, when a customer places an order on an e-commerce website, the application can automatically submit an SMS notification without requiring manual intervention.

In this tutorial, we will understand SMS API fundamentals, authentication, request parameters, JSON responses, PHP integration, error handling, and important security practices using MSG91 as a demonstration service provider.

2. Learning Objectives

After completing this tutorial, you will be able to:

  • Understand SMS APIs and REST architecture.

  • Configure SMS API authentication.

  • Understand HTTP requests and JSON responses.

  • Integrate an SMS API using PHP.

  • Send personalized SMS messages.

  • Submit messages to multiple recipients.

  • Handle API errors and delivery reports.

  • Implement secure messaging workflows.

3. What Is a Bulk SMS API?

API stands for Application Programming Interface.

A Bulk SMS API is a software interface that enables applications to communicate programmatically with an SMS service provider.

Instead of manually opening an SMS dashboard, developers can write server-side code that automatically submits messaging requests.

Common Applications

  • Order confirmation notifications.

  • Payment confirmation messages.

  • Appointment reminders.

  • Student registration notifications.

  • Account verification.

  • Customer service updates.

  • Eligible promotional campaigns.

An SMS API acts as a communication bridge between business software and messaging infrastructure.

4. How Does an SMS API Work?

The simplified SMS API workflow is:

Website or Application → Backend Server → SMS API → SMS Gateway → Telecom Network → Customer Mobile Phone.

When a customer completes an activity, the backend application prepares the required message parameters.

The application sends an authenticated HTTP request to the messaging provider. The provider validates the request, processes applicable compliance information, and forwards eligible messages for delivery.

An API response indicates whether the request was accepted or rejected. Final delivery information is obtained separately through delivery reports or supported webhooks.

5. Requirements for SMS API Integration

Before implementing an SMS API, developers should prepare the following:

  • PHP 8 or later.

  • XAMPP or another PHP development environment.

  • Enabled PHP cURL extension.

  • Active SMS service provider account.

  • Valid API authentication key.

  • Configured SMS billing arrangement.

  • Applicable DLT registration.

  • Registered sender header and content template.

  • Authorized test mobile number.

Businesses sending commercial SMS in India must complete applicable telecommunications requirements before submitting live messages.

Official TRAI sender guidance:

https://www.trai.gov.in/advice-to-senders

6. Understanding SMS API Authentication

SMS providers use authentication credentials to identify authorized applications.

MSG91 uses an authentication key called authkey.

Steps to Obtain an API Key

  1. Log in to your MSG91 account.

  2. Locate the Authkey management section.

  3. Create or select an appropriate authentication key.

  4. Configure supported security restrictions.

  5. Store the authentication key securely on your server.

Never expose API credentials in HTML, JavaScript, public repositories, or client-side mobile application code.

If an authentication key is compromised, revoke or rotate it immediately.

7. Configure the SMS Template

Create an applicable registered message template before integrating the API.

Consider the following order notification:

Dear Rahul, your order ORD1025 has been confirmed. Thank you for shopping with ABC Store.

The corresponding MSG91 template might use variables named VAR1 and VAR2 for the customer name and order number.

After creating the template, configure its sender header and applicable DLT Template ID. Verify its approval status and copy the MSG91 Template ID.

The provider's Template ID is different from the DLT Content Template ID.

Official template configuration guide:

https://msg91.com/help/template/how-to-create-flow-id-to-send-sms-via-api

8. Understanding the SMS API Request

MSG91 provides a dedicated SMS endpoint that accepts HTTP POST requests.

Important request parameters include:

authkey: Authentication credential supplied through the HTTP request header.

template_id: Identifies the configured MSG91 message template.

recipients: Contains destination numbers and permitted personalization values.

mobiles: Specifies a mobile number, including its country code.

VAR1 and VAR2: Represent the variable names configured in the template.

Sample JSON Request

{
  "template_id": "YOUR_MSG91_TEMPLATE_ID",
  "short_url": "0",
  "recipients": [
    {
      "mobiles": "919XXXXXXXXX",
      "VAR1": "Rahul",
      "VAR2": "ORD1025"
    }
  ]
}

The mobile number is masked for educational purposes. Variable names must match the actual configured template.

Official MSG91 API documentation:

https://docs.msg91.com/en/sms/send-sms

9. Step-by-Step PHP SMS API Integration

Step 1: Create a Project Folder

Open your XAMPP htdocs directory and create a folder named bulk-sms-api.

Create a PHP file named send_sms.php inside the project folder.

This example runs through the terminal rather than an unprotected public webpage.

Step 2: Configure Environment Variables

Open PowerShell and navigate to your project directory.

cd C:\xampp\htdocs\bulk-sms-api

$env:MSG91_AUTHKEY="YOUR_AUTH_KEY"
$env:MSG91_TEMPLATE_ID="YOUR_TEMPLATE_ID"
$env:SMS_TEST_MOBILE="YOUR_AUTHORIZED_NUMBER"

Replace the placeholders with your actual configuration. The mobile number should include the country code without the plus sign.

Step 3: Write the Complete PHP Code

Save the following code inside send_sms.php.

<?php

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit('Command-line access only.');
}

$authKey = getenv('MSG91_AUTHKEY');
$templateId = getenv('MSG91_TEMPLATE_ID');
$mobile = getenv('SMS_TEST_MOBILE');

if (!$authKey || !$templateId || !$mobile) {
    exit("Missing SMS configuration.\n");
}

if (!preg_match('/^91[6-9][0-9]{9}$/', $mobile)) {
    exit("Invalid Indian mobile number.\n");
}

if (!function_exists('curl_init')) {
    exit("Enable the PHP cURL extension.\n");
}

$payload = [
    'template_id' => $templateId,
    'short_url' => '0',
    'recipients' => [
        [
            'mobiles' => $mobile,
            'VAR1' => 'Rahul',
            'VAR2' => 'ORD1025'
        ]
    ]
];

$ch = curl_init(
    'https://control.msg91.com/api/v5/flow/'
);

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'authkey: ' . $authKey,
        'Content-Type: application/json',
        'Accept: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode(
        $payload,
        JSON_THROW_ON_ERROR
    ),
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2
]);

$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($response === false) {
    exit("Network error. Check logs before retrying.\n");
}

$result = json_decode($response, true);

if (
    $status >= 200 &&
    $status < 300 &&
    is_array($result) &&
    ($result['type'] ?? '') === 'success'
) {
    echo "SMS request accepted.\n";
    echo "Reference: " .
        ($result['message'] ?? 'Unavailable') . "\n";
} else {
    echo "SMS request failed or status is uncertain.\n";
    echo "HTTP status: " . $status . "\n";
}

Step 4: Execute the PHP Script

Run the following command in PowerShell:

C:\xampp\php\php.exe send_sms.php

This command submits a real SMS request when valid credentials, an approved template, an authorized number, and sufficient credits are configured.

Messaging charges may apply.

10. PHP Code Explanation

The getenv() function retrieves configuration values from environment variables.

The preg_match() function performs a basic Indian mobile number format check.

The payload array contains the template identifier, recipient information, and personalization values.

The json_encode() function converts the PHP array into JSON.

The curl_init() function initializes the HTTP connection.

The curl_setopt_array() function configures authentication headers, the request body, connection timeouts, and HTTPS certificate verification.

The curl_exec() function submits the API request.

The json_decode() function converts the response into a PHP array for further processing.

Official PHP cURL documentation:

https://www.php.net/manual/en/book.curl.php

11. Understanding the API Response

An illustrative successful MSG91 response is:

{
  "message": "EXAMPLE_REQUEST_ID",
  "type": "success"
}

This response indicates successful request acceptance, not necessarily successful delivery.

Store the returned reference with the corresponding business event so that subsequent delivery reports can be associated with the original message.

12. Sending SMS to Multiple Recipients

The recipients array can contain multiple eligible customers.

{
  "template_id": "YOUR_TEMPLATE_ID",
  "recipients": [
    {
      "mobiles": "919XXXXXXXXX",
      "VAR1": "Rahul",
      "VAR2": "ORD1025"
    },
    {
      "mobiles": "918XXXXXXXXX",
      "VAR1": "Priya",
      "VAR2": "ORD1026"
    }
  ]
}

The platform processes each recipient using the corresponding variable values.

Always follow the provider's request limits and verify recipient eligibility.

13. Integrating SMS With a Website

An e-commerce website can trigger SMS notifications after successfully saving a confirmed order.

The recommended process is:

  1. Validate the customer and order.

  2. Save the order in the database.

  3. Create a notification job with a unique event identifier.

  4. Process the job through a backend worker.

  5. Submit the SMS API request.

  6. Store the provider reference and submission status.

  7. Update the delivery status when available.

Using a background queue prevents messaging delays from interrupting the customer's checkout experience.

14. Common API Errors and Solutions

Authentication Failure: Verify the API key and applicable IP restrictions.

Invalid Template: Check the configured MSG91 Template ID and variable names.

Insufficient Credits: Review the account balance and billing arrangement.

Network Timeout: Investigate the request status before resubmitting.

HTTP 429: Respect the provider's rate limits and retry guidance.

DLT Rejection: Verify the approved sender, template, content, and recipient eligibility.

15. Security and Professional Best Practices

Keep API credentials outside public source code. Restrict messaging operations to authorized backend processes.

Validate customer inputs, apply rate limits, use HTTPS, and prevent duplicate notification jobs.

Avoid blindly retrying uncertain requests because the original message may already have been accepted.

Protect customer mobile numbers and verify the authenticity of incoming delivery webhooks according to provider documentation.

16. Frequently Asked Questions

Q1. Can SMS APIs be integrated into CodeIgniter?

Yes. SMS API logic can be implemented inside a CodeIgniter service or library.

Q2. Does API success guarantee SMS delivery?

No. Request acceptance and final delivery are different stages.

Q3. Can SMS APIs send personalized messages?

Yes. Supported template variables enable recipient-specific content.

Q4. Is API integration suitable for automation?

Yes. It enables applications to trigger messages automatically when legitimate business events occur.

17. Conclusion

Bulk SMS API integration enables websites and applications to automate customer communication efficiently.

By understanding authentication, HTTP requests, JSON responses, PHP cURL, and message templates, developers can implement reliable messaging workflows.

Secure credential management, proper error handling, applicable DLT compliance, and delivery monitoring are essential for professional production-level SMS integration.

←
Post 16 of 19
→