Sending WhatsApp Messages Using Laravel: A Step-by-Step Guide

18 Oct 2024 10:34 PM

In today’s digital landscape, WhatsApp has emerged as a powerful tool for communication. Leveraging this platform in your web applications can significantly enhance user engagement. In this post, we'll walk through how to send WhatsApp messages using Laravel and the Twilio API.

Prerequisites

Before we dive in, ensure you have the following:

  • A basic understanding of Laravel.
  • A Twilio account (if you don’t have one, you can sign up here).
  • Composer installed on your system.

Step 1: Set Up Your Twilio Account

  1. Create a Twilio Account: Head over to Twilio and sign up.

  2. Get a Twilio Phone Number: Once registered, navigate to the Twilio Console and purchase a phone number that supports WhatsApp.

  3. Enable WhatsApp in Twilio: Follow the instructions provided in Twilio’s documentation to enable the WhatsApp Sandbox. You'll need to link your personal WhatsApp number for testing purposes.

Step 2: Install the Twilio SDK

To communicate with the Twilio API, we need to install the Twilio PHP SDK. Open your terminal and run the following command:

composer require twilio/sdk

This will add the Twilio SDK to your Laravel project.

Step 3: Configure Environment Variables

To securely store your Twilio credentials, add them to your .env file:

TWILIO_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_WHATSAPP_FROM=whatsapp:+your_twilio_whatsapp_number

Replace your_account_sid, your_auth_token, and your_twilio_whatsapp_number with your actual Twilio account details.

Step 4: Create a WhatsApp Messaging Service

Next, let’s encapsulate our messaging logic into a service class. Create a file named WhatsAppService.php in the app/Services directory:

namespace App\Services;

use Twilio\Rest\Client;

class WhatsAppService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(config('TWILIO_SID'), config('TWILIO_AUTH_TOKEN'));
    }

    public function sendMessage($to, $message)
    {
        return $this->client->messages->create(
            "whatsapp:{$to}",
            [
                'from' => config('TWILIO_WHATSAPP_FROM'),
                'body' => $message,
            ]
        );
    }
}

In this service, we initialize the Twilio client and define a method sendMessage() to handle the message sending.

Step 5: Create a Controller

Next, we’ll create a controller to handle incoming requests. Create a file named WhatsAppController.php in app/Http/Controllers:

namespace App\Http\Controllers;

use App\Services\WhatsAppService;
use Illuminate\Http\Request;

class WhatsAppController extends Controller
{
    protected $whatsappService;

    public function __construct(WhatsAppService $whatsappService)
    {
        $this->whatsappService = $whatsappService;
    }

    public function send(Request $request)
    {
        $validated = $request->validate([
            'to' => 'required|string',
            'message' => 'required|string',
        ]);

        $this->whatsappService->sendMessage($validated['to'], $validated['message']);

        return response()->json(['status' => 'Message sent']);
    }
}

This controller validates the incoming request and uses the WhatsAppService to send the message.

Step 6: Define Your Routes

Now, we need to define a route to access our WhatsApp messaging functionality. Open routes/web.php or routes/api.php and add the following:

use App\Http\Controllers\WhatsAppController;

Route::post('/send-whatsapp', [WhatsAppController::class, 'send']);

Step 7: Testing Your Implementation

To test your new WhatsApp messaging feature, you can use Postman or any API client.

Making a Request

{
    "to": "+recipient_whatsapp_number",
    "message": "Hello from Laravel!"
}

Make sure the recipient has opted in to receive messages from your Twilio number.

Conclusion

Congratulations! You’ve successfully set up WhatsApp messaging in your Laravel application using the Twilio API. This feature can greatly enhance user communication and engagement.

Feel free to expand upon this implementation by adding error handling, message logging, or even scheduling messages. Happy coding! If you have any questions or need further assistance, don’t hesitate to reach out!

 

 

 

 

3
102