## REST Endpoint Integration

Connect your backend service to Trulience avatars by implementing a REST endpoint that handles three types of events:

- Joining end-users to conversations
- Sending messages
- Disconnecting end-users from conversations

### How It Works

When you configure a Trulience avatar with your REST Endpoint URL and API key, our system will send HTTP POST requests to your endpoint for each end-user interaction:

1. **User Joins** → We send a `LOGIN` event to your endpoint
2. **User Sends Message** → We send a `CHAT` event and expect a response for the avatar to speak. You may return an empty string if you have finished processing the request but do not want the avatar to say anything yet.
3. **User Disconnects** → We send a `LOGOUT` event to your endpoint

Additionally, your REST endpoint can proactively send messages by making requests to our callback URL.

### Authentication & Configuration

Set up your integration by providing two details in your Trulience dashboard:

- **REST Endpoint URL** - This is where events will be sent (e.g. `https://your-api.com/trulience`)
- **REST Endpoint API Key** - This will be included in the `Authorization: Bearer` header when calling your endpoint

All communication uses JSON format over HTTPS.

### Event Types

#### User Joins (LOGIN Event)

When a user starts a conversation with your avatar, this event is sent to your endpoint to establish the session:

**Request to your endpoint:**

```json
// POST https://your-api.com/trulience
// Authorization: Bearer your-api-key-here

{
    "action": "LOGIN",
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "userId": "784567545747587",
    "locale": "en-US",
    "lastSeen": "2024-03-15 14:30:25",
    "authToken": "4d665469-2f5c-4b12-ad5f-8e919da592cb",
    "callbackUrl": "https://trulience.com/tglisten"
}
```

**Your endpoint response:**

```json
{
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "status": "OK",
    "statusMessage": "Session Created"
}
```

<span><strong>Key Points:</strong></span>

- Store the `sessionId` as you will need it for all subsequent requests
- The `authToken` is used when you want to send messages back to our gateway
- The `callbackUrl` is where you send messages back to

#### User Sends Message (CHAT Event)

When a user speaks to your avatar, we send their message and wait for your response.

**Request to your endpoint:**

```json
// POST https://your-api.com/trulience
// Authorization: Bearer your-api-key-here

{
    "action": "CHAT",
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "message": "What's the weather like today?"
}
```

**Your endpoint response:**
```json
{
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "reply": "It's currently 72°F and sunny in your area!",
    "status": "OK",
    "statusMessage": "Reply Sent"
}
```

<span><strong>Key Points:</strong></span>

- Your `reply` is what the avatar will speak aloud to the user
- You can use plain text or [SSML](/docs/trulience-platform/ssml) for enhanced speech control
- The response should be fast to maintain conversation flow

#### User Disconnects (LOGOUT Event)

When a user ends the conversation or gets disconnected, we notify your endpoint to clean up the session.

**Request to your endpoint:**

```json
// POST https://your-api.com/trulience
// Authorization: Bearer your-api-key-here

{
    "action": "LOGOUT",
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c"
}
```

**Your endpoint response:**
```json
{
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "status": "OK",
    "statusMessage": "Session Ended"
}
```

### Sending Messages

Your endpoint can initiate messages to users proactively by posting to our callback URL and including the session's auth token.

**Request to Trulience Gateway:**
```json
// POST https://trulience.com/tglisten
// Authorization: Bearer 4d665469-2f5c-4b12-ad5f-8e919da592cb

{
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "message": "I have an update for you!"
}
```

**Response from Trulience Gateway:**
```json
{
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "status": "OK",
    "statusMessage": "Message Delivered"
}
```

<span><strong>Use Cases:</strong></span>

- Send notifications or alerts
- Provide updates on long-running processes
- Initiate new conversation topics

### Simple Implementation Example

Here's a basic Node.js/Express endpoint that handles all three event types:

```javascript
const express = require('express');
const app = express();
app.use(express.json());

// Store active sessions
const sessions = new Map();

app.post('/trulience', (req, res) => {
    const { action, sessionId, userId, message, authToken, callbackUrl } = req.body;
    
    switch (action) {
        case 'LOGIN':
            // Store session info
            sessions.set(sessionId, { 
                userId, 
                authToken, 
                callbackUrl,
                joinedAt: new Date()
            });
            
            res.json({
                sessionId,
                status: 'OK',
                statusMessage: 'Welcome! How can I help you today?'
            });
            break;
            
        case 'CHAT':
            // Process user message and generate response
            const reply = generateResponse(message, sessionId);
            
            res.json({
                sessionId,
                reply,
                status: 'OK',
                statusMessage: 'Reply Sent'
            });
            break;
            
        case 'LOGOUT':
            // Clean up session
            sessions.delete(sessionId);
            
            res.json({
                sessionId,
                status: 'OK',
                statusMessage: 'Goodbye!'
            });
            break;
    }
});

function generateResponse(userMessage, sessionId) {
    // Your business logic here
    // This could integrate with AI services, databases, etc.
    return `I received your message: "${userMessage}". How else can I help?`;
}
```

