Dokumentasi Integrasi Live Chat Widget

Panduan lengkap untuk mengintegrasikan widget live chat Talky ke website Anda. Widget ini mendukung real-time messaging, file upload, dan integrasi dengan AI agent WhatsApp Business.

๐Ÿš€Quick Start

Mulai dengan cepat dalam 3 langkah sederhana:

1

Download Widget

Download file widget-simple.js dari dashboard Talky

2

Tambahkan Script

Tambahkan satu baris script ke website Anda

3

Konfigurasi

Inisialisasi dengan API key dan konfigurasi

๐ŸŽฎ Live Demo

Lihat langsung bagaimana widget bekerja sebelum mengintegrasikan ke website Anda.

โœ…
Fitur Terbaru: Widget sekarang memuat Socket.IO secara otomatis! Tidak perlu lagi menambahkan script Socket.IO secara manual.

๐Ÿ“ฆInstalasi

1. HTML Standar

Untuk website HTML biasa, tambahkan script berikut sebelum closing tag </body>:

index.html
<!DOCTYPE html>
<html>
<head>
  <title>Website Anda</title>
</head>
<body>
  <!-- Konten website Anda -->
  
  <!-- Talky Live Chat Widget -->
  <script src="https://talky.id/widget-min.js"></script>
  <script>
    // Inisialisasi widget
    window.addEventListener('load', async () => {
      const widget = await initLiveChat({
        apiKey: "your-api-key-here",
        visitorInfo: {
          name: "Pengunjung",
          email: "visitor@example.com"
        }
      });
    });
  </script>
</body>
</html>

2. Next.js

Untuk aplikasi Next.js, Anda bisa menggunakan beberapa pendekatan:

Opsi A: Script di _document.js

pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
      <Head />
      <body>
        <Main />
        <NextScript />
        
        {/* Talky Live Chat Widget */}
        <script src="https://talky.id/widget-min.js"></script>
        <script
          dangerouslySetInnerHTML={{
            __html: `
              window.addEventListener('load', async () => {
                const widget = await initLiveChat({
                  apiKey: "your-api-key-here",
                  visitorInfo: {
                    name: "Pengunjung",
                    email: "visitor@example.com"
                  }
                });
              });
            `
          }}
        />
      </body>
    </Html>
  )
}

Opsi B: Custom Hook

hooks/useLiveChat.js
import { useEffect, useState } from 'react';

export const useLiveChat = (config) => {
  const [widget, setWidget] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    // Load widget script
    const script = document.createElement('script');
    script.src = 'https://talky.id/widget-min.js';
    script.async = true;
    
    script.onload = async () => {
      try {
        const widgetInstance = await window.initLiveChat(config);
        setWidget(widgetInstance);
        setIsLoaded(true);
      } catch (error) {
        console.error('Failed to initialize live chat:', error);
      }
    };

    document.head.appendChild(script);

    return () => {
      if (widget) {
        widget.destroy();
      }
      document.head.removeChild(script);
    };
  }, []);

  return { widget, isLoaded };
};
components/LiveChatWidget.jsx
import { useLiveChat } from '../hooks/useLiveChat';

const LiveChatWidget = () => {
  const { widget, isLoaded } = useLiveChat({
    apiKey: "your-api-key-here",
    visitorInfo: {
      name: "Pengunjung",
      email: "visitor@example.com"
    }
  });

  return null; // Widget akan muncul otomatis
};

export default LiveChatWidget;

3. React

App.js
import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Load widget script
    const script = document.createElement('script');
    script.src = 'https://talky.id/widget-min.js';
    script.async = true;
    
    script.onload = async () => {
      const widget = await window.initLiveChat({
        apiKey: "your-api-key-here",
        visitorInfo: {
          name: "Pengunjung",
          email: "visitor@example.com"
        }
      });
    };

    document.head.appendChild(script);

    return () => {
      document.head.removeChild(script);
    };
  }, []);

  return (
    <div className="App">
      {/* Konten aplikasi Anda */}
    </div>
  );
}
โ„น๏ธ
Catatan: Widget akan otomatis memuat Socket.IO dari server. Tidak perlu menambahkan script Socket.IO secara manual.

