To send WhatsApp messages in Laravel with Vonage’s native SDK, follow these steps:

  1. Sign up for a Vonage account and get your API key and API secret.
  2. Install the Vonage PHP SDK via Composer by running the following command in your Laravel project directory:

composer require vonage/client

  1. In your Laravel project, create a new class that will handle the sending of WhatsApp messages. For example, create a new file named VonageWhatsApp.php in your app directory.
  2. In the VonageWhatsApp class, add the following code:


<?php

namespace App;

use Vonage\Client;
use Vonage\Client\Credentials\Basic;
use Vonage\Client\Exception\Request;

class VonageWhatsApp
{
private $basic;
private $client;

public function __construct()
{
    $this->basic = new Basic(env('VONAGE_API_KEY'), env('VONAGE_API_SECRET'));
    $this->client = new Client($this->basic);
}

public function sendMessage($to, $text)
{
    try {
        $response = $this->client->message()->send([
            'to' => $to,
            'from' => 'whatsapp:' . env('VONAGE_WHATSAPP_NUMBER'),
            'text' => $text,
        ]);
        return $response->getResponseData();
    } catch (Request $e) {
        throw new \Exception($e->getMessage());
    }
}}
  1. In your .env file, add the following configuration variables:
VONAGE_API_KEY=your_api_key
VONAGE_API_SECRET=your_api_secret
VONAGE_WHATSAPP_NUMBER=your_whatsapp_number

Replace your_api_key, your_api_secret, and your_whatsapp_number with your Vonage API key, API secret, and WhatsApp-enabled phone number, respectively.

  1. In your Laravel controller or wherever you want to send a WhatsApp message, create a new instance of the VonageWhatsApp class and call the sendMessage method:

    use App\VonageWhatsApp;

class MyController extends Controller
{
public function sendMessage()
{
$to = 'whatsapp:+1234567890';
$text = 'Hello, world!';$whatsapp = new VonageWhatsApp();
    $response = $whatsapp->sendMessage($to, $text);

    dd($response);
}}

Replace +1234567890 with the WhatsApp-enabled phone number of the recipient.

  1. Test the sendMessage method by calling the controller method that sends the WhatsApp message.

Note that you will need to have an active WhatsApp account on the phone number you’re sending the message from. Also, keep in mind that WhatsApp has restrictions on the types of messages that can be sent using their API, such as not allowing promotional messages. Make sure you comply with WhatsApp’s guidelines to avoid being blocked.

By Navid Anjum

Full-stack web developer and founder of Laravelaura. He makes his tutorials as simple as humanly possible and focuses on getting the students to the point where they can build projects independently. https://github.com/NavidAnjum

Leave a Reply

Your email address will not be published. Required fields are marked *