### Parameter Reference

#### LOGIN Event Parameters

Parameters contained in the LOGIN request:

| Parameter | Required | Description |
|-----------|----------|-------------|
| `action` | Yes | Always "LOGIN" |
| `sessionId` | Yes | Unique session identifier - store this for future requests |
| `userId` | Yes | Unique user identifier |
| `locale` | Yes | User's locale (e.g., "en-US") |
| `lastSeen` | Yes | User's last login timestamp |
| `authToken` | Yes | Use this token when sending proactive messages |
| `callbackUrl` | Yes | URL for sending messages back to Trulience |
| `accessToken` | No | OAuth token if applicable |
| `customString` | No | Custom data from auth request |
| `jwtToken` | No | JWT token from auth request |

#### CHAT Event Parameters

Parameters contained in the CHAT request:

| Parameter | Required | Description |
|-----------|----------|-------------|
| `action` | Yes | Always "CHAT" |
| `sessionId` | Yes | Session identifier from LOGIN event |
| `message` | Yes | User's spoken message (text or SSML) |

#### CHAT Response Parameters

Parameters contained in the CHAT json response:

| Parameter | Required | Description |
|-----------|----------|-------------|
| `sessionId` | Yes | Echo back the session ID |
| `reply` | Yes | Avatar's response (text or [SSML](/docs/trulience-platform/ssml)) |
| `status` | Yes | "OK" for success |
| `statusMessage` | Yes | Human-readable status description |

#### LOGOUT Event Parameters

Parameters contained in the LOGOUT json request:

| Parameter | Required | Description |
|-----------|----------|-------------|
| `action` | Yes | Always "LOGOUT" |
| `sessionId` | Yes | Session identifier to clean up |

### Best Practices

- **Store session data**: Keep track of `sessionId`, `authToken` and `callbackUrl` for each active session
- **Respond quickly**: Users expect natural conversational flow, so aim for sub-second response times
- **Handle cleanup**: Use LOGOUT events to free up resources and clear session data
- **Use meaningful responses**: Your `statusMessage` fields help with debugging integration issues
- **Test thoroughly**: Verify your endpoint handles all three event types correctly

### Testing Your Integration

1. Set up your endpoint to handle POST requests with the three action types
2. Configure your avatar in the Trulience dashboard with your endpoint URL and API key
3. Start a conversation with your avatar to trigger LOGIN and CHAT events
4. End the conversation to trigger the LOGOUT event
5. Monitor your logs to ensure all events are being received and handled correctly


## Sending Custom Payloads
You might wish to send custom JSON payloads between your REST endpoint and your client side application. This can be achieved by serialising your data and sending it inside of an [SSML tag](/docs/trulience-platform/ssml), then deserialising it on the other end.

### Sending Custom Payloads from Client to REST Endpoint
You can send custom payloads to the backend by using custom tags that are not prefixed with `<trl-`.

```javascript
const customData = { name: "ABC", id: 123 };
trulienceObj.sendMessage(`<custom-json json='${JSON.stringify(customData)}' />`);
``` 
 
### Sending Custom Payloads from REST Endpoint to Client
When sending custom payloads in the opposite direction you should register a custom tag and listen for the event dispatched by it.
1. [Register a Custom Tag](/docs/trulience-platform/ssml?tab=Client%20SSML#trl-register-tag) when your avatar loads (required for `<trl-` prefixed tags)

```javascript
trulienceObj.sendMessage("<trl-register-tag ssml-tag='trl-custom-rest-json' event='custom-rest-json' />");
```

2. Listen for Events
Use standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener" target="_blank">DOM event listeners</a> to capture the custom event:

```javascript
document.addEventListener(
    'custom-rest-json', 
    (e) => {    
        console.warn('Received event custom-rest-json:', e);
        // parse the data and use it in your application
    }
);
```

### Why not use `<trl-custom-rest-json />` both ways?
At present we intentionally filter any tags beginning with the `<trl-` prefix on messages sent to the REST endpoint (or LLMs). This constraint may be relaxed in the future, but for now a non-trl tag like `<custom-json />` is the way to go when sending payloads from the Client to a REST endpoint.

### Sending Data from Backend to Client
To send custom payloads to the client from the backend, make a POST request to Trulience’s `https://trulience.com/tglisten` endpoint received during LOGIN:

```json
// POST https://trulience.com/tglisten
// Authorization: Bearer 4d665469-2f5c-4b12-ad5f-8e919da592cb

{
    "sessionId": "53dccc58-417e-4ae7-9c7f-5d22c1b77a3c",
    "message": "<trl-custom-rest-json json='{\"name\": \"ABC\", \"id\": 12}'/>"
}
```