Skip to main content

Сервисы уведомлений

Интеграция с различными сервисами для отправки уведомлений пользователям маркетплейса.

Email сервисы

Resend

Современный сервис для транзакционных email рассылок.

Настройка Resend

interface ResendConfig {
api_key: string;
from_email: string;
from_name: string;
reply_to?: string;
webhook_secret?: string;
}

Отправка email

import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

await resend.emails.send({
from: 'noreply@marketplace.com',
to: userEmail,
subject: 'Подтверждение заказа',
html: orderConfirmationTemplate,
tags: [
{ name: 'category', value: 'transactional' },
{ name: 'order_id', value: orderId }
]
});

SendGrid

Масштабируемая платформа для email рассылок.

Конфигурация SendGrid

interface SendGridConfig {
api_key: string;
sender_email: string;
sender_name: string;
template_engine: 'handlebars' | 'dynamic';
tracking: TrackingSettings;
}

interface TrackingSettings {
click_tracking: boolean;
open_tracking: boolean;
subscription_tracking: boolean;
ganalytics: boolean;
}

Динамические шаблоны

const msg = {
to: recipient.email,
from: 'orders@marketplace.com',
templateId: 'd-xyz123',
dynamicTemplateData: {
order_number: order.number,
customer_name: customer.name,
items: order.items,
total: order.total
}
};

await sgMail.send(msg);

Mailgun

Мощный API для отправки email.

Настройка Mailgun

interface MailgunConfig {
api_key: string;
domain: string;
region: 'us' | 'eu';
webhook_signing_key: string;
}

SMS сервисы

Twilio

Ведущая платформа для SMS коммуникаций.

Конфигурация Twilio

interface TwilioConfig {
account_sid: string;
auth_token: string;
phone_number: string;
messaging_service_sid?: string;
}

Отправка SMS

import twilio from 'twilio';

const client = twilio(accountSid, authToken);

await client.messages.create({
body: `Ваш заказ #${orderNumber} готов к получению!`,
from: '+1234567890',
to: customer.phone,
statusCallback: 'https://api.marketplace.com/webhooks/sms-status'
});

СМС Центр (SMSC)

Российский сервис SMS рассылок.

Настройка SMSC

interface SMSCConfig {
login: string;
password: string;
sender: string;
charset: 'utf-8' | 'windows-1251';
}

Массовая рассылка

const smsData = {
login: smscLogin,
psw: smscPassword,
phones: customers.map(c => c.phone).join(','),
mes: 'Новая акция в нашем магазине!',
sender: 'SHOP'
};

const response = await fetch('https://smsc.ru/sys/send.php', {
method: 'POST',
body: new URLSearchParams(smsData)
});

Push уведомления

Firebase Cloud Messaging (FCM)

Бесплатный сервис push уведомлений от Google.

Настройка FCM

interface FCMConfig {
server_key: string;
sender_id: string;
vapid_key: string;
service_account: ServiceAccountConfig;
}

interface ServiceAccountConfig {
type: string;
project_id: string;
private_key_id: string;
private_key: string;
client_email: string;
}

Отправка push уведомления

import admin from 'firebase-admin';

const message = {
notification: {
title: 'Новый заказ!',
body: `Заказ #${orderNumber} оформлен`,
icon: '/icon-192x192.png',
badge: '/badge-72x72.png'
},
data: {
order_id: orderId,
action: 'view_order'
},
token: userFCMToken
};

await admin.messaging().send(message);

OneSignal

Универсальная платформа для push уведомлений.

Конфигурация OneSignal

interface OneSignalConfig {
app_id: string;
rest_api_key: string;
user_auth_key: string;
safari_web_id?: string;
}

Сегментированная рассылка

const notification = {
app_id: oneSignalAppId,
headings: { 'en': 'Special Offer!', 'ru': 'Специальное предложение!' },
contents: { 'en': 'Check out our new products', 'ru': 'Посмотрите наши новинки' },
filters: [
{ field: 'tag', key: 'category', relation: '=', value: 'electronics' },
{ operator: 'AND' },
{ field: 'last_session', relation: '>', hours_ago: 24 }
],
url: 'https://marketplace.com/electronics'
};

