Current Location: Home> Latest Articles> How to Integrate Baidu SMS API in PHP to Send SMS

How to Integrate Baidu SMS API in PHP to Send SMS

gitbox 2025-06-30

Introduction

SMS notifications are an essential feature in many applications. In PHP, we can use third-party service providers' APIs to send SMS. This article will demonstrate how to use Baidu's SMS API to send SMS messages.

Baidu SMS API

API Preparation

First, we need to create an application on the Baidu Open Cloud Platform and obtain the API key. Log in to the Baidu Cloud Developer Platform, create a new application, and note down the API Key and Secret Key.

Install SDK

To simplify the use of Baidu's SMS API, we can install the official SDK via Composer.

composer require baidu-aip/sms

Sending SMS

Once you have created an application and installed the SDK, we can start writing PHP code to send SMS messages.

Initialize SDK

require 'vendor/autoload.php';
use Baidu\Sms\SmsClient;
$apiKey = 'Your API Key';
$secretKey = 'Your Secret Key';
$client = new SmsClient($apiKey, $secretKey);

First, we need to include the SDK and initialize the SmsClient using the API Key and Secret Key obtained from the Baidu Cloud Platform.

Send SMS

$params = [
    'mobile' => 'Phone Number',
    'tpl_id' => 'SMS Template ID',
    'tpl_params' => [
        'VariableName1' => 'VariableValue1',
        'VariableName2' => 'VariableValue2',
    ],
];
$response = $client->sendMessage($params);
print_r($response);

Next, we use the SmsClient's sendMessage method to send the SMS. We need to provide the phone number, SMS template ID, and template parameters.

Example

The following code demonstrates how to send an SMS using Baidu SMS API.

require 'vendor/autoload.php';
use Baidu\Sms\SmsClient;
$apiKey = 'Your API Key';
$secretKey = 'Your Secret Key';
$client = new SmsClient($apiKey, $secretKey);
$params = [
    'mobile' => 'Phone Number',
    'tpl_id' => 'SMS Template ID',
    'tpl_params' => [
        'VariableName1' => 'VariableValue1',
        'VariableName2' => 'VariableValue2',
    ],
];
$response = $client->sendMessage($params);
print_r($response);

Make sure to replace "Your API Key" and "Your Secret Key" with the API Key and Secret Key you obtained from the Baidu Cloud Developer Platform. Also, update the $params array with the phone number, SMS template ID, and template parameters.

Conclusion

By using Baidu's SMS API, we can easily send SMS notifications within PHP applications. With just a few lines of code, we can easily integrate SMS functionality into our applications.