Send SMS From Laravel Application

yemiwebby

Oluyemi

Posted on April 13, 2018

Send SMS From Laravel Application

http://pngtree.com/do/envelope

There is always a need to send a message to users from your web application. It could be to verify details such as phone number or send a **_one time password_** popularly called OTP before a transaction can be completed. Most users don’t have the luxury of patience, waiting for messages to arrive, they want it Asap!!!.

I used this on a particular project recently, so I thought the need to share how I was able to put this together. My application was built using Laravel and an API provided by one of the best bulk SMS platforms in Nigeria (https://www.bulksmsnigeria.net/).

** Disclamer:- I am not in any way affiliated with BulkSMSNigeria and this is not a sponsored post.

Since this post is not really about how you can get started with Laravel. I will suggest that you follow this link https://laravel.com and learn more about laravel and how to quickly set it up.

Alright, there is a lot to do, so I will suggest we quickly get into it

Let’s Begin

I assume that you already have composer setup on your system. Else, quickly follow that link and get composer now.

You can download and install Laravel via:

  1. Laravel installer
  2. Composer create-project.

For the purpose of this tutorial, I will use the second option which is proven to be more straightforward.

So, run the following command in your terminal.

composer create-project — prefer-dist laravel/laravel send-sms

The command above will create a new directory (folder) called **send-sms** in your preferred development folder or whenever local folder you run the command from.

By now, you should have a new laravel project called **_send-sms_**, obviously, this is the name of our simple project, but please feel free to name it whatever you like.

change directory into your new project

cd send-sms

And start the PHP’s built-in development server to serve your application with the Artisan command below:

php artisan serve

This command will start a development server at http://localhost:8000

check it out

WHAT WE WILL BUILD

Now that we are fully set up with laravel. Don’t forget that the main aim of this tutorial is to be able to send SMS from our laravel application. So we are just going to build a very simple form that takes in the phone number of a user and send SMS to him/her.

Quickly create a controller that will handle the SMS action for us

php artisan make:controller SmsController

This will generate a new controller for you. Fill in the following : -

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

class SmsController extends Controller
{

    private $SMS_SENDER = "Sample";
    private $RESPONSE_TYPE = 'json';
    private $SMS_USERNAME = 'Your username';
    private $SMS_PASSWORD = 'Your password';

    public function getUserNumber(Request $request)
    {
        $phone_number = $request->input('phone_number');

        $message = "A message has been sent to you";

        $this->initiateSmsActivation($phone_number, $message);
// $this->initiateSmsGuzzle($phone_number, $message);

        return redirect()->back()->with('message', 'Message has been sent successfully');
    }

    public function initiateSmsActivation($phone_number, $message){
        $isError = 0;
        $errorMessage = true;

        //Preparing post parameters
        $postData = array(
            'username' => $this->SMS_USERNAME,
            'password' => $this->SMS_PASSWORD,
            'message' => $message,
            'sender' => $this->SMS_SENDER,
            'mobiles' => $phone_number,
            'response' => $this->RESPONSE_TYPE
        );

        $url = "http://portal.bulksmsnigeria.net/api/";

        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData
        ));

        //Ignore SSL certificate verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        //get response
        $output = curl_exec($ch);

        //Print error if any
        if (curl_errno($ch)) {
            $isError = true;
            $errorMessage = curl_error($ch);
        }
        curl_close($ch);

        if($isError){
            return array('error' => 1 , 'message' => $errorMessage);
        }else{
            return array('error' => 0 );
        }
    }

    public function initiateSmsGuzzle($phone_number, $message)
    {
        $client = new Client();

        $response = $client->post('http://portal.bulksmsnigeria.net/api/?', [
            'verify' => false,
            'form_params' => [
                'username' => $this->SMS_USERNAME,
                'password' => $this->SMS_PASSWORD,
                'message' => $message,
                'sender' => $this->SMS_SENDER,
                'mobiles' => $phone_number,
            ],
        ]);

        $response = json_decode($response->getBody(), true);
    }
}

