Jun 15, 2024 | Laravel 11 Laravel
Hello Dev,
This article will guide you through some essential examples of integrating WhatsApp API with Laravel. You'll learn how to integrate WhatsApp API into your Laravel application, allowing you to send messages via WhatsApp. We'll explore a simple example demonstrating how to send WhatsApp messages to WhatsApp numbers using Laravel. Let's delve into the details.
Twilio stands out as a cloud communications platform offering a versatile API that enables developers to integrate voice, messaging, and video functionalities into their applications seamlessly. Renowned for its simplicity and scalability, Twilio supports various programming languages, making it an ideal choice for businesses seeking to enhance customer engagement and communication. Its API facilitates features like sending SMS, making voice calls, and implementing two-factor authentication, offering a robust solution for building innovative and interactive applications across diverse industries.
In this example, we'll utilize the "twilio/sdk" third-party package to send WhatsApp messages to users. Twilio provides a WhatsApp API that allows you to programmatically send messages and media to WhatsApp users. We'll create a simple form comprising a phone number input field and a message box. Then, we'll send a WhatsApp message to the provided number. Let's follow the steps outlined below:
Step for Laravel WhatsApp API Integration:
Step 1. Install Laravel 10
Step 2. Set up a Twilio Account
Step 3. Install the twilio/sdk Package
Step 4. Create Routes
Step 5. Create Controller
Step 6. Create Blade File
Step 7. Run the Laravel App
Let's proceed with the following steps:
To integrate WhatsApp API with Laravel for sending messages, you can follow these steps. This guide uses the Twilio SDK, which simplifies the process of sending WhatsApp messages from a Laravel application.
Step 1: Install Laravel 10If you haven't already, create a new Laravel project:
composer create-project laravel/laravel example-appStep 2: Set Up a Twilio Account
Sign up for a Twilio account at Twilio and obtain your Account SID and Auth Token. You'll also need a Twilio WhatsApp number, which you can get from your Twilio Console.
.envTWILIO_SID=your_twilio_account_sid TWILIO_AUTH_TOKEN=your_twilio_auth_token TWILIO_WHATSAPP_NUMBER=your_twilio_whatsapp_numberStep 3: Install the twilio/sdk Package
Install the Twilio SDK via Composer:
composer require twilio/sdkRead Also: Laravel 11 JSON Web Token(JWT) API Authentication Example Tutorial Step 4: Create Route
In routes/web.php, add a route to trigger sending a WhatsApp message:
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\WhatsAppController; /* |-------------------------------------------------------------------------- | 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('whatsapp', [WhatsAppController::class, 'index']); Route::post('whatsapp', [WhatsAppController::class, 'store'])->name('whatsapp.post');Step 5: Create Controller
Generate a new controller:
php artisan make:controller WhatsAppController
Edit WhatsAppController.php to include the logic for sending a WhatsApp message:
app/Http/Controllers/WhatsAppController.php<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Twilio\Rest\Client; use Exception; class WhatsAppController extends Controller { /** * Write code on Method * * @return response() */ public function index() { return view('whatsapp'); } /** * Write code on Method * * @return response() */ public function store(Request $request) { $twilioSid = env('TWILIO_SID'); $twilioToken = env('TWILIO_AUTH_TOKEN'); $twilioWhatsAppNumber = env('TWILIO_WHATSAPP_NUMBER'); $recipientNumber = $request->phone; $message = $request->message; try { $twilio = new Client($twilioSid, $twilioToken); $twilio->messages->create( $recipientNumber, [ "from" => "whatsapp:+". $twilioWhatsAppNumber, "body" => $message, ] ); return back()->with(['success' => 'WhatsApp message sent successfully!']); } catch (Exception $e) { return back()->with(['error' => $e->getMessage()]); } } }Read Also: Laravel 11 Update User Profile Example Tutorial Step 6: Create Blade File
Here, we will create "whatsapp.blade.php" file with following code:
resources/views/whatsapp.blade.php<!DOCTYPE html> <html> <head> <title>How to Send Whatsapp Message Using Laravel? -- ItErrorSolution.com</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-9"> <div class="card"> <div class="card-header"> <h2>How to Send Whatsapp Message Using Laravel? -- ItErrorSolution.com</h2> </div> <div class="card-body"> <form method="POST" action="{{ route('whatsapp.post') }}"> {{ csrf_field() }} @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <strong>{{ $message }}</strong> </div> @endif @if ($message = Session::get('error')) <div class="alert alert-danger alert-block"> <strong>{{ $message }}</strong> </div> @endif <div class="mb-3"> <label class="form-label" for="inputName">Phone:</label> <input type="text" name="phone" id="inputName" class="form-control @error('phone') is-invalid @enderror" placeholder="Phone Number"> @error('phone') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="mb-3"> <label class="form-label" for="inputName">Message:</label> <textarea name="message" id="inputName" class="form-control @error('message') is-invalid @enderror" placeholder="Enter Message"></textarea> @error('message') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="mb-3"> <button class="btn btn-success btn-submit">Send Message</button> </div> </form> </div> </div> </div> </div> </div> </body> </html>Step: Run the Application
Now, to run the Laravel application, please type the following command and press enter:
php artisan serve
Now, open your web browser and enter the provided URL to view the output of the application.
View Your Applicationhttp://localhost:8000/whatsappOutput:
Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!
"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"