Laravel

Send whatsapp message using laravel

To send WhatsApp messages using the WhatsApp Business API in Laravel, you can utilize the Twilio API for seamless integration. Follow these steps to set it up:

Begin by installing the Twilio PHP package via Composer:

composer require twilio/sdk

Configure the Twilio credentials in your .env file. Add the following lines and replace the placeholders with your Twilio account details:

TWILIO_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_WHATSAPP_NUMBER=your_twilio_whatsapp_number

Create a new Laravel controller to handle the sending of WhatsApp messages. Run the following command to generate the controller file:

php artisan make:controller WhatsAppController

Inside the generated app/Http/Controllers/WhatsAppController.php file, replace the existing content with the following code:

<?php

namespace App\Http\Controllers;

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

class WhatsAppController extends Controller
{
    public function sendWhatsAppMessage(Request $request)
    {
        $message = $request->input('message');
        $to = $request->input('to');

        $twilio = new Client(config('TWILIO_SID'), config('TWILIO_AUTH_TOKEN'));

        $twilio->messages->create(
            "whatsapp:$to",
            [
                "from" => "whatsapp:" . config('TWILIO_WHATSAPP_NUMBER'),
                "body" => $message
            ]
        );

        return response()->json(['message' => 'WhatsApp message sent.']);
    }
}

Define the route to access the sendWhatsAppMessage method in your routes/web.php file:

Route::post('/send-whatsapp-message', 'WhatsAppController@sendWhatsAppMessage');

With these steps completed, you'll be able to send WhatsApp messages using the WhatsApp Business API in Laravel. To send a message, make a POST request to the /send-whatsapp-message endpoint with the message and to parameters in the request body. The message parameter should contain the text of the message, and the to parameter should contain the recipient's WhatsApp number.

Leave A Comment