JavaScript SDK
Official HueChat SDK for Node.js and browser applications.
Installation
npm install @huechat/sdk
# or
yarn add @huechat/sdk
# or
pnpm add @huechat/sdk
Quick Start
const HueChat = require('@huechat/sdk');
const client = new HueChat.Client({
apiKey: process.env.HUECHAT_API_KEY
});
// Create a contact
const contact = await client.contacts.create({
phone: '+1234567890',
firstName: 'John',
lastName: 'Doe'
});
// Send a message
const message = await client.messages.send(contact.id, {
channel: 'whatsapp',
messageType: 'text',
content: 'Hello from HueChat!'
});
console.log(`Message sent: ${message.id}`);
Configuration
Basic Setup
const client = new HueChat.Client({
apiKey: 'sk_live_your_key'
});
With Options
const client = new HueChat.Client({
apiKey: process.env.HUECHAT_API_KEY,
baseUrl: 'https://api.huechat.ai/v2', // Default
timeout: 30000, // Request timeout in ms
retries: 3, // Number of retries
debug: true // Enable debug logging
});
Environment-Based
const client = new HueChat.Client({
apiKey: process.env.HUECHAT_API_KEY,
// Automatically uses sandbox URL for test keys
// sk_test_* -> https://sandbox.huechat.ai/v2
// sk_live_* -> https://api.huechat.ai/v2
});
Contacts
Create Contact
const contact = await client.contacts.create({
phone: '+1234567890',
email: 'john@example.com',
firstName: 'John',
lastName: 'Doe',
preferredChannel: 'whatsapp',
metadata: {
customerId: 'cust_123',
plan: 'premium'
}
});
Get Contact
// By ID
const contact = await client.contacts.get('cnt_abc123');
// By phone
const contact = await client.contacts.get('+1234567890');
// By email
const contact = await client.contacts.get('john@example.com');
Update Contact
const updated = await client.contacts.update('cnt_abc123', {
firstName: 'Johnny',
metadata: {
plan: 'enterprise'
}
});
Delete Contact
await client.contacts.delete('cnt_abc123');
Get Contact Conversations
const conversations = await client.contacts.conversations('cnt_abc123', {
status: 'open',
limit: 20
});
Messages
Send Text Message
const message = await client.messages.send('cnt_abc123', {
channel: 'whatsapp',
messageType: 'text',
content: 'Hello! How can I help you today?'
});
Send Template Message
const message = await client.messages.send('cnt_abc123', {
channel: 'whatsapp',
messageType: 'template',
templateName: 'order_confirmation',
templateParameters: {
orderId: 'ORD-12345',
total: '$99.99',
deliveryDate: 'January 27'
}
});
Send Media Message
// Image
const message = await client.messages.send('cnt_abc123', {
channel: 'whatsapp',
messageType: 'image',
mediaUrl: 'https://example.com/image.jpg',
content: 'Check out this product!'
});
// Document
const message = await client.messages.send('cnt_abc123', {
channel: 'whatsapp',
messageType: 'document',
mediaUrl: 'https://example.com/invoice.pdf',
content: 'Here is your invoice'
});
Reply in Conversation
const message = await client.conversations.sendMessage('conv_xyz789', {
messageType: 'text',
content: 'Thanks for your patience!'
});
Conversations
List Conversations
const conversations = await client.conversations.list({
status: 'open',
channel: 'whatsapp',
limit: 50
});
for (const conv of conversations.data) {
console.log(`${conv.contact.fullName}: ${conv.lastMessagePreview}`);
}
Get Conversation
const conversation = await client.conversations.get('conv_xyz789');
Get Messages
const messages = await client.conversations.messages('conv_xyz789', {
limit: 100,
sort: 'created_at:asc'
});
Assign Conversation
await client.conversations.assign('conv_xyz789', {
assignedTo: 'usr_agent1',
internalNote: 'Please handle this VIP customer'
});
Add Labels
await client.conversations.addLabels('conv_xyz789', ['urgent', 'billing']);
Resolve Conversation
await client.conversations.resolve('conv_xyz789', {
resolutionReason: 'issue_resolved',
internalNote: 'Refund processed',
sendSatisfactionSurvey: true
});
Webhooks
Create Webhook
const webhook = await client.webhooks.create({
url: 'https://your-server.com/webhooks/huechat',
events: ['message.received', 'conversation.created']
});
// Save the signing secret!
console.log('Signing secret:', webhook.signingSecret);
List Webhooks
const webhooks = await client.webhooks.list();
Update Webhook
await client.webhooks.update('wh_abc123', {
events: ['message.received', 'message.sent'],
active: true
});
Delete Webhook
await client.webhooks.delete('wh_abc123');
Verify Signature
const isValid = HueChat.Webhook.verify(
request.body, // Raw body string
request.headers['x-huechat-signature'],
request.headers['x-huechat-timestamp'],
process.env.HUECHAT_WEBHOOK_SECRET
);
Error Handling
try {
const contact = await client.contacts.create({
phone: 'invalid-phone'
});
} catch (error) {
if (error instanceof HueChat.BadRequestError) {
console.log('Validation error:', error.message);
console.log('Details:', error.details);
} else if (error instanceof HueChat.UnauthorizedError) {
console.log('Invalid API key');
} else if (error instanceof HueChat.NotFoundError) {
console.log('Resource not found');
} else if (error instanceof HueChat.RateLimitError) {
console.log('Rate limited, retry after:', error.retryAfter);
} else {
throw error;
}
}
TypeScript Support
The SDK includes full TypeScript definitions:
import HueChat, { Contact, Message, Conversation } from '@huechat/sdk';
const client = new HueChat.Client({
apiKey: process.env.HUECHAT_API_KEY!
});
async function sendWelcome(contact: Contact): Promise<Message> {
return client.messages.send(contact.id, {
channel: 'whatsapp',
messageType: 'text',
content: `Welcome, ${contact.firstName}!`
});
}
Express Middleware
const express = require('express');
const HueChat = require('@huechat/sdk');
const app = express();
// Webhook verification middleware
app.use('/webhooks/huechat', HueChat.Webhook.middleware({
secret: process.env.HUECHAT_WEBHOOK_SECRET
}));
app.post('/webhooks/huechat', (req, res) => {
const event = req.body;
switch (event.type) {
case 'message.received':
console.log('New message:', event.data.content);
break;
case 'conversation.created':
console.log('New conversation:', event.data.id);
break;
}
res.status(200).send();
});