AWS SNS with Codeigniter: How to Send SMS Using AWS SNS Services in Codeigniter

AWS SNS with Codeigniter: How to Send SMS Using AWS SNS Services in Codeigniter

Amazon Simple Notification Service (SNS) is an exceedingly accessible, strong secure which enables you to build a serverless application. Serverless application enables you to build and run applications and administrations without considering servers. AWS SNS provides sevices at a very cheap price. You can check here AWS SNS pricing.

This tutorial illustrates how to send SMS using AWS services. Let see step by step how to implement this configuration.

Get Client key and Client Secret key from AWS:

Login to your aws console. here you can find the Menu “My Billing Dashboard” under profile area.Inside of Access keys (access key ID and secret access key) you need to create new access key and save it to use in future.

Installation and Configuration AWS SDK in codeigniter:

To get started, download a specific version of the zip file from https://github.com/aws/aws-sdk-php/releases, unzip it inside application/third_party directory of your codeigniter project.

Creating Base Model for Sending Email:

It is best practice to make a base model to put all send sms functionalities so that in every child model you can extend base model to avoid repetition of code.Create a file called My_Model inside application/core directory and put code below giving.Here is how code looks.

My_Model.php

<?php
require_once APPPATH.'third_party/awsSns/aws-autoloader.php';
class MY_Model extends CI_Model
{
public function SendAwsSms(){
$params = array(
'credentials'=> array(
'key'=>'YOUR API KEY',
'secret'=>'YOUR CLIENT SECRET KEY',
),
'region'=>'us-east-1',
'version'=>'latest'
);
$sns = new \Aws\Sns\SnsClient($params);
$args = array(
"SenderID"=>"SenderName",
"SMSType"=>"Transactional",
"Message"=>"Hello ! This is a test message",
"PhoneNumber"=>"Mobile No",
);
$result = $sns->publish($args);
}
}

Creating Model to Extend Base Model:

Now extend base model that already created.

<?php
  class AwsSnsModel extends My_Model {
     public function __construct() {
  }
}
?>

Creating Controller:

After done with the model, next we need to create controller and here we will load model.From controller we need to call the function that already implemented in base model. Also you can pass parameter like phone number and message to the function.

Create a file named AwsSendSmsController.phpinside application/controller directory. Please find below the code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AwsSendSmsController extends CI_Controller {
publicfunction __construct(){
parent::__construct();
$this->load->model('AwsSnsModel');
}
    public function index(){
        $this->AwsSnsModel->SendAwsSms();
    }
}

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!