npm package: @menphurk/chat-hub
Description: Chat Hub SDK for LINE, Facebook, Instagram, TikTok, Shopee, Lazada.
Latest version: 1.0.2

# Chat Hub SDK

A unified SDK for integrating multiple chat platforms including LINE, Facebook, Instagram, TikTok, Shopee, and Lazada.

## Features

- 🚀 **Multi-platform support**: Connect to 6 different chat platforms through a single interface
- 🔐 **OAuth integration**: Built-in OAuth utilities for token exchange
- 🛡️ **Security**: Secure signature generation for e-commerce platforms
- 📦 **TypeScript support**: Full TypeScript definitions included
- 🎯 **Easy configuration**: Simple setup with platform-specific configurations

## Supported Platforms

- **LINE**: Business messaging
- **Facebook Messenger**: Social media messaging
- **Instagram**: Direct messaging
- **TikTok**: Social commerce messaging
- **Shopee**: E-commerce marketplace messaging
- **Lazada**: E-commerce platform messaging

## Installation

```bash
npm install @menphurk/chat-hub
```

## Quick Start

### Basic Usage

```typescript
import { ChatHub, ChatPlatform } from "@menphurk/chat-hub";

// Initialize with platform configurations
const chatHub = new ChatHub({
  facebookToken: "your-facebook-token",
  instagramToken: "your-instagram-token",
  lineChannelAccessToken: "your-line-channel-access-token",
  tiktokToken: "your-tiktok-token",
  shopee: {
    partnerId: 123456,
    partnerKey: "your-partner-key",
    shopId: 789012,
  },
  lazada: {
    appKey: "your-app-key",
    appSecret: "your-app-secret",
  },
});

// Send a message
await chatHub.sendMessage(
  ChatPlatform.LINE,
  "customer-id",
  "Hello from Chat Hub!"
);
```

### Using Individual Providers

```typescript
import { LineProvider, FacebookProvider } from "@menphurk/chat-hub";

// LINE provider
const lineProvider = new LineProvider("your-line-channel-access-token");
await lineProvider.sendMessage("user-id", "Hello from LINE!");

// Facebook provider
const facebookProvider = new FacebookProvider("your-facebook-token");
await facebookProvider.sendMessage("user-id", "Hello from Facebook!");
```

### OAuth Integration

The SDK provides built-in OAuth utilities to connect with various platforms. This is especially useful for e-commerce platforms like Shopee and Lazada where you need to authorize access to merchant accounts.

#### Complete OAuth Flow Example

```typescript
import {
  oauthAuthorizeUrl,
  exchangeToken,
  ChatHub,
  ChatPlatform,
} from "@menphurk/chat-hub";

// Step 1: Generate OAuth authorization URL
function connectStore(platform: string) {
  const authUrl = oauthAuthorizeUrl({
    platform: platform, // 'shopee', 'lazada', 'facebook', etc.
    clientId: "your-client-id",
    redirectUri: "https://yourapp.com/callback",
    scope: "read write", // platform-specific scopes
    state: "random-state-string", // for security
  });

  // Redirect user to platform's OAuth login
  window.location.href = authUrl;
}

// Step 2: Handle OAuth callback
app.get("/callback/:platform", async (req, res) => {
  const { platform } = req.params;
  const { code, state } = req.query;

  // Verify state parameter for security
  if (state !== expectedState) {
    return res.status(400).json({ error: "Invalid state parameter" });
  }

  try {
    // Step 3: Exchange authorization code for access token
    const tokenData = await exchangeToken({
      platform: platform,
      clientId: "your-client-id",
      clientSecret: "your-client-secret",
      code: code,
      redirectUri: "https://yourapp.com/callback",
    });

    // Step 4: Save tokens to database
    await saveTokens(platform, tokenData);

    res.redirect("/dashboard?connected=" + platform);
  } catch (error) {
    console.error("OAuth error:", error);
    res.redirect("/error?message=connection-failed");
  }
});

// Step 5: Use tokens to send messages
async function initializeChatHub() {
  const tokens = await getStoredTokens();

  const chatHub = new ChatHub({
    shopee: tokens.shopee
      ? {
          partnerId: tokens.shopee.partner_id,
          partnerKey: "your-partner-key",
          shopId: tokens.shopee.shop_id,
        }
      : undefined,
    lazada: tokens.lazada
      ? {
          appKey: "your-app-key",
          appSecret: "your-app-secret",
        }
      : undefined,
    facebookToken: tokens.facebook?.access_token,
    lineChannelAccessToken: tokens.line?.access_token,
  });

  // Now you can send messages
  if (tokens.shopee) {
    await chatHub.sendMessage(
      ChatPlatform.SHOPEE,
      "customer-id",
      "Hello from your Shopee store!"
    );
  }
}
```

