Всем привет! Я пытаюсь задеплоить функции в Firebase functions, но у меня возникают ошибки. Сразу говорю что знаю, что код может быть не идеален и вероятно плох, я не разбираюсь в node js поэтому сгенерировал его)
Вот ошибка:
Could not create or update Cloud Run service createpaymentlink, Container Healthcheck failed. Revision 'createpaymentlink-00001-fox' is not ready and cannot serve traffic.
The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable within the allocated timeout.
This can happen when the container port is misconfigured or if the timeout is too short. The health check timeout can be extended. Logs for this revision might contain more information.
Вот мой код:
const {onSchedule} = require("firebase-functions/v2/scheduler");
const {onRequest} = require("firebase-functions/v2/https");
const admin = require("firebase-admin");
const axios = require("axios");
admin.initializeApp();
const CRYPTOCLOUD_API_TOKEN = "Здесь токен";
const subscriptionPrices = {
Week: 1.25,
Month: 4.99,
ThreeMonth: 12.99,
Year: 39.99,
};
exports.deleteUser = onRequest(async (req, res) => {
// Проверка, что это POST-запрос
if (req.method !== "POST") {
return res.status(405).send("Only POST requests are allowed");
}
const uid = req.body.uid;
if (!uid) {
return res.status(400).send("Missing uid");
}
try {
// Удаление данных пользователя из Realtime Database
await admin.database().ref(`/users/${uid}`).remove();
return res.status(200).send(`User with UID ${uid} has been deleted.`);
} catch (error) {
console.error("Error deleting user:", error);
return res.status(500).send("Internal Server Error");
}
});
// Создание ссылки на оплату
exports.createPaymentLink = onRequest(async (req, res) => {
if (req.method !== "POST") {
return res.status(405).send("Method Not Allowed");
}
const {userId, subscriptionType} = req.body;
if (!userId || !subscriptionType || !subscriptionPrices[subscriptionType]) {
return res.status(400).send("Missing or invalid fields");
}
const amount = subscriptionPrices[subscriptionType];
const orderId = `${userId}_${Date.now()}`;
try {
const response = await axios.post(
"https://pay.cryptocloud.plus/api/v2/invoice/create",
{
amount: amount.toString(),
currency: "USD",
order_id: orderId,
description: `Подписка: ${subscriptionType}`,
lifetime: 3600,
},
{
headers: {
"Authorization": `Token ${CRYPTOCLOUD_API_TOKEN}`,
"Content-Type": "application/json",
},
},
);
const invoiceUrl = response.data.data.url;
if (!invoiceUrl) {
return res.status(500).send("Не удалось получить ссылку на оплату");
}
// ⏳ Сохраняем заказ в базу данных для последующего отслеживания
await admin.database().ref(`pendingPayments/${orderId}`).set({
userId,
subscriptionType,
createdAt: Date.now(),
});
return res.status(200).json({invoiceUrl});
} catch (error) {
console.error("Ошибка CryptoCloud:", error.response.data || error.message);
return res.status(500).send("Ошибка при создании счёта");
}
});
// Периодическая проверка всех неоплаченных заказов (вызывать по крону)
exports.checkPendingPayments = onSchedule("every 1 minutes", async (event) => {
const snapshot = await admin.database().ref("pendingPayments")
.once("value");
const payments = snapshot.val();
if (!payments) {
console.log("Нет ожидающих оплат.");
return null;
}
const now = Date.now();
const checks = Object.entries(payments).map(async ([orderId, data]) => {
const {userId, subscriptionType} = data;
try {
const res = await axios.get(
`https://pay.cryptocloud.plus/api/v2/invoice/info?order_id=${orderId}`,
{
headers: {
Authorization: `Token ${CRYPTOCLOUD_API_TOKEN}`,
},
},
);
const status = res.data.data.status;
console.log(`Статус ${orderId}: ${status}`);
if (status === "paid") {
let durationMs = 0;
switch (subscriptionType) {
case "Week":
durationMs = 7 * 24 * 60 * 60 * 1000;
break;
case "Month":
durationMs = 30 * 24 * 60 * 60 * 1000;
break;
case "ThreeMonth":
durationMs = 90 * 24 * 60 * 60 * 1000;
break;
case "Year":
durationMs = 365 * 24 * 60 * 60 * 1000;
break;
}
const expirationDate = now + durationMs;
await admin.database().ref(`users/${userId}/subscription`).set({
active: true,
expiresAt: expirationDate,
});
console.log(`✅ Подписка активирована для ${userId}`);
await admin.database().ref(`pendingPayments/${orderId}`).remove();
} else if (status === "expired" || status === "cancelled") {
console.log(`❌ Счёт ${orderId} отменён или истёк`);
await admin.database().ref(`pendingPayments/${orderId}`).remove();
}
} catch (error) {
console.error(`Ошибка при проверке ${orderId}:`,
error.response.data || error.message);
}
});
await Promise.all(checks);
return null;
});
Я не разбираюсь в этом сильно, поэтому мог не указать какую-то необходимую информацию, если для ответа нужно что-то ещё - я могу это сбросить. Заранее спасибо за помощь!