How to Send Whatsapp Notifications with Laravel 8 and Twilio
Whatsapp Laravel Twilio - After in the previous article we tried the Programmable Messaging API service from Twilio to create an SMS broadcast feature or SMS portal in laravel version 8, in this tutorial article we will try the service from Twilio to create a whatsapp notification feature in laravel version 8.
In this article we will not discuss the flow of account registration on Twilio because in the previous article we discussed how to register a free trial account on Twilio. For this experimental project, we can still use the credentials from what we got on the Twilio dashboard page, it's just that to use the Programmable Messaging API service from Twilio to make the WhatsApp notification send feature, there are a few steps that must be followed.
Read: How to Create an SMS Broadcast or SMS Portal with Laravel 8 and Twilio
The scenario in this experiment is quite simple, namely when the user successfully registers, it will send a WhatsApp notification to the user's WhatsApp number. Ok, let's go straight to the project.
Table of Contents
Setup Twilio Testing Sandbox
To send whatsapp notification messages in production mode, we have to register an account by sending some of the requested data to Whatsapp. Whatsapp will verify the data that we sent and will send the results of the verification whether it is approved or rejected (it is not Twilio who does the verification). However, for development mode, we don't need to register an account and wait for verification from Whatsapp, we can use Twilio Sandbox to start developing or testing the WhatsApp notification sending feature using the Programmable Messaging API service from Twilio.
To start using Sandbox from Twilio, please enter the Send a Whatsapp message menu in the Twilio dashboard sidebar menu (Messaging>Try it Out) then click the link click here.
By pressing or clicking the link, we will be directed to Whatsapp and please send a join excitement-ancient message. By successfully sending the message, we can already use the Sandbox from Twilio to start creating the WhatsApp notification feature in Laravel.
* Save the whatsapp number from Twilio for us to setup in the .ENV file
Install Laravel 8
composer create-project laravel/laravel whatsapp-laravel-twilio
cd whatsapp-laravel-twilio
After successfully setup the Twilio Testing Sandbox in the previous step, now let's start coding starting with installing the laravel version (currently version 8). Please open a terminal, then run the command as above. The command will create or generate a laravel project folder with the name whatsapp-laravel-twilio. If the installation process is complete, please enter the project with the command cd whatsapp-laravel-twilio.
Install Twilio SDK Package
composer require twilio/sdk
To be able to use Twilio services in laravel 8, we need to install the Twilio SDK package. Run the command as above to start installing the Twilio SDK package. If the process is complete, now we can use the services of Twilio.
Install Laravel UI
composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
Because in this tutorial we have a scenario where the user will receive a WhatsApp notification after the user has successfully registered, so we need the authentication feature in our Laravel project. For that, we will use the laravel ui package to generate the authentication feature. Please run the commands as above in sequence to install laravel ui package.
Edit Migration File
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
By default, Laravel already provides a migration file for the user table, but in this experiment we need data on the WhatsApp number or telephone number to send WhatsApp messages to the user's WhatsApp number. For that we need to adjust or add the phone field in the migration file for the users table. Please open the file in databases/migrations/{timestamp}_create_users_table.php, and add the code for the phone field as above.
Create Database & Setup .ENV
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=whatsapp-laravel-twilio
DB_USERNAME=root
DB_PASSWORD=
We need to create a new database to migrate the migration files to the database. If using XAMPP, we can directly create a new database at localhost/phpmyadmin. Here as an example, we will create a new database with the name whatsapp-laravel-twilio and then adjust the DB_DATABASE in the .ENV file with the database name that was just created.
TWILIO_AUTH_SID="INSERT YOUR TWILIO SID HERE"
TWILIO_AUTH_TOKEN="INSERT YOUR TWILIO TOKEN HERE"
TWILIO_WHATSAPP_FROM="INSERT YOUR TWILIO WHATSAPP FROM"
Still in the .ENV file, don't forget to add the twilio value as above for our needs to make the whatsapp notification feature in laravel 8 with twilio. TWILIO_AUTH_SID and TWILIO_AUTH_TOKEN can be found on the Twilio dashboard page. While TWILIO_WHATSAPP_FROM can be obtained when we setup the Twilio Testing Sandbox in the first step or the whatsapp number that we have sent a join excitement-ancient message.
Migrate
php artisan migrate
Run the php artisan migrate command to migrate the migration files to the newly created database.
Edit Register Form
<div class="form-group row">
<label for="phone" class="col-md-4 col-form-label text-md-right">Whatsapp Number</label>
<div class="col-md-6">
<input id="phone" type="text" class="form-control @error('phone') is-invalid @enderror" name="phone" value="{{ old('phone') }}" placeholder="+6282xxxxxxx" required>
@error('phone')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
Next, on the register page we need to add a new input form for the user to fill in the user's whatsapp number data. Copy the code above, open the file resources/views/auth/register.blade.php, then paste the code just below the email form.
Edit User Model
protected $fillable = [
'name',
'email',
'phone',
'password',
];
Then, open the user model file located in the app/Models/User.php directory. In protected $fillable, add 'phone' like the code example above so that the user's whatsapp number input can be read and entered into the users table in the database.
Edit RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Twilio\Rest\Client;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phone' => ['required', 'string', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\Models\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
]);
$this->whatsappNotification($user->phone);
return $user;
}
private function whatsappNotification(string $recipient)
{
$sid = getenv("TWILIO_AUTH_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$wa_from= getenv("TWILIO_WHATSAPP_FROM");
$twilio = new Client($sid, $token);
$body = "Hello, welcome to codelapan.com.";
return $twilio->messages->create("whatsapp:$recipient",["from" => "whatsapp:$wa_from", "body" => $body]);
}
}
The last step, please open the file in app/Http/Controllers/Auth/RegisterController.php. In this RegisterController file we will create a whatsapp notification feature that uses the Programmable Messaging API service from Twilio. Import or add code use Twilio\Rest\Client;
before the RegisterController class, then in the validator function we will also add validation for the phone number or whatsapp number data.
Then we need to create a private function for whatsapp notification. In this function, we will create new variables such as $sid, $token and $wa_form whose values are taken from the .ENV file. Then we define the twilio client and the $body variable which is the text that will be sent to the user's whatsapp number after the user has successfully registered.
In the create function, we add phone data to add the phone number data entered by the user to the users table in the database. Then when the data is successfully added, it will call the WhatsAppNotification function to send a WhatsApp notification message to the user's phone number or whatsapp number.
So the RegisterController.php file will now be like the code above. *You can also direct all the code above and replace it in the RegisterController.php file.
Testing Whatsapp Notification Feature in Laravel 8 with Twilio
After going through the processes starting from the twilio testing sandbox setup, installing laravel 8, installing laravel ui to editing the RegisterController.php file, now is the time to test the whatsapp notification send feature that we have made in laravel 8 with the Programmable Messaging API from Twilio.
Please run the server with the command php artisan serve, then open it in a browser with the URL 127.0.0.1:8000/register or whatsapp-laravel-twilio.test/register. Fill in the available forms, and fill in the phone number or whatsapp number input form with your telephone number starting with the country code (such as +62), then click Register. If you register successfully, the whatsapp number you entered will receive a whatsapp message with the message content or the text "Hello, welcome to codelapan.com."
The picture above is an example of a WhatsApp notification that a user receives after successfully registering.
That's all for this article, if there are criticisms, suggestions or whatever you want to discuss, please write your comments in the comment form provided below. I hope this article can be useful and see you in the next article
Credit: Online illustrations by Storyset
- Cara Mengatasi Error XAMPP: MySQL shutdown unexpectedly 23 Oktober 2021 66093 views
- Laravel 8: REST API Authentication dengan Sanctum 17 September 2021 31802 views
- Tutorial CRUD (Create, Read, Update & Delete) Codeigniter 4 dengan Bootstrap 14 Oktober 2021 30197 views
- Membuat REST API CRUD di Laravel 8 dengan Sanctum 18 September 2021 28293 views
- Contoh Cara Menggunakan Sweet Alert di Laravel 8 27 Agustus 2021 27463 views