Step-by-step guide to integrating WhatsApp Business API with your existing systems and CRM platforms. Learn how to connect WhatsApp to your workflows, automate responses, and create seamless customer experiences.
๐ง Technical Overview
This guide covers both Cloud API and On-Premises API implementations, with practical examples for common integration scenarios.
Integrating WhatsApp Business API with your existing systems can transform how you communicate with customers. This comprehensive guide walks you through the entire process, from initial setup to advanced automation workflows.
Before diving into integration, you need to choose between two API options:
Before accessing the API, your business must be verified by Meta:
Start by creating a Facebook app and configuring WhatsApp Business:
1. Go to developers.facebook.com
2. Create new app โ Business
3. Add WhatsApp Business product
4. Complete business verification
5. Get phone number ID and access token
Set up a webhook to receive incoming messages and delivery updates:
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
// Webhook verification
app.get('/webhook', (req, res) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === process.env.VERIFY_TOKEN) {
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
});
// Receive webhook events
app.post('/webhook', (req, res) => {
const body = req.body;
// Verify webhook signature
const signature = req.headers['x-hub-signature-256'];
const expectedSignature = crypto
.createHmac('sha256', process.env.APP_SECRET)
.update(JSON.stringify(body))
.digest('hex');
if (signature !== `sha256=${expectedSignature}`) {
return res.sendStatus(403);
}
// Process incoming messages
if (body.object === 'whatsapp_business_account') {
body.entry.forEach(entry => {
entry.changes.forEach(change => {
if (change.field === 'messages') {
processMessage(change.value);
}
});
});
}
res.sendStatus(200);
});
Implement the core function to send messages via the API:
async function sendMessage(phoneNumber, message) {
const url = `https://graph.facebook.com/v17.0/${PHONE_NUMBER_ID}/messages`;
const payload = {
messaging_product: 'whatsapp',
to: phoneNumber,
type: 'text',
text: {
body: message
}
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
const result = await response.json();
console.log('Message sent:', result);
return result;
} catch (error) {
console.error('Send message error:', error);
throw error;
}
}
Support various message formats for rich communication:
// Send template message
async function sendTemplateMessage(phoneNumber, templateName, params) {
const payload = {
messaging_product: 'whatsapp',
to: phoneNumber,
type: 'template',
template: {
name: templateName,
language: {
code: 'en'
},
components: [
{
type: 'body',
parameters: params.map(param => ({
type: 'text',
text: param
}))
}
]
}
};
return await sendAPIRequest(payload);
}
// Send media message
async function sendMediaMessage(phoneNumber, mediaUrl, caption) {
const payload = {
messaging_product: 'whatsapp',
to: phoneNumber,
type: 'image',
image: {
link: mediaUrl,
caption: caption
}
};
return await sendAPIRequest(payload);
}
Connect WhatsApp messages to Salesforce records:
async function createSalesforceActivity(phoneNumber, message) {
// Search for existing contact
const contact = await salesforce.query(
`SELECT Id FROM Contact WHERE Phone = '${phoneNumber}' LIMIT 1`
);
let contactId;
if (contact.records.length > 0) {
contactId = contact.records[0].Id;
} else {
// Create new contact
const newContact = await salesforce.sobject('Contact').create({
Phone: phoneNumber,
LastName: 'WhatsApp Lead'
});
contactId = newContact.id;
}
// Create activity record
await salesforce.sobject('Task').create({
WhoId: contactId,
Subject: 'WhatsApp Message',
Description: message,
Status: 'Completed',
ActivityDate: new Date().toISOString().split('T')[0]
});
}
Sync WhatsApp conversations with HubSpot contacts and deals:
async function syncWithHubSpot(phoneNumber, message) {
const hubspot = require('@hubspot/api-client');
const client = new hubspot.Client({ accessToken: HUBSPOT_TOKEN });
try {
// Search for existing contact
const searchRequest = {
filterGroups: [{
filters: [{
propertyName: 'phone',
operator: 'EQ',
value: phoneNumber
}]
}]
};
const searchResult = await client.crm.contacts.searchApi.doSearch(searchRequest);
if (searchResult.results.length > 0) {
// Update existing contact
const contactId = searchResult.results[0].id;
await client.crm.contacts.basicApi.update(contactId, {
properties: {
'last_whatsapp_message': message,
'last_contact_date': new Date().toISOString()
}
});
} else {
// Create new contact
await client.crm.contacts.basicApi.create({
properties: {
phone: phoneNumber,
'first_whatsapp_message': message,
'contact_source': 'WhatsApp'
}
});
}
} catch (error) {
console.error('HubSpot sync error:', error);
}
}
Implement dynamic template selection and management:
Implement robust error handling and respect API limits:
class WhatsAppRateLimiter {
constructor() {
this.messageQueue = [];
this.processing = false;
this.rateLimits = {
perSecond: 20,
perMinute: 600,
perHour: 10000
};
}
async sendMessage(phoneNumber, message) {
return new Promise((resolve, reject) => {
this.messageQueue.push({
phoneNumber,
message,
resolve,
reject,
timestamp: Date.now()
});
this.processQueue();
});
}
async processQueue() {
if (this.processing || this.messageQueue.length === 0) return;
this.processing = true;
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift();
try {
// Check rate limits
if (this.isRateLimited()) {
await this.delay(1000);
continue;
}
const result = await this.sendAPIMessage(message);
message.resolve(result);
} catch (error) {
message.reject(error);
}
}
this.processing = false;
}
}
Comprehensive testing approach for WhatsApp integrations:
Essential considerations for production deployment:
WhatsApp Business API integration opens up powerful opportunities for customer engagement and automation. While the initial setup requires technical expertise, the long-term benefits of seamless customer communication make it a worthwhile investment. Start with basic messaging functionality and gradually add advanced features as your needs grow.
๐ฏ Integration outcomes:
OnSync provides complete WhatsApp Business API solutions with expert support and seamless integration.
We use cookies and similar technologies to enhance your experience and measure site performance. By continuing to use this site, you consent to our use of cookies. Learn more