#### Platform-specific OAuth URLs

```typescript
// Shopee - Connect to merchant account
const shopeeUrl = oauthAuthorizeUrl({
  platform: "shopee",
  clientId: "your-partner-id", // Partner ID from Shopee
  redirectUri: "https://yourapp.com/callback/shopee",
});

// Lazada - Connect to seller account
const lazadaUrl = oauthAuthorizeUrl({
  platform: "lazada",
  clientId: "your-app-key",
  redirectUri: "https://yourapp.com/callback/lazada",
  scope: "read write",
});

// Facebook - Connect to page
const facebookUrl = oauthAuthorizeUrl({
  platform: "facebook",
  clientId: "your-app-id",
  redirectUri: "https://yourapp.com/callback/facebook",
  scope: "pages_messaging,pages_read_engagement",
});

// LINE - Connect to channel
const lineUrl = oauthAuthorizeUrl({
  platform: "line",
  clientId: "your-channel-id",
  redirectUri: "https://yourapp.com/callback/line",
  scope: "profile openid email",
  responseType: "code",
});
```

#### Token Exchange Response Examples

```typescript
// Shopee token response
{
  "access_token": "shopee_access_token",
  "refresh_token": "shopee_refresh_token",
  "token_type": "Bearer",
  "expires_in": 14400,
  "shop_id": 123456789
}

// Facebook token response
{
  "access_token": "facebook_page_access_token",
  "token_type": "bearer"
}

// LINE token response
{
  "access_token": "line_channel_access_token",
  "expires_in": 2592000,
  "refresh_token": "line_refresh_token",
  "scope": "profile openid email",
  "token_type": "Bearer"
}
```

## Configuration

### OAuth Requirements by Platform

Before using OAuth integration, you need to set up your application with each platform:

#### Shopee