await fetch('https://onesignal.com/api/v1/notifications', {
method: 'POST',
headers: {
'Authorization': `Basic ${restApiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(notification)
});

Telegram боты

Настройка Telegram бота

interface TelegramBotConfig {
bot_token: string;
webhook_url: string;
admin_chat_id: string;
notifications_chat_id: string;
}

Отправка уведомлений в Telegram

const sendTelegramMessage = async (chatId: string, message: string) => {
const url = `https://api.telegram.org/bot${botToken}/sendMessage`;

await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: message,
parse_mode: 'Markdown'
})
});
};

// Уведомление о новом заказе
await sendTelegramMessage(adminChatId, `
🛒 *Новый заказ #${orderNumber}*
👤 Клиент: ${customerName}
💰 Сумма: ${orderTotal}
📅 Дата: ${orderDate}
`);

Slack интеграция

Настройка Slack

interface SlackConfig {
webhook_url: string;
bot_token?: string;
channel: string;
username: string;
icon_emoji: string;
}

Отправка в Slack

const slackMessage = {
channel: '#orders',
username: 'Marketplace Bot',
icon_emoji: ':shopping_cart:',
attachments: [{
color: 'good',
title: `Новый заказ #${orderNumber}`,
fields: [
{ title: 'Клиент', value: customerName, short: true },
{ title: 'Сумма', value: `${orderTotal}`, short: true },
{ title: 'Товары', value: itemsList, short: false }
],
footer: 'Marketplace',
ts: Math.floor(Date.now() / 1000)
}]
};

await fetch(slackWebhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(slackMessage)
});

Системы уведомлений в приложении

In-app уведомления

interface InAppNotification {
id: string;
user_id: string;
title: string;
message: string;
type: NotificationType;
action_url?: string;
read: boolean;
created_at: string;
expires_at?: string;
}

type NotificationType =
| 'order_update'
| 'payment_confirmation'
| 'promotion'
| 'system_alert'
| 'reminder';

Центр уведомлений

interface NotificationCenter {
unread_count: number;
notifications: InAppNotification[];
preferences: NotificationPreferences;
filters: NotificationFilter[];
}

interface NotificationPreferences {
email: boolean;
sms: boolean;
push: boolean;
in_app: boolean;
categories: CategoryPreference[];
}

Управление подписками

Настройки подписки пользователя

interface SubscriptionSettings {
user_id: string;
email_marketing: boolean;
order_updates: boolean;
promotional_sms: boolean;
push_notifications: boolean;
frequency: NotificationFrequency;
quiet_hours: QuietHours;
}

interface QuietHours {
enabled: boolean;
start_time: string; // "22:00"
end_time: string; // "08:00"
timezone: string;
}

Отписка от рассылок

const unsubscribeLink = `https://marketplace.com/unsubscribe?token=${unsubscribeToken}&type=${notificationType}`;

// Глобальная отписка
const handleUnsubscribe = async (token: string, type: string) => {
const user = await validateUnsubscribeToken(token);

if (type === 'all') {
await updateUserPreferences(user.id, {
email_marketing: false,
promotional_sms: false
});
} else {
await updateSpecificPreference(user.id, type, false);
}
};

Аналитика уведомлений

Метрики доставки

interface NotificationMetrics {
sent: number;
delivered: number;
opened: number;
clicked: number;
bounced: number;
unsubscribed: number;
delivery_rate: number;
open_rate: number;
click_rate: number;
}

A/B тестирование

interface NotificationTest {
id: string;
name: string;
variants: NotificationVariant[];
metric: TestMetric;
duration: number;
status: TestStatus;
}

interface NotificationVariant {
name: string;
subject?: string;
content: string;
send_time?: string;
weight: number; // процент трафика
}

Автоматизация уведомлений

Триггерные кампании

interface TriggerCampaign {
id: string;
name: string;
trigger: CampaignTrigger;
actions: CampaignAction[];
conditions: CampaignCondition[];
active: boolean;
}

interface CampaignTrigger {
event: TriggerEvent;
delay?: number; // минуты
conditions?: TriggerCondition[];
}

type TriggerEvent =
| 'user_registered'
| 'cart_abandoned'
| 'order_placed'
| 'product_viewed'
| 'subscription_expires';

Последовательности уведомлений

interface NotificationSequence {
id: string;
name: string;
steps: SequenceStep[];
entry_conditions: EntryCondition[];
exit_conditions: ExitCondition[];
}

interface SequenceStep {
delay: number; // дни
notification: NotificationTemplate;
conditions?: StepCondition[];
}