WhatsApp API untuk Integrasi CRM
Cara integrasikan WhatsApp API dengan CRM. HubSpot, Salesforce, Zoho. Sync contacts, log conversations. Developer guide!
WhatsApp + CRM = Customer data yang lengkap!
Integrasi API memungkinkan semua chat WhatsApp tercatat di CRM. No more data silos!
Manfaat Integrasi
✅ Semua conversation logged
✅ Contact auto-sync
✅ 360° customer view
✅ Automated workflows
✅ Better reportingArchitecture
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ WhatsApp │───►│ Your API │───►│ CRM │
│ Cloud API │◄───│ Server │◄───│ (HubSpot) │
└──────────────┘ └──────────────┘ └──────────────┘
│
┌──────▼──────┐
│ Database │
└─────────────┘Integrasi HubSpot
Setup Connection:
javascript
const hubspot = require('@hubspot/api-client');
const hubspotClient = new hubspot.Client({
accessToken: process.env.HUBSPOT_ACCESS_TOKEN
});Sync Contact dari WhatsApp:
javascript
async function syncContactToHubspot(waContact) {
const { phone, name } = waContact;
// Search existing contact
const searchResponse = await hubspotClient.crm.contacts.searchApi.doSearch({
filterGroups: [{
filters: [{
propertyName: 'phone',
operator: 'EQ',
value: phone
}]
}]
});
const properties = {
phone: phone,
firstname: name.split(' ')[0],
lastname: name.split(' ').slice(1).join(' ') || '',
whatsapp_contact: 'true',
last_whatsapp_activity: new Date().toISOString()
};
if (searchResponse.total > 0) {
// Update existing
const contactId = searchResponse.results[0].id;
await hubspotClient.crm.contacts.basicApi.update(contactId, { properties });
return contactId;
} else {
// Create new
const response = await hubspotClient.crm.contacts.basicApi.create({ properties });
return response.id;
}
}Log Conversation:
javascript
async function logConversationToHubspot(contactId, message, direction) {
await hubspotClient.crm.objects.notes.basicApi.create({
properties: {
hs_note_body: `[WhatsApp ${direction}] ${message}`,
hs_timestamp: Date.now()
},
associations: [{
to: { id: contactId },
types: [{
associationCategory: 'HUBSPOT_DEFINED',
associationTypeId: 202 // Note to Contact
}]
}]
});
}
// Usage in webhook handler
async function handleIncomingMessage(message, contact) {
// Sync contact
const hubspotContactId = await syncContactToHubspot({
phone: message.from,
name: contact.profile.name
});
// Log message
await logConversationToHubspot(
hubspotContactId,
message.text.body,
'incoming'
);
// Process and reply
const reply = await generateReply(message);
await sendWhatsAppMessage(message.from, reply);
// Log outgoing
await logConversationToHubspot(
hubspotContactId,
reply,
'outgoing'
);
}Integrasi Salesforce
Setup Connection:
javascript
const jsforce = require('jsforce');
const conn = new jsforce.Connection({
loginUrl: 'https://login.salesforce.com'
});
await conn.login(
process.env.SF_USERNAME,
process.env.SF_PASSWORD + process.env.SF_TOKEN
);Sync Contact:
javascript
async function syncContactToSalesforce(waContact) {
const { phone, name } = waContact;
// Upsert contact by phone
const result = await conn.sobject('Contact').upsert({
Phone: phone,
FirstName: name.split(' ')[0],
LastName: name.split(' ').slice(1).join(' ') || 'Unknown',
WhatsApp_Number__c: phone,
Last_WhatsApp_Activity__c: new Date()
}, 'Phone'); // External ID field
return result;
}Log as Activity:
javascript
async function logActivityToSalesforce(contactId, message, direction) {
await conn.sobject('Task').create({
WhoId: contactId,
Subject: `WhatsApp ${direction}: ${message.substring(0, 50)}...`,
Description: message,
Status: 'Completed',
Type: 'WhatsApp',
ActivityDate: new Date().toISOString().split('T')[0]
});
}Create Case dari Komplain:
javascript
async function createCaseFromWhatsApp(contactId, complaint) {
const caseResult = await conn.sobject('Case').create({
ContactId: contactId,
Subject: `WhatsApp Complaint: ${complaint.substring(0, 100)}`,
Description: complaint,
Origin: 'WhatsApp',
Status: 'New',
Priority: 'Medium'
});
return caseResult.id;
}Integrasi Zoho CRM
Setup:
javascript
const axios = require('axios');
const zohoApi = axios.create({
baseURL: 'https://www.zohoapis.com/crm/v2',
headers: {
'Authorization': `Zoho-oauthtoken ${process.env.ZOHO_ACCESS_TOKEN}`
}
});Sync Contact:
javascript
async function syncContactToZoho(waContact) {
const { phone, name } = waContact;
// Search existing
const searchResponse = await zohoApi.get('/Contacts/search', {
params: { phone }
});
const contactData = {
First_Name: name.split(' ')[0],
Last_Name: name.split(' ').slice(1).join(' ') || '-',
Phone: phone,
WhatsApp_Active: true
};
if (searchResponse.data.data && searchResponse.data.data.length > 0) {
// Update
const contactId = searchResponse.data.data[0].id;
await zohoApi.put(`/Contacts/${contactId}`, { data: [contactData] });
return contactId;
} else {
// Create
const response = await zohoApi.post('/Contacts', { data: [contactData] });
return response.data.data[0].details.id;
}
}Full Integration Flow
javascript
// Main webhook handler with CRM integration
async function processWebhookWithCRM(body) {
const message = body.entry[0].changes[0].value.messages[0];
const contact = body.entry[0].changes[0].value.contacts[0];
// 1. Sync contact to CRM
const crmContactId = await syncContactToCRM({
phone: message.from,
name: contact.profile.name
});
// 2. Log incoming message
await logMessageToCRM(crmContactId, message.text.body, 'incoming');
// 3. Get customer context from CRM
const customerData = await getCustomerFromCRM(crmContactId);
// 4. Generate contextual reply
const reply = await generateContextualReply(message, customerData);
// 5. Send reply via WhatsApp
await sendWhatsAppMessage(message.from, reply);
// 6. Log outgoing message
await logMessageToCRM(crmContactId, reply, 'outgoing');
// 7. Update CRM based on conversation
if (isOrderIntent(message.text.body)) {
await updateDealStage(crmContactId, 'Qualified');
}
if (isComplaint(message.text.body)) {
await createSupportTicket(crmContactId, message.text.body);
}
}Automated Workflows
Lead Scoring:
javascript
async function updateLeadScore(crmContactId, activity) {
const scores = {
'replied': 5,
'asked_price': 10,
'asked_availability': 15,
'ready_to_order': 25
};
const score = scores[activity] || 5;
await crmClient.updateContact(crmContactId, {
lead_score: { $inc: score }
});
}Auto-assign to Sales:
javascript
async function autoAssignToSales(crmContactId, region) {
const salesReps = {
'jakarta': 'rep_001',
'surabaya': 'rep_002',
'bandung': 'rep_003'
};
const assignedRep = salesReps[region] || 'rep_default';
await crmClient.updateContact(crmContactId, {
owner_id: assignedRep
});
// Notify sales rep
await notifySalesRep(assignedRep, crmContactId);
}Best Practices
1. Real-time Sync
Sync immediately saat message masuk.
Jangan batch, data harus fresh.2. Error Handling
javascript
async function syncWithRetry(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) {
// Log to error queue for manual review
await logSyncError(error);
throw error;
}
await sleep(1000 * Math.pow(2, i));
}
}
}3. Data Mapping
Standardize format:
- Phone: 628xxx (international)
- Dates: ISO format
- Custom fields: Map properlyFAQ
CRM mana yang paling mudah?
HubSpot punya API paling developer-friendly. Free tier juga available.
Perlu middleware?
Recommended. Jangan direct connect. Middleware handle transformation, retry, dan buffering.
Bagaimana handle rate limit CRM?
Implement queue system dan batch updates untuk high volume.
Kesimpulan
WA + CRM = Complete customer intelligence!
| Without Integration | With Integration |
|---|---|
| Data silos | Unified view |
| Manual logging | Auto-logged |
| No context | Full history |
Connect your channels!