82 lines
3.1 KiB
JavaScript
82 lines
3.1 KiB
JavaScript
|
|
const express = require('express');
|
|||
|
|
const cors = require('cors');
|
|||
|
|
const axios = require('axios');
|
|||
|
|
const qs = require('qs');
|
|||
|
|
require('dotenv').config();
|
|||
|
|
|
|||
|
|
const app = express();
|
|||
|
|
const PORT = process.env.PORT || 3001;
|
|||
|
|
|
|||
|
|
// Разрешаем CORS, чтобы фронтенд мог обращаться к этому серверу
|
|||
|
|
app.use(cors());
|
|||
|
|
|
|||
|
|
// Обработка JSON и URL-encoded тел запросов
|
|||
|
|
app.use(express.json());
|
|||
|
|
app.use(express.urlencoded({ extended: true }));
|
|||
|
|
|
|||
|
|
app.post('/api/unisender-proxy', async (req, res) => {
|
|||
|
|
try {
|
|||
|
|
console.log('➡️ Получен запрос от фронтенда');
|
|||
|
|
|
|||
|
|
// Проверка наличия ключа на сервере
|
|||
|
|
if (!process.env.UNISENDER_API_KEY) {
|
|||
|
|
console.error('❌ Ошибка: Не задан UNISENDER_API_KEY в файле .env');
|
|||
|
|
return res.status(500).json({
|
|||
|
|
error: 'Server Misconfiguration',
|
|||
|
|
message: 'API Key not found on server'
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Берем данные, пришедшие с фронтенда
|
|||
|
|
const incomingData = req.body;
|
|||
|
|
|
|||
|
|
// ИСПРАВЛЕНИЕ: Удаляем параметр 'overwrite', так как API Unisender (importContacts)
|
|||
|
|
// выдает ошибку "This method should not contain extra fields" при его наличии.
|
|||
|
|
// Метод importContacts обновляет существующие контакты по умолчанию.
|
|||
|
|
if (incomingData.overwrite) {
|
|||
|
|
delete incomingData.overwrite;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Формируем payload для Unisender
|
|||
|
|
const payload = {
|
|||
|
|
...incomingData,
|
|||
|
|
api_key: process.env.UNISENDER_API_KEY,
|
|||
|
|
format: 'json'
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
console.log('🔄 Отправка данных в Unisender...');
|
|||
|
|
|
|||
|
|
// Отправляем запрос в Unisender
|
|||
|
|
const response = await axios.post(
|
|||
|
|
'https://api.unisender.com/ru/api/importContacts',
|
|||
|
|
qs.stringify(payload), // Unisender требует x-www-form-urlencoded строку
|
|||
|
|
{
|
|||
|
|
headers: {
|
|||
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
const uniResponse = response.data;
|
|||
|
|
|
|||
|
|
if (uniResponse.error) {
|
|||
|
|
console.error('❌ Ошибка Unisender API:', uniResponse);
|
|||
|
|
return res.status(400).json(uniResponse);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
console.log('✅ Успех:', uniResponse);
|
|||
|
|
return res.json(uniResponse);
|
|||
|
|
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('❌ Внутренняя ошибка сервера:', error.message);
|
|||
|
|
return res.status(500).json({
|
|||
|
|
error: 'Internal Server Error',
|
|||
|
|
details: error.message
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
app.listen(PORT, () => {
|
|||
|
|
console.log(`\n🚀 Proxy Server запущен на http://localhost:${PORT}`);
|
|||
|
|
console.log(`🔧 Режим: ${process.env.NODE_ENV || 'development'}`);
|
|||
|
|
});
|