โš™๏ธKonfigurasi

Widget mendukung berbagai opsi konfigurasi untuk menyesuaikan tampilan dan perilaku:

Konfigurasi Dasar

const widget = await initLiveChat({
  // Required
  apiKey: "your-api-key-here",
  
  // Optional - User Information
  userId: "user_123", // Untuk session persistence per user
  visitorInfo: {
    name: "John Doe",
    email: "john@example.com",
    phone: "+62812345678",
    company: "PT. Example"
  }
});
โ„น๏ธ
Server URL: Jika tidak diisi, widget akan menggunakanhttps://api.talky.id sebagai default. Untuk production, ganti dengan URL server Anda.

Konfigurasi Minimal

// Konfigurasi paling sederhana - hanya API key
const widget = await initLiveChat({
  apiKey: "your-api-key-here"
});

// Widget akan menggunakan default:
// - persistSession: true
// - enableFullscreen: true

Kustomisasi Tampilan

const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  
  // Warna kustom
  primaryColor: "#10b981",      // Warna utama
  secondaryColor: "#059669",    // Warna sekunder
  backgroundColor: "#ffffff",   // Background
  textColor: "#1f2937",         // Warna teks
  agentBubbleColor: "#f3f4f6",  // Bubble pesan agent
  userBubbleColor: "#10b981",   // Bubble pesan user
  userBubbleTextColor: "#ffffff", // Teks bubble user
  
  // Posisi widget
  position: "bottom-right", // bottom-right, bottom-left
  
  // Theme
  theme: "modern" // modern, classic
});

Session Persistence

const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  
  // Session persistence
  persistSession: true, // Default: true
  sessionStorage: "localStorage", // "localStorage" atau "sessionStorage"
  userId: "user_123", // Untuk multi-device session
  
  // Session akan expire otomatis setelah 24 jam
});

Fullscreen Mode

const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  
  // Fullscreen options
  enableFullscreen: true, // Default: true
  fullscreenBreakpoint: 768, // Auto-fullscreen di mobile (px)
});

Event Callbacks

const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  
  // Event handlers
  onMessage: (message) => {
    console.log('New message:', message);
    // Kirim ke analytics, dll
  },
  
  onTyping: (data) => {
    console.log('Typing indicator:', data);
  },
  
  onError: (error) => {
    console.error('Widget error:', error);
    // Error handling
  }
});

Parameter Lengkap

Required:
  • apiKey - API key dari dashboard
Optional:
  • userId - ID user untuk session
  • visitorInfo - Info pengunjung
  • persistSession - Enable session persistence
  • enableFullscreen - Enable fullscreen mode
  • primaryColor - Warna utama widget
  • position - Posisi widget
  • Dan banyak lagi...
โ„น๏ธ
Environment Variables: Disarankan menggunakan environment variables untuk konfigurasi yang berbeda antara development dan production.

๐Ÿ“Contoh Implementasi

E-commerce Website

// Untuk website e-commerce dengan info customer
const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  userId: customerData.id,
  visitorInfo: {
    name: customerData.name,
    email: customerData.email,
    phone: customerData.phone,
    customerType: "premium",
    lastOrder: customerData.lastOrderId
  },
  primaryColor: "#e11d48", // Brand color
  onMessage: (message) => {
    // Track customer interactions
    analytics.track('chat_message_received', {
      customerId: customerData.id,
      messageType: message.sender
    });
  }
});

SaaS Dashboard

// Untuk aplikasi SaaS dengan user login
const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  userId: user.id,
  visitorInfo: {
    name: user.name,
    email: user.email,
    plan: user.subscription.plan,
    company: user.company.name,
    accountValue: user.subscription.value
  },
  position: "bottom-left", // Tidak mengganggu dashboard
  enableFullscreen: false, // Disable fullscreen di desktop
  onMessage: (message) => {
    // Notifikasi untuk support team
    if (message.sender === 'user') {
      notifySupport({
        userId: user.id,
        message: message.content,
        priority: user.subscription.plan === 'enterprise' ? 'high' : 'normal'
      });
    }
  }
});

