Hey there, fellow developer! Ready to supercharge your app with some sweet customer communication features? Let's dive into building an Intercom API integration using JavaScript. This guide will walk you through the process, assuming you're already familiar with the basics. We'll keep it concise and focus on the good stuff.
Before we jump in, make sure you've got:
Let's get this party started:
mkdir intercom-integration && cd intercom-integration npm init -y npm install axios dotenv
First things first, let's get you authenticated:
.env
file and add:INTERCOM_ACCESS_TOKEN=your_access_token_here
require('dotenv').config(); const axios = require('axios'); const intercomApi = axios.create({ baseURL: 'https://api.intercom.io', headers: { Authorization: `Bearer ${process.env.INTERCOM_ACCESS_TOKEN}`, 'Content-Type': 'application/json' } });
Now you're ready to rock! Here's a basic request structure:
async function getUsers() { try { const response = await intercomApi.get('/users'); return response.data; } catch (error) { console.error('Error fetching users:', error.response.data); } }
Let's cover some key operations:
async function getUser(userId) { const response = await intercomApi.get(`/users/${userId}`); return response.data; }
async function createOrUpdateUser(userData) { const response = await intercomApi.post('/users', userData); return response.data; }
async function getConversations() { const response = await intercomApi.get('/conversations'); return response.data; }
async function sendMessage(userId, message) { const response = await intercomApi.post('/messages', { message_type: 'inapp', user_id: userId, body: message }); return response.data; }
Time to listen for those Intercom events:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const event = req.body; console.log('Received event:', event.topic); // Handle the event based on its topic res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook listener running on port 3000'));
Remember to handle rate limits and log errors:
intercomApi.interceptors.response.use(null, error => { if (error.response && error.response.status === 429) { console.log('Rate limit hit. Retrying after cooldown...'); // Implement retry logic here } return Promise.reject(error); });
Don't forget to test! Here's a quick example using Jest:
test('getUser returns user data', async () => { const user = await getUser('test_user_id'); expect(user).toHaveProperty('id'); expect(user).toHaveProperty('email'); });
When deploying, remember to:
And there you have it! You've just built a solid Intercom API integration. Remember, this is just the beginning – there's so much more you can do with Intercom's API. Keep exploring, keep building, and most importantly, keep making those customers happy!
For more in-depth info, check out Intercom's API documentation. Now go forth and integrate!