Skip to Content

How to use WhatsApp api in laravel?

WhatsApp has become one of the most popular messaging platforms in the world, with over 2 billion active users. Given its widespread adoption, many developers are looking to integrate WhatsApp messaging capabilities into their applications. One popular framework for building web applications is Laravel, a free, open-source PHP web framework. With some configuration, it is possible to leverage the WhatsApp API in a Laravel application to send and receive WhatsApp messages programmatically.

Requirements

To use the WhatsApp API in Laravel, you will need:

  • A Laravel application set up on a server
  • A WhatsApp Business account
  • The WhatsApp Business API activated for your account
  • A dedicated virtual or physical device to use WhatsApp on
  • The phone number for your WhatsApp account whitelisted by Facebook for using the API

With these requirements met, you can start integrating WhatsApp messaging into your Laravel application using the WhatsApp Business API.

Setting Up a WhatsApp Business Account

To use the WhatsApp Business API, you first need to set up a WhatsApp Business account. Here are the steps to do this:

  1. Download the WhatsApp mobile app on your device
  2. Verify your phone number in WhatsApp
  3. Open WhatsApp, go to the settings menu, and tap “Business”
  4. Follow the on-screen prompts to create your business profile
  5. Complete setting up your business description, email, address, etc.

Once your WhatsApp Business account is created, take note of your business phone number as you’ll need this to configure the API.

Activating the WhatsApp Business API

With your business account ready, you now need to activate the WhatsApp Business API for your account:

  1. Go to the Facebook for Developers site
  2. Login and select your business account
  3. Go to Products > WhatsApp > Settings
  4. Accept the Terms of Service and click Activate

This will initiate the process to activate the API. Note that it can take up to 24 hours to fully activate.

Whitelist Your Phone Number

For your WhatsApp Business account phone number to work with the API, it needs to be whitelisted by Facebook. Here’s how:

  1. In the Facebook Developer Dashboard, go to Tools > Whitelisted Phone Numbers
  2. Enter your WhatsApp Business account phone number
  3. Click Add to whitelist the number

Again this can take up to 24 hours to process. Make sure your number is whitelisted before trying to implement the API.

Get an API Access Token

To allow your Laravel application to call the WhatsApp Business API, you need an access token. Here are the steps to get one:

  1. In the Dashboard, go to Products > WhatsApp > Settings
  2. Under Access Tokens, click Create New Token
  3. Give the token a name, then click Create
  4. Copy the generated access token value to use in your app

Make sure to store this access token securely, as it provides full access to your WhatsApp account via the API.

Install the WhatsApp PHP SDK

To call the WhatsApp Business API from Laravel, you can use the official WhatsApp PHP SDK. Install it using Composer:

composer require WhatsApp/WhatsApp-Web-API

This will install the SDK in your Laravel application’s vendor directory.

Configure the SDK

Once installed, you need to configure the SDK to use your access token and phone number:

// Filename: config/whatsapp.php

return [

  'token' => 'YOUR_ACCESS_TOKEN',
  
  'phone_number_id' => 'YOUR_WHATSAPP_NUMBER' 

];

Replace the placeholder values with your actual access token and WhatsApp business number.

Initialize the WhatsApp Client

With the SDK configured, you can now initialize the WhatsApp client in your application. For example, in a route service provider:

// Filename: app/Providers/RouteServiceProvider.php

use WhatsApp\Client as WhatsApp; 

public function boot() {

  $token = config('whatsapp.token');
  $phone = config('whatsapp.phone_number_id');  

  $whatsapp = new WhatsApp($token, $phone);

} 

This will create a WhatsApp client instance you can use to call the API.

Send a WhatsApp Message

To send a WhatsApp message from your Laravel application, you can use the sendMessage() method:

$whatsapp->sendMessage([
  'phone' => 'RECIPIENT_NUMBER', 
  'body' => 'Hello from Laravel!' 
]);

The phone parameter should contain the recipient’s phone number in international format. The body parameter contains the message text.

Receive Incoming Messages

To receive incoming WhatsApp messages to your account, you need to set up a webhook endpoint in your Laravel app. In your webhook route:

use Illuminate\Http\Request;

public function webhook(Request $request) {

  $data = $request->all();
  
  // Contains incoming message data

}

Then configure this webhook URL in the WhatsApp Dashboard under Webhooks > Configuration.

You can now process incoming messages in this endpoint, storing them in your database, sending responses, etc.

Implement Other API Features

The WhatsApp Business API provides many other features you may want to leverage:

  • Send media like images, audio, documents
  • Send WhatsApp templates
  • Create QR codes for easy messaging
  • Assign conversations to agent accounts
  • Set away messages when not available

Refer to the WhatsApp SDK documentation for details on implementing these features in your Laravel application.

Conclusion

Integrating WhatsApp into your Laravel application via the WhatsApp Business API opens up powerful messaging capabilities. Following the steps outlined here, you can activate the API for your business account, install the SDK, and start building features like sending messages, receiving messages via webhook, and more.

