> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vambe.me/llms.txt
> Use this file to discover all available pages before exploring further.

# Add metadata for a webchat contact

> Add metadata for a webchat contact

<Note>
  **Webchat Contacts Only**: This endpoint is specifically for contacts from
  your web chat widget. For other channels, use [POST /api/public/contact/
  {aiContactId}/update-metadata](/reference/contact/update-contact-metadata).
</Note>

## Overview

Add or update metadata for a webchat contact using their external user ID. This endpoint is designed specifically for web chat widget integrations where you may have your own user identification system.

Unlike the general metadata endpoint, this one identifies contacts by your `externalUserId` rather than the Vambe contact ID.

## Use Cases

* **User Profile Enrichment**: Add user data from your system to webchat contacts
* **Session Data**: Store information about user sessions and interactions
* **External System Sync**: Sync user data from your database to Vambe
* **Custom Tracking**: Add custom tracking fields for webchat visitors
* **User Identification**: Link webchat conversations to your user IDs

## Authentication

This endpoint requires authentication using an API key. Include your API key in the request header:

```
x-api-key: your_api_key_here
```

## Request Body

| Field            | Type   | Required | Description                                 |
| ---------------- | ------ | -------- | ------------------------------------------- |
| `externalUserId` | string | Yes      | Your unique identifier for the webchat user |
| `metadata`       | object | Yes      | Key-value pairs of metadata to add/update   |

<Warning>
  **External User ID**: This must match the `externalUserId` you provided when
  initializing the webchat widget or creating the contact.
</Warning>

## Response Structure

Returns the updated contact metadata.

## Example Request

```bash theme={null}
curl --request POST \
  'https://api.vambe.me/api/public/webchat/contact/add-metadata' \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: your_api_key_here' \
  --data-raw '{
    "externalUserId": "user-12345",
    "metadata": {
      "subscription_tier": "premium",
      "account_status": "active",
      "lifetime_value": "5000",
      "registration_date": "2024-01-15",
      "preferred_language": "es",
      "location": "Santiago, Chile"
    }
  }'
```

## Example Response

```json theme={null}
{
  "success": true,
  "updated_fields": 6
}
```

## Common Use Cases

### 1. Add User Profile Data

```javascript theme={null}
const enrichWebchatContact = async (externalUserId, userProfile) => {
  const response = await fetch(
    'https://api.vambe.me/api/public/webchat/contact/add-metadata',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify({
        externalUserId: externalUserId,
        metadata: {
          user_name: userProfile.name,
          email: userProfile.email,
          account_type: userProfile.accountType,
          member_since: userProfile.joinDate,
          total_purchases: userProfile.purchaseCount.toString(),
        },
      }),
    },
  );

  const result = await response.json();
  console.log('Webchat contact enriched with user profile');

  return result;
};
```

### 2. Track Session Information

```javascript theme={null}
const trackWebchatSession = async (externalUserId, sessionData) => {
  const response = await fetch(
    'https://api.vambe.me/api/public/webchat/contact/add-metadata',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify({
        externalUserId: externalUserId,
        metadata: {
          session_start: sessionData.startTime,
          page_views: sessionData.pageViews.toString(),
          time_on_site: sessionData.duration.toString(),
          referrer: sessionData.referrer,
          device_type: sessionData.deviceType,
          browser: sessionData.browser,
        },
      }),
    },
  );

  return await response.json();
};
```

### 3. Sync from Your Database

```javascript theme={null}
const syncUserDataToWebchat = async (userId) => {
  // Get user from your database
  const user = await yourDatabase.getUserById(userId);

  // Sync to Vambe webchat contact
  const response = await fetch(
    'https://api.vambe.me/api/public/webchat/contact/add-metadata',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify({
        externalUserId: user.id,
        metadata: {
          full_name: user.fullName,
          company: user.company,
          role: user.role,
          industry: user.industry,
          company_size: user.companySize,
          phone: user.phone,
          country: user.country,
        },
      }),
    },
  );

  console.log('User data synced to webchat contact');

  return await response.json();
};
```

## Webchat External User ID

The `externalUserId` is typically set when:

1. **Widget Initialization**: Passed when initializing the webchat widget
2. **User Login**: Set when user authenticates on your website
3. **Cookie/Session**: Tracked via browser session or cookie

Example webchat initialization:

```javascript theme={null}
VambeChat.init({
  channelId: 'your-channel-id',
  externalUserId: 'user-12345', // Your user ID
  // ...
});
```

## Metadata Processing

* **Unstructured Data**: Metadata is processed with AI
* **Field Matching**: Automatically maps to custom field definitions
* **All Fields Updated**: Uses `editAllFields: true` mode
* **Flexible Schema**: Accept any key-value pairs

## Error Responses

| Status Code | Description                                     |
| ----------- | ----------------------------------------------- |
| 400         | Bad Request - Invalid metadata format           |
| 401         | Unauthorized - Invalid or missing API key       |
| 404         | Not Found - Contact not found with that user ID |
| 500         | Internal Server Error - Something went wrong    |

## Important Notes

* **Webchat Only**: This endpoint only works for webchat contacts
* **External User ID Required**: Must match the ID used in webchat widget
* **Contact Must Exist**: The webchat contact must already exist
* **Organization Scoped**: Contact must belong to your organization
* **AI Processing**: Metadata is processed with AI for field extraction

## For Other Channels

If you need to update metadata for contacts from other channels (WhatsApp, Instagram, etc.), use the general metadata endpoint:

**General Metadata Endpoint**:

```
POST /api/public/contact/{aiContactId}/update-metadata
```

[View Documentation](/reference/contact/update-contact-metadata)

## Related Endpoints

* [POST /api/public/contact/{aiContactId}/update-metadata](/reference/contact/update-contact-metadata) - General metadata update (all channels)
* [GET /api/public/contact/{aiContactId}/info](/reference/contact/get-info-of-an-ai-contact) - Get contact info including metadata
* [POST /api/public/customer/upsert/info](/reference/customer/upsert-customer-info) - Create/update contacts with metadata

## Webchat vs General Metadata

| Feature                | Webchat Metadata (This)  | General Metadata         |
| ---------------------- | ------------------------ | ------------------------ |
| **Identifier**         | externalUserId (your ID) | aiContactId (Vambe UUID) |
| **Channel**            | Webchat only             | All channels             |
| **Use When**           | Have external user ID    | Have Vambe contact ID    |
| **Widget Integration** | ✅ Perfect for widgets    | ❌ Need contact ID lookup |


## OpenAPI

````yaml post /api/public/webchat/contact/add-metadata
openapi: 3.0.0
info:
  title: Vambe AI API
  description: Vambe AI documentation
  version: '1.0'
  contact: {}
servers:
  - url: https://api.vambe.me
    description: Production Server
security: []
tags:
  - name: Vambe AI
    description: ''
paths:
  /api/public/webchat/contact/add-metadata:
    post:
      tags:
        - Webchat contact
      summary: Add metadata for a webchat contact
      description: Add metadata for a webchat contact
      operationId: PublicWebchatContactController_addMetadata
      parameters:
        - name: x-api-key
          in: header
          description: API key needed to authorize the request
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                metadata:
                  type: object
                externalUserId:
                  type: string
      responses:
        '201':
          description: Message sent successfully.
        '400':
          description: Bad request.
        '401':
          description: Unauthorized.

````