WhatsApp has become an integral part of our daily lives. Most businesses and organizations use WhatsApp to engage and support their customers. Integrating WhatsApp API in Laravel applications can help enhance customer experience by enabling important features like notifications, chatbots, surveys and more.
In this comprehensive guide, we will walk you through the step-by-step process of integrating WhatsApp API in a Laravel 8 application.
Prerequisites
Before we start with the integration, let’s first go through the prerequisites:
- Basic knowledge of PHP, Laravel and REST APIs
- Composer installed to manage Laravel dependencies
- Laravel 8 application set up on your local machine or server
- Free WhatsApp Business API account and phone number
Make sure you have the above prerequisites in place before moving further with the integration steps.
Step 1 – Get WhatsApp Business API Account
The first step is to get access to the WhatsApp Business API by creating an account.
Visit the official WhatsApp Business API website and click on ‘Get Started’. Follow the prompts and create your business account by adding details like business name, email, phone number etc.
Once your account is approved, you will get access to your business phone number and APIs to build WhatsApp integrations.
Key Things to Note
- You can only create one account per business for now
- Make sure to verify the email and phone number added during sign up
- The business phone number will be used for all API communication
This unique WhatsApp business number will be used later for sending and receiving messages from your Laravel application using the API.
Step 2 – Generate API Credentials
Now that you have a WhatsApp business account, the next step is to generate the API credentials which will be used by the Laravel application to authenticate and communicate with the WhatsApp APIs.
Follow these steps to generate your API credentials:
- Login to your WhatsApp business account at www.facebook.com/business/help
- Go to Settings > Apps > Add new app
- Give app name, description, category and agree to the terms
- Click on Generate new credentials and copy the generated keys
This will generate the app ID, app secret and access token which we will use later in the Laravel .env file for configuration.
Key Things to Note
- Store the app credentials securely in your Laravel .env file
- Do not share the app secret key to maintain authentication security
- You can generate access token as required from the WhatsApp UI
Step 3 – Add WhatsApp API Package in Laravel
Now that we have the API credentials, the next step is to install the WhatsApp API package in Laravel using Composer.
Run the following command in your Laravel app root directory to install the laravel-wa API wrapper:
composer require notificationchannels/laravel-wa
This will install the latest version of the laravel-wa package and update composer.json and composer.lock files.
Key Things to Note
- We are using the laravel-wa package by Notification Channels for WhatsApp API integration
- There are other community packages like chatsms/laravel-whatsapp-web as well
- Make sure to run composer update if package already exists
The WhatsApp API package provides an easy way to integrate WhatsApp APIs with Laravel apps using a clean syntax.
Step 4 – Add Service Provider & Aliases
With the package installed, we now need to register the Service Provider and Facade alias in Laravel.
Open config/app.php file and add the following to providers array:
'providers' => [
//...
NotificationChannels\Whatsapp\WhatsappServiceProvider::class
]
Next, add the Facade alias to the aliases array:
'aliases' => [
//...
'Whatsapp' => NotificationChannels\Whatsapp\WhatsappFacade::class
]
This will register the WhatsApp service provider and alias for easy usage in Laravel app.
Key Things to Note
- Run composer dump-autoload to refresh namespaces
- Add service provider before RouteServiceProvider
- Use ‘Whatsapp’ alias for facade instead of full namespace
Step 5 – Add API Credentials to .env
We are now ready to add the API credentials that we generated earlier in the Laravel .env file.
Open the .env file in your Laravel app root and add the following lines:
WHATSAPP_AUTH_TOKEN=abcdefghijklmnopqrstuvwxyz
WHATSAPP_ACCOUNT_ID=0123456789
WHATSAPP_API_URL=https://graph.facebook.com/v13.0/
Update the auth token, account ID and API URL as per the values from your WhatsApp business account.
Key Things to Note
- Get latest auth token from WhatsApp account settings
- Do not commit the .env file with secrets to source control
- API URL version may change as per WhatsApp updates
This will provide environment specific configuration for API communication from your Laravel app.
Step 6 – Send Test Message
Our WhatApp API integration is now ready! Let’s send a test message to verify that it works.
Create a new controller method like this:
namespace App\Http\Controllers;
use Whatsapp;
class TestController extends Controller
{
public function sendMessage() {
$response = Whatsapp::sendMessage([
'phone' => '1234567899',
'body' => 'Hi there!'
]);
return $response;
}
}
When you call this method, it will use the laravel-wa package to send a WhatsApp message using your business phone number to the phone number specified.
You should receive the test message on the specified mobile number once it is delivered.
The response will contain status, message ID and other information about the sent message.
Key Things to Note
- Make sure to import the Whatsapp facade
- Change phone and message as per your test requirements
- Refer WhatsApp API docs for more options and examples
This confirms that our WhatsApp integration works as expected. You can now build additional logic using Laravel and WhatsApp APIs.
Step 7 – Receive Incoming Messages
Till now we have seen how to send outbound messages from Laravel to WhatsApp. But for complete integration, we also need to handle incoming messages.
When a user replies or sends a message to your business phone number, it needs to be routed to your Laravel application for processing.
WhatsApp provides a webhook option to configure a callback URL in your account. We need to setup an endpoint in Laravel to receive the inbound message data.
Follow these steps:
- Go to WhatsApp account > Settings > Webhooks > Configure URL
- Set the webhook URL to: YOUR_LARAVEL_URL/api/webhook/receive
- In Laravel, create a route and controller method to handle this endpoint
// routes/api.php
Route::post('/webhook/receive', 'WebhookController@receive');
// WebhookController.php
public function receive() {
// Contains inbound message data from WhatsApp
}
This will send all incoming messages from your WhatsApp account to the configured webhook URL in Laravel application.
Key Things to Note
- Enable Laravel app over HTTPS for webhook URL
- Add code to verify webhook signature
- Print and process request data for testing
By handling these webhooks, you can respond to messages, trigger notifications and build conversational bots via Laravel.
Step 8 – Send Media Messages
So far we have seen how to send text messages from Laravel to WhatsApp. The API also provides the capability to send media messages like images, documents and videos.
To send a media message, we need to pass the media content as base64 encoded data along with the filename and mime type.
Here is an example to send an image:
// Attach image as base64
$imageData = base64_encode(file_get_contents('image.jpg'));
$response = Whatsapp::sendMedia([
'phone' => '1234567899',
'body' => 'See this image!',
'filename' => 'image.jpg',
'caption' => 'Image sample',
'mimeType' => 'image/jpeg',
'media' => $imageData
]);
Similar process can be followed to attach documents, videos and other media types.
Key Things to Note
- Optimize media before sending to reduce size
- Add appropriate filename and MIME type
- Use media uploader to avoid base64 encoding
This enables building chatbots, product catalogs, order notifications and other solutions with media capabilities using Laravel and WhatsApp.
Step 9 – User Management & Messaging
For most applications, you need to maintain a database of users and map their WhatsApp numbers for communication.
Some ways to achieve this:
- Maintain a users table with name, phone, WhatsApp id etc.
- Use phone number as unique key for mapping
- Add relationships to link users table with orders, support etc.
- Fetch user by phone number before sending WhatsApp message
// Fetch user
$user = User::where('phone', '1234567890')->first();
// Send message
Whatsapp::sendMessage([
'phone' => $user->phone,
'body' => 'Hello '.$user->name
]);
You can also use Laravel model events like creating order, changing status etc. to trigger WhatsApp notifications to users.
Key Things to Note
- Use phone number for WhatsApp mapping
- Add messaging opt-in option for users
- Follow WhatsApp policy for user messages
Proper user management ensures you message the right users and enhance engagement.
Step 10 – Automate Notifications & Alerts
One of the key benefits of integrating WhatsApp is the ability to send event-based alerts and notifications to users.
For example, you can send order updates, shipping alerts, appointment reminders, payment notifications automatically using Laravel.
Some common use cases for automation:
- New order placed – Send confirmation message
- Order shipped – Send tracking info and link
- Appointment booked – Send reminder before appointment
- Payment failed – Send payment retry notification
These can be achieved by creating Laravel jobs, listeners or handlers for the specific events and triggering WhatsApp messages from there.
// On order created
event(new OrderCreated($order));
// Handle event
class SendOrderMessage implements ShouldQueue
{
public function handle(OrderCreated $event)
{
$order = $event->order;
// Send WhatsApp message to customer
}
}
Scheduling cron jobs periodically is another great way to send automated messages and alerts.
Key Things to Note
- Follow user opt-in and preferences
- Add variety to avoid repetitive notifications
- Include option to disable notifications
Automated notifications and alerts take WhatsApp integration to the next level.
Step 11 – Build WhatsApp Chatbot
Chatbots make conversing with customers easy and efficient. With Laravel and WhatsApp API, you can build smart chatbots to handle conversations.
Here are some tips for building WhatsApp chatbots:
- Use Laravel command to create bot skeleton
- Define conversational flow with commands, questions etc.
- Integrate natural language processing for intelligence
- Add capabilities like checking order status, support queries etc.
- Fall back to human agent when needed
// Basic echo bot
if (Str::startsWith($message, '/start')) {
return "Welcome to ABC chatbot!";
}
if (Str::contains($message, ['hi', 'hello'])) {
return "Hello there!";
}
return "Sorry I didn't understand that.";
Keep improving the bot with more capabilities like transactions, recommendations, personalization etc.
Key Things to Note
- Start with basic conversational flow
- Analyze real user conversations
- Continuously train the bot with feedback
WhatsApp chatbots create magical customer experience when built right!
Conclusion
Integrating WhatsApp API in Laravel opens up many possibilities for engaging customers and enhancing user experience.
Once the initial integration is done, we have seen the different use cases like sending messages and media, receiving webhooks, automation, chatbots and more.
Some key takeaways from this guide:
- Choose proper Laravel WhatsApp package for ease of integration
- Follow WhatsApp policy, ethics and permissions for messaging
- Start simple and evolve chatbots with continuous learning
- Analyze user conversations to improve messaging
- Use Laravel broadcasting for real-time messaging
There are many creative ways you can leverage WhatsApp and Laravel framework to engage your users.
So go ahead, integrate WhatsApp API in your Laravel application and enhance your customer experience today!