To send WhatsApp messages in Laravel, regardless of the version, you typically use third-party APIs. One popular API for WhatsApp integration is Twilio, which provides a straightforward way to send messages programmatically. Here’s a step-by-step guide using Laravel and Twilio:
- Create a Twilio Account:
Sign up for a Twilio account if you don’t have one. Obtain your Account SID, Auth Token, and a Twilio phone number. - Install Twilio SDK:
In your Laravel project, install the Twilio SDK using Composer:
composer require twilio/sdk
- Configure Twilio Credentials:
Add your Twilio credentials to the.env
file:
TWILIO_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number
- Create a Controller:
Generate a controller to handle WhatsApp messages:
php artisan make:controller WhatsAppController
- Write the Controller Code:
In theWhatsAppController.php
file, use the Twilio SDK to send a WhatsApp message:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
class WhatsAppController extends Controller
{
public function sendWhatsAppMessage(Request $request)
{
$to = $request->input('to'); // WhatsApp number
$message = $request->input('message');
$twilio = new Client(env('TWILIO_SID'), env('TWILIO_AUTH_TOKEN'));
$twilio->messages->create(
"whatsapp:{$to}",
[
'from' => "whatsapp:{$twilioPhoneNumber}",
'body' => $message,
]
);
return response()->json(['status' => 'success']);
}
}
- Define Routes:
In theroutes/web.php
file, define a route to the controller method:
use App\Http\Controllers\WhatsAppController;
Route::post('/send-whatsapp', [WhatsAppController::class, 'sendWhatsAppMessage']);
- Testing:
Create a form in your view to input the recipient’s number and message, then submit the form to the/send-whatsapp
endpoint.
Remember to replace placeholders like your_twilio_account_sid
and your_twilio_auth_token
with your actual Twilio credentials. Ensure that your server has internet access to communicate with the Twilio API.
Always refer to the official documentation for any updates or changes, and adapt the code accordingly based on the Laravel version you are using.