Some key points to remember when using the WhatsApp Business API in Laravel:

  • Activate your business account and whitelist your phone number first
  • Generate an access token and configure the SDK
  • Use the SDK to send messages, receive webhooks, etc.
  • Refer to WhatsApp’s documentation for additional API capabilities

With the ubiquity of WhatsApp, being able to integrate it into your Laravel applications provides huge engagement potential with your users. The WhatsApp Business API makes this possible, even for fairly complex Laravel-based platforms and products.

Setting up a WhatsApp Business Account

The first step to integrate WhatsApp into a Laravel application is to set up a WhatsApp Business account. Here is how to do it:

  1. Download the WhatsApp mobile app on your device and verify your phone number
  2. Open WhatsApp, go to the settings menu, and tap on “Business”
  3. Follow the prompts to create your business profile and complete your business description
  4. Your WhatsApp Business account will be created with the phone number you verified

Key Notes

  • Use a dedicated device for your business account to ensure reliability
  • Make sure to use a real phone number and not a VOIP number
  • Completely fill out your business profile for a verified account

Obtaining an API Access Token

To allow your Laravel app to interact with your WhatsApp Business account, you need an API access token. Follow these steps:

  1. Go to the Facebook for Developers site and login with your business account
  2. Navigate to Products > WhatsApp > Settings
  3. Accept the Terms of Service and click on “Activate” to activate the API
  4. Under the Access Tokens section, click on “Create New Token”
  5. Give the token a name and click on “Create”
  6. Copy the generated token to use in your Laravel app

Key Notes

  • Store the access token securely, keep it private
  • The token provides full access to your WhatsApp account
  • Regenerate the token if it gets compromised or leaked

Installing the WhatsApp PHP SDK

To interface with the WhatsApp Business API from Laravel, install the official WhatsApp PHP SDK:

composer require whatsapp/whatsapp-web-api

This will install the latest version of the SDK into your Laravel application’s vendor folder.

Key Notes

  • Require the SDK via Composer to receive updates
  • The SDK handles authentication and API requests
  • Refer to the SDK docs for usage instructions

Configuring the SDK

Once installed, configure the SDK to use your credentials:

// in config/whatsapp.php

return [
  'token' => 'YOUR_ACCESS_TOKEN',
  'phone_number_id' => 'YOUR_WHATSAPP_NUMBER'
];

Replace the placeholders with your actual access token and WhatsApp business number.

Key Notes

  • Set proper filesystem permissions on the config file
  • Version control the config file, but exclude tokens
  • Use environment variables for tokens in production

Initializing the WhatsApp Client

To initialize the WhatsApp client in your app:

// in app/Providers/WhatsAppServiceProvider.php

use WhatsApp\Client as WhatsApp;

public function register() {
  $config = config('whatsapp');
  $whatsapp = new WhatsApp($config['token'], $config['phone_number_id']);
  
  $this->app->singleton(WhatsApp::class, function() use ($whatsapp) {
    return $whatsapp;
  });
} 

Now you can inject the client where needed.

Key Notes

  • Initialize one client instance for the entire app
  • Use dependency injection to access the client
  • Make sure to handle any exceptions thrown

Sending WhatsApp Messages

To send messages from your Laravel app:

// Controller example

public function sendMessage(WhatsApp $whatsapp) {

  $response = $whatsapp->sendMessage([
    'phone' => 'RECIPIENT_NUMBER',
    'body' => 'Hello from Laravel!'
  ]);
  
  // Handle response

}

The phone parameter contains the recipient’s number, body has the message text.

Key Notes

  • Validate the recipient number format before sending
  • Check the response status for success/failure
  • Implement queued jobs for asynchronous sending

Receiving Inbound Messages

To receive incoming messages via a webhook:

// routes/web.php

Route::post('whatsapp/webhook', 'WebhookController@handle');

// WebhookController

public function handle(Request $request) {
  // Process incoming message data  
} 

Configure this webhook URL in your WhatsApp dashboard.

Key Notes

  • Use CSRF protection on the webhook endpoint
  • Validate request signatures for security
  • Handle attachments and media downloads

Additional WhatsApp Business API Features

Some other useful API capabilities include:

  • Send media files like images, audio, documents
  • Implement WhatsApp templates for efficient messaging
  • Set away status when agents are unavailable
  • Create QR codes for easy customer messaging
  • Assign conversations to agent accounts

Refer to the SDK documentation for help on implementing these features.

Key Notes

  • Leverage all available API options for a full-featured integration
  • Analyze chat history and metrics to improve support
  • Follow WhatsApp guidelines for proper feature usage

Conclusion

Integrating WhatsApp messaging into a Laravel application can provide immense value through native mobile engagement with your users. The WhatsApp Business API and SDK make this integration straightforward.

The key steps are:

  1. Set up a WhatsApp Business account and activate the API
  2. Obtain an API access token for your account
  3. Install and configure the WhatsApp PHP SDK
  4. Initialize the WhatsApp client in your Laravel app
  5. Leverage the client to send messages, receive webhooks, and more

With proper design and implementation, you can build rich messaging capabilities on top of Laravel. WhatsApp is used by billions of people worldwide, so integrating it can drastically increase your application’s user engagement and retention.