- Register as a Shopee Partner at [Shopee Open Platform](https://open.shopee.com)
- Get your `Partner ID` and `Partner Key`
- Configure callback URL in your app settings

#### Lazada

- Register at [Lazada Open Platform](https://open.lazada.com)
- Get your `App Key` and `App Secret`
- Set up redirect URI in app configuration

#### Facebook/Instagram

- Create a Facebook App at [Facebook Developers](https://developers.facebook.com)
- Add Facebook Login and Instagram Basic Display products
- Configure OAuth redirect URIs

#### LINE

- Create a LINE Login channel at [LINE Developers Console](https://developers.line.biz)
- Get your `Channel ID` and `Channel Secret`
- Set callback URL in channel settings

#### TikTok

- Apply for TikTok for Business API access
- Get your `Client Key` and `Client Secret`
- Configure redirect URI

### Platform-specific Configuration

#### LINE

```typescript
{
  lineChannelAccessToken: "your-line-channel-access-token";
}
```

#### Facebook & Instagram

```typescript
{
  facebookToken: 'your-facebook-page-access-token',
  instagramToken: 'your-instagram-access-token'
}
```

#### TikTok

```typescript
{
  tiktokToken: "your-tiktok-access-token";
}
```

#### Shopee

```typescript
{
  shopee: {
    partnerId: 123456,
    partnerKey: 'your-partner-key',
    shopId: 789012
  }
}
```

#### Lazada

```typescript
{
  lazada: {
    appKey: 'your-app-key',
    appSecret: 'your-app-secret'
  }
}
```

## API Reference

### ChatHub Class

#### Constructor

```typescript
new ChatHub(config: ChatHubConfig)
```

#### Methods

##### `provider(platform: ChatPlatform): ChatProvider`

Get a specific platform provider instance.

##### `sendMessage(platform: ChatPlatform, customerId: string, message: string): Promise<any>`

Send a message through the specified platform.

### ChatPlatform Enum

Available platforms:

- `ChatPlatform.FACEBOOK`
- `ChatPlatform.INSTAGRAM`
- `ChatPlatform.LINE`
- `ChatPlatform.TIKTOK`
- `ChatPlatform.SHOPEE`
- `ChatPlatform.LAZADA`

### Individual Providers

Each provider implements the `ChatProvider` interface:

```typescript
interface ChatProvider {
  sendMessage(customerId: string, message: string): Promise<any>;
}
```

### OAuth Functions

#### `oauthAuthorizeUrl(params: OAuthAuthorizeParams): string`

Generate an OAuth authorization URL for platform connection.

```typescript
interface OAuthAuthorizeParams {
  platform: string; // Platform identifier ('shopee', 'lazada', etc.)
  clientId: string; // Your app's client ID
  redirectUri: string; // Callback URL after authorization
  scope?: string; // Requested permissions
  state?: string; // Security parameter to prevent CSRF
  [key: string]: any; // Additional platform-specific parameters
}
```

#### `exchangeToken(params: OAuthTokenExchangeParams): Promise<any>`

Exchange authorization code for access token.

```typescript
interface OAuthTokenExchangeParams {
  platform: string; // Platform identifier
  clientId: string; // Your app's client ID
  clientSecret: string; // Your app's client secret
  code: string; // Authorization code from callback
  redirectUri: string; // Same redirect URI used in authorization
  [key: string]: any; // Additional platform-specific parameters
}
```

## Error Handling

### Basic Error Handling

```typescript
try {
  await chatHub.sendMessage(ChatPlatform.LINE, "user-id", "Hello!");
} catch (error) {
  if (error.message.includes("not configured")) {
    console.error("Platform not configured in ChatHub");
  } else {
    console.error("Failed to send message:", error);
  }
}
```

### OAuth Error Handling

```typescript
try {
  const tokenData = await exchangeToken({
    platform: "shopee",
    clientId: "your-partner-id",
    clientSecret: "your-partner-key",
    code: authCode,
    redirectUri: "https://yourapp.com/callback",
  });
} catch (error) {
  if (error.response?.status === 400) {
    // Invalid authorization code or expired
    console.error("Invalid or expired authorization code");
  } else if (error.response?.status === 401) {
    // Invalid client credentials
    console.error("Invalid client ID or secret");
  } else if (error.message.includes("Unknown OAuth provider")) {
    // Unsupported platform
    console.error("Platform not supported for OAuth");
  } else {
    console.error("OAuth exchange failed:", error.message);
  }
}
```

### Common OAuth Error Scenarios

- **Invalid authorization code**: Code expired or already used
- **Mismatched redirect URI**: URI doesn't match registered callback
- **Invalid client credentials**: Wrong client ID/secret combination
- **Insufficient permissions**: Missing required scopes
- **Rate limiting**: Too many requests in short period

## TypeScript Support

This package includes full TypeScript definitions. All interfaces and types are exported for use in your TypeScript projects.

```typescript
import type {
  ChatProvider,
  ChatHubConfig,
  OAuthAuthorizeParams,
  OAuthTokenExchangeParams,
} from "@menphurk/chat-hub";

// Example usage with types
const config: ChatHubConfig = {
  lineChannelAccessToken: "your-line-token",
  shopee: {
    partnerId: 123456,
    partnerKey: "your-partner-key",
    shopId: 789012,
  },
};

const oauthParams: OAuthAuthorizeParams = {
  platform: "shopee",
  clientId: "123456",
  redirectUri: "https://yourapp.com/callback",
  state: "secure-random-string",
};
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

For questions and support, please open an issue on the GitHub repository.

---

**Keywords**: chat, sdk, messaging, line, facebook, instagram, tiktok, shopee, lazada, typescript, nodejs