Интеграция Amplitude аналитики на сайт
Amplitude — product analytics платформа. Отличается от Google Analytics тем, что строит поведенческие модели: кто дошёл до покупки, где отвалился, какие фичи используют удержавшиеся пользователи. Ключевые инструменты — Funnels, Retention, Pathfinder, Behavioral Cohorts.
Установка
npm install @amplitude/analytics-browser
// src/analytics/amplitude.ts
import * as amplitude from '@amplitude/analytics-browser';
amplitude.init(import.meta.env.VITE_AMPLITUDE_API_KEY, {
defaultTracking: {
sessions: true,
pageViews: false, // ручной контроль
formInteractions: false,
fileDownloads: true,
},
logLevel: import.meta.env.DEV
? amplitude.Types.LogLevel.Debug
: amplitude.Types.LogLevel.Warn,
flushIntervalMillis: 10000,
flushQueueSize: 30,
serverUrl: undefined, // EU: 'https://api.eu.amplitude.com'
});
export { amplitude };
Для CDN без бандлера:
<script type="text/javascript">
!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[],_iq:{}};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{r.invoked=!0;var n=t.createElement("script");n.type="text/javascript",n.integrity="sha384-PPfHw2ILiMEr3WZDN6DpXDT0H5MkALzORQB9jAbWCEBpI6kU0MXVIRlzEpLDMo0e",n.crossOrigin="anonymous",n.async=!0,n.src="https://cdn.amplitude.com/libs/analytics-browser-2.10.1-min.js.gz",n.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Failed to load SDK")};var s=t.getElementsByTagName("script")[0];s.parentNode.insertBefore(n,s);function v(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}}var o=function(){this._q=[],this._q.push(arguments)};v(o,"add"),v(o,"append"),v(o,"clearAll"),v(o,"prepend"),v(o,"set"),v(o,"setOnce"),v(o,"unset"),v(o,"preInsert"),v(o,"postInsert"),v(o,"remove"),v(o,"getUserProperties");var u=function(){return this._q=[],this};["setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties","setGroups","setGroupProperties","setTime","setLocationId","setReceipt","setReceiptSig","setReceiptType","setUserData"].forEach(function(e){v(u,e)});r.Revenue=u;var l=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","clearUserProperties","setUserProperties","addUserProperties","setOptOut","logEvent","identify","groupIdentify","setGroup","getBrowserType","logRevenue","logRevenueV2","regenerateDeviceId","logEventWithTimestamp","logEventWithGroups","setVersionName","init","removeEventType"].concat(["runQueuedFunctions"]);for(var p=0;p<l.length;p++){var c=l[p];r[c]=function(e){return function(){var t=[e].concat(Array.prototype.slice.call(arguments,0));return r._q.push(t),r}}(c)}e.amplitude=r}}(window,document)}();
amplitude.init('YOUR_API_KEY');
</script>
Трекинг событий
Amplitude использует event-модель с произвольными свойствами. Нейминг событий — Noun Verb или Subject Action:
import { amplitude } from '@/analytics/amplitude';
import { track, Identify, identify, Revenue, revenue } from '@amplitude/analytics-browser';
// Просмотр страницы
track('Page Viewed', {
page_path: window.location.pathname,
page_title: document.title,
page_type: 'product_listing',
});
// Клик по CTA
track('CTA Clicked', {
cta_text: 'Попробовать бесплатно',
cta_position: 'header',
page_section: 'hero',
});
// Заполнение формы
track('Form Completed', {
form_type: 'lead',
fields_filled: ['name', 'email', 'phone'],
time_to_complete_seconds: 45,
});
// Просмотр товара
track('Product Viewed', {
product_id: 'SKU-001',
product_name: 'Professional Plan',
product_category: 'subscription',
price: 2990,
currency: 'RUB',
});
Идентификация и пользовательские свойства
import { Identify, identify, setUserId } from '@amplitude/analytics-browser';
// После логина
function onUserAuthenticated(user: {
id: string;
email: string;
plan: 'free' | 'pro' | 'enterprise';
company?: string;
createdAt: string;
}) {
setUserId(user.id);
const identifyEvent = new Identify();
identifyEvent.set('email', user.email);
identifyEvent.set('plan', user.plan);
identifyEvent.set('company', user.company ?? '');
identifyEvent.setOnce('signup_date', user.createdAt);
identifyEvent.add('login_count', 1);
identify(identifyEvent);
}
// Сброс при логауте
function onUserLoggedOut() {
amplitude.reset(); // очищает userId и deviceId
}
Revenue трекинг
import { Revenue, revenue } from '@amplitude/analytics-browser';
function trackPurchase(order: {
productId: string;
productName: string;
price: number;
quantity: number;
orderId: string;
}) {
const revenueEvent = new Revenue()
.setProductId(order.productId)
.setPrice(order.price)
.setQuantity(order.quantity)
.setRevenue(order.price * order.quantity)
.setRevenueType('purchase')
.setEventProperties({
order_id: order.orderId,
product_name: order.productName,
});
revenue(revenueEvent);
}
Плагин для автотрекинга кликов
Amplitude поддерживает плагины. Можно написать плагин, который автоматически трекает клики по всем элементам с data-track:
// src/analytics/plugins/autotrack.ts
import type { BrowserClient, Plugin } from '@amplitude/analytics-browser';
export const autoTrackPlugin = (): Plugin => ({
name: 'auto-track-plugin',
type: 'enrichment',
setup: async (_config, client: BrowserClient) => {
document.addEventListener('click', (e) => {
const target = (e.target as HTMLElement).closest('[data-track]');
if (!target) return;
const eventName = target.getAttribute('data-track') ?? 'Element Clicked';
const props = target.dataset as Record<string, string>;
client.track(eventName, {
element_text: target.textContent?.trim().substring(0, 100),
element_class: target.className,
...props,
});
});
},
});
// Подключение
amplitude.add(autoTrackPlugin());
Server-side через HTTP API v2
// app/Services/AmplitudeService.php
class AmplitudeService
{
private string $apiKey;
private string $endpoint = 'https://api2.amplitude.com/2/httpapi';
public function __construct()
{
$this->apiKey = config('services.amplitude.api_key');
}
public function track(string $userId, string $eventType, array $eventProperties = []): bool
{
$payload = [
'api_key' => $this->apiKey,
'events' => [[
'user_id' => $userId,
'event_type' => $eventType,
'event_properties' => $eventProperties,
'time' => (int) (microtime(true) * 1000),
'insert_id' => uniqid('srv_', true),
'platform' => 'web',
]],
];
$response = Http::timeout(5)->post($this->endpoint, $payload);
// Amplitude возвращает { "code": 200, "events_ingested": 1, ... }
return $response->ok() && ($response->json('code') === 200);
}
public function trackBatch(array $events): array
{
// Батч до 10 событий за один запрос
$chunks = array_chunk($events, 10);
$results = [];
foreach ($chunks as $chunk) {
$response = Http::timeout(10)->post($this->endpoint, [
'api_key' => $this->apiKey,
'events' => $chunk,
]);
$results[] = $response->json();
}
return $results;
}
}
Cohorts API для экспорта данных
Amplitude позволяет экспортировать когорты пользователей в CRM или email-систему:
# Получить список когорт
curl -X GET 'https://amplitude.com/api/3/cohorts' \
-u 'API_KEY:SECRET_KEY'
# Экспортировать когорту (асинхронно)
curl -X GET 'https://amplitude.com/api/5/cohorts/export/download?id=COHORT_ID&props=1' \
-u 'API_KEY:SECRET_KEY' \
--output cohort.csv
Настройка Session Replay
Amplitude Session Replay пишет DOM-снапшоты без захвата личных данных:
import { sessionReplayPlugin } from '@amplitude/plugin-session-replay-browser';
amplitude.add(sessionReplayPlugin({
sampleRate: 0.1, // 10% сессий
privacyConfig: {
blockSelector: ['[data-private]', 'input[type="password"]', '.sensitive'],
defaultBlockLevel: 'medium', // скрывает текст инпутов
},
}));
Сроки
Базовая установка с ключевыми событиями — 1 день. Полная настройка identify, revenue, плагинов — 2–3 дня. Server-side интеграция и настройка когорт — ещё 1–2 дня.







