SMS Services : AWS SNS Implementation In PHP5 In Ubuntu 14.04

Hi Everyone, today we are going to implement one of the AWS service, SNS(Simple Notification Service) for SMS services in php.

SMS services are usually used for otp(One time password) features in various platforms. It is also used for marketing. There are various services which provide bulk sms services, like twilio, plivo, nexmo, etc. Among all of them, I found out that AWS SNS is a better one, with their offerings.

Install PHP SDK for AWS

1- Install Composer
curl -sS https://getcomposer.org/installer | php

2- Create a composer.json file into your project.
sudo touch composer.json

3- Edit composer.json with below content.
{
"require": {
"aws/aws-sdk-php": "3.*"
}
}

4- Run you composer command to install aws sdk.
php composer.phar install

This will install aws-sdk into your project. Now, you must be having a vendor folder in your project, which contains the aws-sdk. It also contains an autoload.php file, which is used to load the aws-sdk in your project.

Use Of PHP-SDK

1- Include the autoload.php into your file where you want to implement sns and specify SnsClient class to be used.
include 'vendor/autoload.php'; or include FCPATH.'vendor/autoloader.php';(for codeigniter)
use Aws\Sns\SnsClient;

2- Get an object of sns library, to use its functions.
$client = new SnsClient([
'version' => 'latest',
'region' => 'us-west-2',
'credentials' => [
'key' => 'KEY',
'secret' => 'SECRET KEY',
],
]);

In above replace, key and secret’s value with their correct value.

Now you are ready to send message using the above client object.

3- Create settings for your object.
$options = array(
'MessageAttributes' => array(
'AWS.SNS.SMS.SenderID' => array(
'DataType' => 'String',
'StringValue' => 'SENDERID'
),
'AWS.SNS.SMS.SMSType' => array(
'DataType' => 'String',
'StringValue' => 'SMSType'
)
),
'Message' => $message,
'PhoneNumber' => $phone
);

In above, replace SENDERID, with your desired sender id, SMSType with desired value(Transactional/Promotional), appropriate message, phone number.

4- Send the message, by calling the publish function of the object.
$result = $client->publish($options);

Result contains the response sent by aws sns.

At this point, you must be able to send a message using aws sns.
Github URL
AWS-SDK Tutorial
AWS-SDK Installation
Composer Commands

Leave a Reply

Your email address will not be published. Required fields are marked *