In this part, we'll:

  • Create a simple service to send WhatsApp messages.
  • Handle incoming WhatsApp messages by replying automatically.

🐘 1. Twilio Service and Webhook in Laravel

Install Twilio SDK

composer require twilio/sdk

Create a simple Twilio service

Create a file at app/Services/TwilioService.php:

namespace App\Services;

use Twilio\Rest\Client;

class TwilioService
{
    protected $twilio;

    public function __construct()
    {
        $this->twilio = new Client(env('TWILIO_ACCOUNT_SID'), env('TWILIO_AUTH_TOKEN'));
    }

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

Set up the webhook route and use the service

Add this to your routes/web.php:

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

Route::post('/webhook', function (Request $request) {
    $phone = $request->input('From');
    $incomingMessage = $request->input('Body');

    $twilio = new TwilioService();
    $twilio->sendMessage($phone, "Hey 👋, thanks for your message: \"$incomingMessage\"");

    return response()->json(['status' => 'message sent'], 200);
});

✅ Now when Twilio sends a message, your webhook will automatically reply using the service!


🟰 2. Twilio Service and Webhook in Express

Install Twilio SDK

npm install twilio express

Create a simple Twilio service

Create a file twilioService.js:

const { Twilio } = require('twilio');

const client = new Twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

async function sendMessage(to, message) {
  return client.messages.create({
    from: 'whatsapp:' + process.env.TWILIO_WHATSAPP_FROM,
    to: 'whatsapp:' + to,
    body: message
  });
}

module.exports = { sendMessage };

Set up the webhook route and use the service

In your server.js:

const express = require('express');
const { sendMessage } = require('./twilioService');
const app = express();

app.use(express.urlencoded({ extended: true }));

app.post('/webhook', async (req, res) => {
  const phone = req.body.From;
  const incomingMessage = req.body.Body;

  await sendMessage(phone, `Hey 👋, thanks for your message: "${incomingMessage}"`);

  res.status(200).json({ status: 'message sent' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

✅ Now your Express app will automatically reply when a message is received!


🌎 3. Exposing your Local Server with ngrok

Since Twilio needs a public URL, you'll need to expose your localhost using ngrok.

Install ngrok

npm install -g ngrok

Start ngrok

For Laravel (port 8000):

ngrok http 8000

For Express (port 3000):

ngrok http 3000

ngrok will give you a public URL like:

https://random-ngrok-url.ngrok.io

Set this URL in your Twilio Sandbox Settings under "WHEN A MESSAGE COMES IN", adding /webhook at the end.

Example:

https://random-ngrok-url.ngrok.io/webhook

If you need more details using ngrok, you can check this post


🛠️ What's Next?

  • Customize replies based on user input.
  • Validate incoming requests from Twilio.
  • Move from Sandbox to Production environment.

Good luck! 🚀