Sending WhatsApp messages using Twilio in a Laravel 11 application involves setting up Twilio, integrating it into your Laravel project, and creating a simple interface to send messages. Here's how you can do it step by step:
### Step 1: Set Up Twilio Account
1. **Sign Up for Twilio**: If you don’t have a Twilio account, sign up at [Twilio](https://www.twilio.com/).
2. **Get WhatsApp Sandbox**: After signing in, navigate to the [WhatsApp Sandbox](https://www.twilio.com/console/sms/whatsapp/sandbox) in the Twilio Console. Twilio provides a sandbox environment for testing WhatsApp messages. You’ll get a sandbox phone number and an access code.
3. **Configure Sandbox**: Follow the instructions on the sandbox page to join the sandbox by sending a WhatsApp message with the given code to the Twilio sandbox number.
### Step 2: Install Twilio SDK
Install the official Twilio SDK using Composer:
```bash
composer require twilio/sdk
```
### Step 3: Configure Environment Variables
Add your Twilio credentials to the `.env` file:
```env
TWILIO_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_WHATSAPP_FROM=whatsapp:+14155238886 # Twilio WhatsApp sandbox number
```
### Step 4: Create a Service Class for Sending WhatsApp Messages
Create a new service class to handle sending WhatsApp messages:
```bash
php artisan make:service TwilioService
```
In `app/Services/TwilioService.php`, add the following code:
```php
namespace App\Services;
use Twilio\Rest\Client;
class TwilioService
{
protected $client;
public function __construct()
{
$this->client = new Client(env('TWILIO_SID'), env('TWILIO_AUTH_TOKEN'));
}
public function sendWhatsAppMessage($to, $message)
{
return $this->client->messages->create(
'whatsapp:' . $to,
[
'from' => env('TWILIO_WHATSAPP_FROM'),
'body' => $message
]
);
}
}
```
### Step 5: Create a Controller to Handle Requests
Create a controller that will handle sending WhatsApp messages:
```bash
php artisan make:controller WhatsAppController
```
In `app/Http/Controllers/WhatsAppController.php`, add the following code:
```php
namespace App\Http\Controllers;
use App\Services\TwilioService;
use Illuminate\Http\Request;
class WhatsAppController extends Controller
{
protected $twilio;
public function __construct(TwilioService $twilio)
{
$this->twilio = $twilio;
}
public function sendMessage(Request $request)
{
$request->validate([
'phone' => 'required|regex:/^\+?\d{10,15}$/',
'message' => 'required|string|max:1600',
]);
$phone = $request->input('phone');
$message = $request->input('message');
try {
$this->twilio->sendWhatsAppMessage($phone, $message);
return redirect()->back()->with('success', 'Message sent successfully!');
} catch (\Exception $e) {
return redirect()->back()->with('error', 'Failed to send message: ' . $e->getMessage());
}
}
}
```
### Step 6: Create a Form to Send WhatsApp Messages
Create a simple Blade view for sending WhatsApp messages. Create a new file at `resources/views/whatsapp.blade.php`:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send WhatsApp Message</title>
</head>
<body>
<h1>Send WhatsApp Message</h1>
@if (session('success'))
<p style="color: green;">{{ session('success') }}</p>
@endif
@if (session('error'))
<p style="color: red;">{{ session('error') }}</p>
@endif
<form action="{{ route('whatsapp.send') }}" method="POST">
@csrf
<label for="phone">Phone Number (including country code):</label>
<input type="text" id="phone" name="phone" required>
<br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<br><br>
<button type="submit">Send Message</button>
</form>
</body>
</html>
```
### Step 7: Define the Routes
Add the necessary routes to `routes/web.php`:
```php
use App\Http\Controllers\WhatsAppController;
Route::get('/whatsapp', function () {
return view('whatsapp');
})->name('whatsapp.form');
Route::post('/whatsapp/send', [WhatsAppController::class, 'sendMessage'])->name('whatsapp.send');
```
### Step 8: Test Sending WhatsApp Messages
Start your Laravel server:
```bash
php artisan serve
```
Navigate to `http://localhost:8000/whatsapp`, enter the recipient's phone number (including the country code), type a message, and submit the form. If everything is set up correctly, the message should be sent via WhatsApp using the Twilio API.
### Conclusion
By following these steps, you can easily integrate Twilio's WhatsApp messaging service into your Laravel 11 application. This setup allows you to send WhatsApp messages programmatically, which can be useful for notifications, alerts, or even two-factor authentication.
0 Comments