Landing Page

// Untuk landing page dengan lead capture
const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  visitorInfo: {
    source: "landing-page",
    campaign: getUrlParameter('utm_campaign'),
    medium: getUrlParameter('utm_medium'),
    referrer: document.referrer
  },
  primaryColor: "#3b82f6",
  onMessage: (message) => {
    // Track leads
    if (message.metadata?.isRegistration) {
      gtag('event', 'lead_generated', {
        source: 'live_chat',
        campaign: getUrlParameter('utm_campaign')
      });
    }
  }
});

Multi-language Support

// Deteksi bahasa dan sesuaikan widget
const userLanguage = navigator.language || 'id';
const isEnglish = userLanguage.startsWith('en');

const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  visitorInfo: {
    language: userLanguage,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
  },
  // Sesuaikan warna berdasarkan region
  primaryColor: isEnglish ? "#2563eb" : "#10b981"
});

๐Ÿ“šAPI Reference

Widget Methods

widget.open()

Membuka widget chat

widget.open();

widget.close()

Menutup widget chat

widget.close();

widget.toggle()

Toggle buka/tutup widget

widget.toggle();

widget.toggleFullscreen()

Toggle mode fullscreen

widget.toggleFullscreen();

widget.clearSessionData()

Hapus data session (untuk logout)

widget.clearSessionData();

widget.destroy()

Hancurkan widget dan bersihkan memory

widget.destroy();

Widget Properties

PropertyTypeDescription
sessionIdstringID session saat ini
conversationIdstringID percakapan aktif
isOpenbooleanStatus widget terbuka/tertutup
isFullscreenbooleanStatus fullscreen mode
currentViewstringView aktif: 'home', 'registration', 'chat'
userInfoobjectInformasi user yang sedang chat

๐Ÿ”งTroubleshooting

Masalah Umum

Widget tidak muncul

Kemungkinan penyebab dan solusi:

  • Pastikan API key valid dan aktif
  • Cek console browser untuk error JavaScript
  • Pastikan script widget dimuat dengan benar
  • Cek koneksi internet dan firewall
// Debug: Cek apakah widget berhasil dimuat
console.log('Widget instance:', window.liveChatWidgetInstance);
console.log('initLiveChat function:', window.initLiveChat);

Socket.IO tidak terhubung

Widget akan fallback ke API, tapi untuk debugging:

// Cek status Socket.IO
console.log('Socket.IO loaded:', !!window.io);
if (widget.socket) {
  console.log('Socket connected:', widget.socket.connected);
  console.log('Socket ID:', widget.socket.id);
}

Session tidak tersimpan

Periksa pengaturan browser dan storage:

// Cek localStorage/sessionStorage
console.log('LocalStorage available:', !!window.localStorage);
console.log('Session data:', localStorage.getItem('livechat_session_your-api-key'));

// Manual clear session
widget.clearSessionData();

File upload gagal

Periksa ukuran dan tipe file:

  • Maksimal 10MB per file
  • Maksimal 5 file sekaligus
  • Tipe file yang didukung: gambar, PDF, dokumen, arsip
  • Pastikan server mendukung upload file

Debug Mode

Untuk debugging yang lebih detail, aktifkan debug mode:

const widget = await initLiveChat({
  apiKey: "your-api-key-here",
  debug: true, // Aktifkan debug logging
  onError: (error) => {
    console.error('Widget Error:', error);
    // Kirim error ke monitoring service
    errorReporting.captureException(error);
  }
});

Dukungan Browser

โœ… Didukung Penuh

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+
  • iOS Safari 12+
  • Android Chrome 60+

โš ๏ธ Dukungan Terbatas

  • Internet Explorer (tidak didukung)
  • Chrome < 60 (fallback ke API)
  • Firefox < 55 (fallback ke API)
  • Safari < 12 (fallback ke API)
โ„น๏ธ
Butuh bantuan? Jika masih mengalami masalah, hubungi tim support kami disupport@talky.idatau melalui live chat di dashboard Talky.