How To Send WhatsApp Messages In Laravel 11

In Laravel 11, sending WhatsApp messages can be achieved using the WhatsApp Business API or third-party services that provide APIs for sending messages. Below is a detailed guide on how to send WhatsApp messages in Laravel 11 using the Twilio API as an example.

  1. Set Up Twilio Account:
    First, sign up for a Twilio account if you haven’t already. Twilio provides APIs for various communication channels, including WhatsApp. Once signed up, you’ll get access to your Twilio Account SID and Auth Token, which you’ll need to authenticate API requests.
  2. Install Twilio SDK for Laravel:
    In your Laravel project directory, install the Twilio SDK using Composer:
   composer require twilio/sdk
  1. Configure Twilio Credentials:
    Add your Twilio Account SID, Auth Token, and WhatsApp sender number to your Laravel application’s environment configuration file (.env):
   TWILIO_SID=your_twilio_account_sid
   TWILIO_AUTH_TOKEN=your_twilio_auth_token
   TWILIO_WHATSAPP_SENDER=your_twilio_whatsapp_sender_number
  1. Create a Controller for Sending Messages:
    Generate a controller to handle sending WhatsApp messages. For example:
   php artisan make:controller WhatsAppController
  1. Implement Message Sending Logic:
    In your WhatsAppController, create a method to send WhatsApp messages using the Twilio SDK:
   <?php

   namespace App\Http\Controllers;

   use Illuminate\Http\Request;
   use Twilio\Rest\Client;

   class WhatsAppController extends Controller
   {
       public function sendMessage(Request $request)
       {
           $twilio = new Client(config('services.twilio.sid'), config('services.twilio.auth_token'));

           $message = $twilio->messages->create(
               "whatsapp:" . $request->input('recipient_number'),
               [
                   "from" => "whatsapp:" . config('services.twilio.whatsapp_sender'),
                   "body" => $request->input('message')
               ]
           );

           return response()->json($message);
       }
   }
  1. Define Routes:
    Define a route to invoke the sendMessage method in your routes/web.php file:
   use App\Http\Controllers\WhatsAppController;

   Route::post('/send-whatsapp', [WhatsAppController::class, 'sendMessage']);
  1. Send Messages:
    You can now send WhatsApp messages by making a POST request to the /send-whatsapp route with the recipient’s number and message body.

By following these steps, you can integrate WhatsApp message sending functionality into your Laravel 11 application using the Twilio API. Remember to handle errors and exceptions gracefully, especially when dealing with external APIs like Twilio.

Leave a Reply