# Overview

Telegram Mini Apps is an SDK and API that turns your Telegram Mini App into a source of valuable data. With this tool, you get instant access to key metrics that help you understand how users interact with your application and what steps need to be taken to optimize it. It supports off-chain events and on-chain events from TON Connect SDK.

### &#x20;⚠️ Disclaimer

> The library does not collect or store any private user data. It tracks app launches, TON Connect interactions, and GDPR-compliant events in an anonymous format. This data is used solely for to rank applications in the catalog based on their performance and Streaks.

***

### Navigation:

* [Overview](/)
* SDK installation:
  * [preparations](/sdk/preparations)
  * [via \<script> tag](/sdk/installation-via-less-than-script-greater-than-tag)
  * [via NPM package](/sdk/installation-via-npm-package)
* [API docs](/api/endpoints)
* [Supported events](/supported-events)
* [Bot](/managing-integration)
* [Demo app](https://github.com/Dimitreee/demo-dapp-with-analytics)


# Preparations

Preparations before connection

### 1. Connect the TON Connect SDK

Web3 events for the Telegram Mini Apps Analytics SDK are supported by the [`@tonconnect/ui`](https://www.npmjs.com/package/@tonconnect/ui) and [`@tonconnect/ui-react`](https://www.npmjs.com/package/@tonconnect/ui-react) libraries since version 2.0.3, [`@tonconnect/sdk`](https://www.npmjs.com/package/@tonconnect/sdk) since version 3.0.3.

[Read more about TON Connect integration](https://github.com/ton-connect)

Don't worry if your app doesn't use TON Connect, the analytics SDK will still work and collect non-Web3 events.

### 2.  Get the token with TON Builders

Register your project on [TON Builders](https://builders.ton.org) and go to the Analytics tab.

![](https://storage.googleapis.com/ton-strapi/Empty_49d500d906/Empty_49d500d906.png)

Enter your Telegram Bot URL and mini app domain to receive an **API key** for SDK initialization. You can also manage your existing keys from the same section. Enter your Telegram Bot URL and mini app domain to receive a token for SDK initialization.

### 3. Initialize SDK

Now you can initialize the SDK in your application. There are two ways to do this:

* via \<script> tag (See [Installation via \<script> tag](/sdk/installation-via-less-than-script-greater-than-tag) page)
* via NPM package (See [Installation via NPM package](/sdk/installation-via-npm-package) page)

***

### Navigation:

* [Overview](/)
* SDK installation:
  * [preparations](/sdk/preparations)
  * [via \<script> tag](/sdk/installation-via-less-than-script-greater-than-tag)
  * [via NPM package](/sdk/installation-via-npm-package)
* [API docs](/api/endpoints)
* [Supported events](/supported-events)
* [Bot](/managing-integration)
* [Demo app](https://github.com/Dimitreee/demo-dapp-with-analytics)


# Installation via \<script> tag

How to install and use via \<script> tag

## How to install it?

**1. Add Telegram Mini Apps Analytics to your project**

Include the Telegram Mini Apps Analytics script in the header of your HTML document. This script will allow you to track and analyze user interactions effectively.

```html
<!-- Add Telegram Analytics script to HTML head -->
<script 
    async 
    src="https://tganalytics.xyz/index.js" 
    onload="initAnalytics()" 
    type="text/javascript"
></script>
```

Alternative solution (not recommended)

```html
<!-- Add Telegram Analytics script to HTML head -->
<script
    async 
    src="https://unpkg.com/@telegram-apps/analytics@latest/dist/index.js"
    onload="initAnalytics()"  
    type="text/javascript"
></script>
```

#### 2. Initialize the **Telegram Mini Apps Analytics** SDK

Once you have your unique access token and analytics identifier (if not, see [Preparations](/sdk/preparations) page), you can initialize the Telegram Analytics SDK in your code. This step is crucial for enabling the tracking of events without repeatedly transferring the token.

```html
<script>
    function initAnalytics() {
      window.telegramAnalytics.init({
        token: 'YOUR_TOKEN',
        appName: 'ANALYTICS_IDENTIFIER',
      });
    }
</script>
```

### Supported Events

After initializing the **Telegram Analytics**, you are all set to transfer the data, gain insights, and improve user engagement. (99% of them will be tracked **automatically** without manual control)

[Read more about supported events](/supported-events)

***

### Navigation:

* [Overview](/)
* SDK installation:
  * [preparations](/sdk/preparations)
  * [via \<script> tag](/sdk/installation-via-less-than-script-greater-than-tag)
  * [via NPM package](/sdk/installation-via-npm-package)
* [API docs](/api/endpoints)
* [Supported events](/supported-events)
* [Bot](/managing-integration)
* [Demo app](https://github.com/Dimitreee/demo-dapp-with-analytics)


# Installation via NPM package

How to install and use via \<script> tag

## How to install it?

**1. Install the NPM package in  your project**

```shell
npm install @telegram-apps/analytics
```

```shell
yarn add @telegram-apps/analytics
```

```sh
pnpm add @telegram-apps/analytics
```

**2. Add Telegram Mini Apps Analytics in code**

Once you have your unique access token (if not, see [Preparations](/sdk/preparations) page) and install NPM package, you can initialize the Telegram Analytics SDK in your code. To ensure that all events are collected correctly, you must initialize the SDK before the application starts rendering. For example, in react applications, before calling the `render()` function

```jsx
import TelegramAnalytics from '@telegram-apps/analytics'

TelegramAnalytics.init({
    token: 'YOUR_TOKEN',
    appName: 'ANALYTICS_IDENTIFIER',
});
```

### Supported Events

After initializing the **Telegram Analytics**, you are all set to transfer the data, gain insights, and improve user engagement. (99% of them will be tracked **automatically** without manual control)

[Read more about supported events](/supported-events)

***

### Navigation:

* [Overview](/)
* SDK installation:
  * [preparations](/sdk/preparations)
  * [via \<script> tag](/sdk/installation-via-less-than-script-greater-than-tag)
  * [via NPM package](/sdk/installation-via-npm-package)
* [API docs](/api/endpoints)
* [Supported events](/supported-events)
* [Bot](/managing-integration)
* [Demo app](https://github.com/Dimitreee/demo-dapp-with-analytics)


# Endpoints

Here you can view information about existing endpoints and how to make requests for them. URL for requests: https\://tganalytics.xyz

## POST /events[^1]

This request is needed to record an event in the database

### Body

The request body may contain an array rather than a single event. The main thing is that all events in the array satisfy the scheme below

#### <mark style="color:red;">Required</mark>

* `user_id`
  * Type: <mark style="color:orange;">number</mark>
  * Description: unique identifier for the user.
* `event_name`
  * Type: <mark style="color:orange;">string</mark>
  * Description: the name of the event from the [supported](/supported-events)
* `session_id`
  * Type: <mark style="color:orange;">string</mark> **(must be** [**UUID**](https://github.com/Telegram-Mini-Apps/analytics/blob/master/src/utils/generateUUID.ts)**)**
  * Description: session identifier for tracking user sessions
* `app_name`
  * Type: <mark style="color:orange;">string</mark>&#x20;
  * Description: the name of the application that you specified when creating the token

#### <mark style="color:green;">Optional</mark>

* `is_premium`
  * Type: <mark style="color:orange;">boolean</mark>
  * Description: if the user has a premium account, by default - <mark style="color:orange;">false</mark>
* `is_success`
  * Type: <mark style="color:orange;">boolean</mark>
  * Description: indicates whether a wallet is connected or the transaction was successful, by default - <mark style="color:orange;">false</mark>
* `error_message`
  * Type: <mark style="color:orange;">string</mark>
  * Description: error message if the wallet connection or transaction is unsuccessful
* `error_code`
  * Type: <mark style="color:orange;">number</mark>
  * Description: error code if the wallet connection or transaction is unsuccessful
* `wallet_address`
  * Type: <mark style="color:orange;">string</mark>
  * Description: wallet address involved in the event
* `wallet_type`
  * Type: <mark style="color:orange;">string</mark>
  * Description: type of the wallet
* `wallet_version`
  * Type: <mark style="color:orange;">string</mark>
  * Description: version of the wallet software
* `auth_type`
  * Type: <mark style="color:orange;">enum</mark>(0 - <mark style="color:green;">'ton\_addr'</mark>, 1 - <mark style="color:green;">'ton\_proof'</mark>)
  * Description: type of authorization used
* `valid_until`&#x20;
  * Type: <mark style="color:orange;">string</mark>
  * Description: timestamp until when a transaction offer is valid
* `from`
  * Type: <mark style="color:orange;">string</mark>
  * Description: wallet address initiating the transaction
* `messages`&#x20;
  * Type: <mark style="color:orange;">{ address: string; amount: string }\[]</mark>
  * Description: list of transactions {to, amount} involved in the event
* `custom_data`
  * Type: <mark style="color:orange;">object</mark>
  * Description: object to store custom event details as needed
* `client_timestamp`
  * Type: <mark style="color:orange;">string</mark>
  * Description: the time when the event occurred on the clent
* `platform`
  * Type: <mark style="color:orange;">string</mark>
  * Description: the platform from which the MiniApp was opened
* `locale`
  * Type: <mark style="color:orange;">string</mark>
  * Description: user language code
* `start_param`
  * Type: <mark style="color:orange;">string</mark>
  * Description: tgWebAppStartParam
* `url_referer`
  * Type: <mark style="color:orange;">string</mark>
  * Description: the URL of the web application from which the request was sent
* `scope`
  * Type: <mark style="color:orange;">string</mark>
  * Description: event scope

### Request Body Example\`s:

```json
[
  {
    "event_name": "app-init",
    "session_id": "10c574d9-6d2c-4e6d-a141-ce6da141ce6d",
    "user_id": 111111111,
    "app_name": "docs",
    "is_premium": true,
    "platform": "tdesktop",
    "locale": "en",
    "client_timestamp": "1743503599534"
  }
]
```

```json
[
  {
    "event_name": "connection-started",
    "custom_data": {
      "ton_connect_sdk_lib": "3.0.3",
      "ton_connect_ui_lib": "2.0.5"
    },
    "session_id": "10c574d9-6d2c-4e6d-a141-ce6da141ce6d",
    "user_id": 111111111,
    "app_name": "docs",
    "is_premium": true,
    "platform": "tdesktop",
    "locale": "en",
    "client_timestamp": "1743503647541"
  }
```

```json
[
  {
    "event_name": "connection-error",
    "is_success": false,
    "error_message": "Connection was cancelled",
    "error_code": null,
    "custom_data": {
      "ton_connect_sdk_lib": "3.0.3",
      "ton_connect_ui_lib": "2.0.5"
    },
    "session_id": "10c574d9-6d2c-4e6d-a141-ce6da141ce6d",
    "user_id": 111111111,
    "app_name": "docs",
    "is_premium": true,
    "platform": "tdesktop",
    "locale": "en",
    "client_timestamp": "1743503683701"
  }
]
```

### Headers

Instead of YOUR\_TOKEN, you need to specify the token received using the [bot](/managing-integration)

```json
{
    "TGA-Auth-Token": "YOUR_TOKEN",
    "Content-Type": "application/json"
}
```

### Responses

#### <mark style="background-color:green;">HTTP201</mark>

* Description: the event has been successfully recorded
* Content:&#x20;

<pre class="language-json"><code class="lang-json"><strong>{
</strong>    "message": "Success record."
}
</code></pre>

#### <mark style="background-color:orange;">HTTP400</mark>

* Description: the event was not recorded due to server issues
* Content:&#x20;

```json
{
    "message": "Failed to record"
}
```

#### <mark style="background-color:orange;">HTTP400</mark>

* Description:  the token was entered incorrectly or in the wrong format
* Content:

```json
{
    "message": "The token is not specified in the headers or is specified incorrectly."
}
```

#### <mark style="background-color:orange;">HTTP400</mark>

* Description:  the entered token is invalid (was not created through a Data Chief bot)
* Content:

```json
{
    "message": "Token is invalid."
}
```

#### <mark style="background-color:orange;">HTTP400</mark>

* Description: the request body contains the application name that does not match the token
* Content:

```json
{
    "message": "Invalid app_name is specified."
}
```

#### <mark style="background-color:orange;">HTTP400</mark>

* Description: the body specified in the request was not validated (for example, the type of one of the fields does not match)
* Content:

```json
{
    "status": 400,
    "message": "VALIDATION_MISMATCH_REPORT"
}
```

#### <mark style="background-color:orange;">HTTP403</mark>

* Description: an attempt to use the API on a domain name that does not match the token
* Content:

```json
{
    "message": "The domain name does not match."
}
```

#### <mark style="background-color:orange;">HTTP429</mark>

* Description: too many requests from the client in a certain amount of time
* Content:&#x20;

```json
{
    "message": "Too many requests. Try again later."
}
```

[^1]: <https://tganalytics.xyz/events>


# Supported events

Events that can be tracked via the SDK and API

> Events from [TON Connect](https://docs.ton.org/develop/dapps/ton-connect/overview) will be sent only if `@tonconnect/ui-react@2.0.3` or `@tonconnect/ui@2.0.3` or  `@tonconnect/sdk@3.0.3`  and higher versions packages are used

<table data-full-width="false"><thead><tr><th width="341">event_name</th><th width="195">description</th><th data-type="checkbox">TON Connect required</th><th data-hidden></th></tr></thead><tbody><tr><td><code>app-init</code></td><td>connection attempts and their initiation</td><td>false</td><td></td></tr><tr><td><code>app-hide</code></td><td>hiding the app from the screen</td><td>false</td><td></td></tr><tr><td><code>custom-event</code></td><td>the event specified by the user</td><td>false</td><td></td></tr><tr><td><code>connection-started</code></td><td>the user starts connecting the wallet</td><td>true</td><td></td></tr><tr><td><code>connection-completed</code></td><td>successful connection to a wallet</td><td>true</td><td></td></tr><tr><td><code>connection-error</code></td><td>errors in connection specifying reasons (e.g., user cancelled)</td><td>true</td><td></td></tr><tr><td><code>connection-restoring-completed</code></td><td>the connection was restored successfully</td><td>true</td><td></td></tr><tr><td><code>connection-restoring-error</code></td><td>connection restoration failed</td><td>true</td><td></td></tr><tr><td><code>transaction-sent-for-signature</code></td><td>the user submits the transaction for signature</td><td>true</td><td></td></tr><tr><td><code>transaction-signed</code></td><td>the user successfully signs the transaction</td><td>true</td><td></td></tr><tr><td><code>transaction-signing-failed</code></td><td>the user cancels the transaction signature or an error occurs during the signing process</td><td>true</td><td></td></tr><tr><td><code>disconnection</code></td><td>user-initiated disconnection events, specifying scope (dapp or wallet)</td><td>true</td><td></td></tr></tbody></table>


# Managing integration

[TON Builders](https://builders.ton.org) helps you to manage your SDK keys and participate in various support programs from TON Foundation.

Register your project and go to the **Analytics** tab.

![](https://storage.googleapis.com/ton-strapi/Empty_49d500d906/Empty_49d500d906.png)

Enter your Telegram Bot URL and mini app domain to receive an **API key** for SDK initialization. You can also manage your existing keys from the same section. Enter your Telegram Bot URL and mini app domain to receive a token for SDK initialization.


# How can I check the integration status of the SDK?

How to check intergration of analytics

## 1. Using a bot

After completing the integration process using the steps described [here](/sdk/installation-via-less-than-script-greater-than-tag), the bot will display the time of the last recorded event in our database. If it shows something like "one minute ago," this means that everything is working correctly.

<figure><img src="/files/O2akZkgA6soP63RhHhmR" alt=""><figcaption></figcaption></figure>

## 2. Using DevTools

### Desktop version

Go to Telegram settings, then to Advanced Settings, and then to Experimental Settings. Toggle on the "**Enable webview inspectin**g" function.

<figure><img src="/files/LwMJPlimuImjSFRxdqaH" alt=""><figcaption></figcaption></figure>

Next, open your application and right-click to open the developer console. In the Network section, you should see the SDK script (index.js) loading and sending events. If this is not observed, try refreshing the application without closing TMA.

<figure><img src="/files/eQlSkLwvmTeyubzLKMhe" alt=""><figcaption></figcaption></figure>

### Web version

Go to [Telegram's web version](https://web.telegram.org/), open the developer tools, go to the network section, open your TMA and filter queries by 'tganalytics.xyz'. You'll see the SDK being loaded (index.js) and events being sent afterward.

<figure><img src="/files/xVhUd74rOqj1K4zZRpPN" alt=""><figcaption></figcaption></figure>