What I have done here is to create a function that will accept the user’s phone number and send SMS, but before we can use this, you will need to create an account on https://www.bulksmsnigeria.net/ if don’t have one already. Once you are set, proceed and recharge your account.

Don’t forget to use your credentials here

private $SMS_USERNAME = 'Your username';
private $SMS_PASSWORD = 'Your password';

What I have also done here is to add two separate functions,

public function initiateSmsActivation($phone_number, $message){
    $isError = 0;
    $errorMessage = true;

    //Preparing post parameters
    $postData = array(
        'username' => $this->SMS_USERNAME,
        'password' => $this->SMS_PASSWORD,
        'message' => $message,
        'sender' => $this->SMS_SENDER,
        'mobiles' => $phone_number,
        'response' => $this->RESPONSE_TYPE
    );

    $url = "http://portal.bulksmsnigeria.net/api/";

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData
    ));

    //Ignore SSL certificate verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    //get response
    $output = curl_exec($ch);

    //Print error if any
    if (curl_errno($ch)) {
        $isError = true;
        $errorMessage = curl_error($ch);
    }
    curl_close($ch);

    if($isError){
        return array('error' => 1 , 'message' => $errorMessage);
    }else{
        return array('error' => 0 );
    }
}

and

public function initiateSmsGuzzle($phone_number, $message)
{
    $client = new Client();

    $response = $client->post('http://portal.bulksmsnigeria.net/api/?', [
        'verify' => false,
        'form_params' => [
            'username' => $this->SMS_USERNAME,
            'password' => $this->SMS_PASSWORD,
            'message' => $message,
            'sender' => $this->SMS_SENDER,
            'mobiles' => $phone_number,
        ],
    ]);

    $response = json_decode($response->getBody(), true);
}

You can use the first one if you prefer to use cURL, while the second one is to make API calls using guzzleClient (you will have to install guzzle client in order to be able to use it ).

Now open _send_-_sms_/_routes_/_web_._php_ and add a route as shown below : -

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::post('/send-sms', [
   'uses' => 'SmsController@getUserNumber',
   'as' => 'sendSms'
]);

Lastly, to add our view and style the page appropriately. Locate **_send-sms/resources/views_** folder and clear the default html files, then replace it with this:-

<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link href="{{ asset('css/style.css') }}" rel="stylesheet">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>SEND SMS</title>
</head>
<body>
<div id="homepage">
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">SEND SMS</a>
            </div>
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="{{ url('/') }}">Home</a></li>
                </ul>
            </div><!--/.nav-collapse -->
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="panel panel-default">

                    @if(session()->has('message'))
                        <div class="alert alert-success">
                            {{ session()->get('message') }}
                        </div>
                    @endif

                    <div class="panel-heading">
                        <h3 class="panel-title">Welcome to my site</h3>
                    </div>
                    <div class="panel-body">
                        <form id="myForm" method="POST" action="{{ route('sendSms') }}" role="form">
                            {{csrf_field()}}
                            <fieldset>
                                <div class="form-group">
                                    <input class="form-control" placeholder="Your Phone Number" name="phone_number" type="number" autofocus>
                                </div>
                                <!-- Change this to a button or input when using this as a form -->
                                <button id="submitBtn" type="submit" class="btn btn-success btn-block">Send Message</button>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div><!-- /.container -->

</div>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<script>
    $('#myForm').submit(function(){
        $('#submitBtn').html('Sending...');
    });
</script>

</html>

For styling:-

/* send-sms/public/css/style.css */
#homepage {
    margin-top: 100px;
}

Your page should look like this now:

You can try to send SMS to your own phone number or anyone.

You could also check this out on Github

CONCLUSION

I believe this tutorial has shown you a very simple way of sending SMS from your Laravel application without much hassle. Needless to say this, the same process can be followed to implement sending of SMS using any other sms API.

Moving forwards, you can create a separate class for sending SMS as you might need to use this within any of your controller.

Furthermore, you can build on this and improve the structure as you deem fit. If you have found this useful, kindly show some love, share with others and post your comments below. Happy coding!!!!


💖 💪 🙅 🚩
yemiwebby
Oluyemi

Posted on April 13, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related