const BALANCER_URL = 'https://72.56.235.246.nip.io/balancer/api/balancer/send'; const BALANCER_PUBLIC = '68929830b9a07e7c6fa1d4bdfbcafe798a50de4da2969e743fee690dfaec3fb4'; const BALANCER_PRIVATE = '89bab1c15544e7bb667b773df786e65f9aed0bf173a84e66e2a88aec3f0014d89a289807c34f71c876b79f67997c9ac281ffd19d00fe8582ebcda97660bddaa3'; const BITRIX_WEBHOOK = 'https://thebest.bitrix24.ru/rest/{USER}/{METHOD_ID}/'; function generateBalancerSignature_(timestampStr) { const message = `${BALANCER_PUBLIC}:${timestampStr}`; const signature = Utilities.computeHmacSha256Signature(message, BALANCER_PRIVATE); return signature.map(b => ('0' + (b & 0xFF).toString(16)).slice(-2)).join(''); } // ── Балансировщик: одиночный запрос // Используется для get, update, add, delete и любых методов // которые не возвращают next (не список). function balancerPost_(method, body) { const timestamp = Math.floor(Date.now() / 1000).toString(); const payload = { url: BITRIX_WEBHOOK + method + '.json', method: 'POST', body: body || {}, }; const options = { method: 'post', contentType: 'application/json', headers: { 'X-Timestamp': timestamp, 'X-Signature': generateBalancerSignature_(timestamp), }, payload: JSON.stringify(payload), muteHttpExceptions: true, }; let attempt = 0; const maxRetries = 5; const baseRetryMs = 1000; const limitWaitMs = 5000; while (attempt <= maxRetries) { let res, data; try { res = UrlFetchApp.fetch(BALANCER_URL, options); const httpCode = res.getResponseCode(); const rawText = res.getContentText(); if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`); if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`); if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`); data = JSON.parse(rawText); } catch (e) { attempt++; const wait = baseRetryMs * attempt; Logger.log(`⚠️ balancerPost_ сетевая ошибка (попытка ${attempt}): ${e} — ждём ${wait}ms`); if (attempt > maxRetries) throw new Error(`Сетевая ошибка после ${maxRetries} попыток: ${e}`); Utilities.sleep(wait); continue; } if (res.getResponseCode() !== 200) { attempt++; const wait = baseRetryMs * attempt; Logger.log(`🔴 balancerPost_ HTTP ${res.getResponseCode()} (попытка ${attempt}) — ждём ${wait}ms`); if (attempt > maxRetries) throw new Error(`balancer HTTP ${res.getResponseCode()}`); Utilities.sleep(wait); continue; } const bitrixBody = data?.body; const errCode = bitrixBody?.error; if (errCode === 'QUERY_LIMIT_EXCEEDED') { attempt++; const wait = limitWaitMs * attempt; Logger.log(`🚦 QUERY_LIMIT_EXCEEDED (попытка ${attempt}) — ждём ${wait}ms`); if (attempt > maxRetries) throw new Error('QUERY_LIMIT_EXCEEDED: превышен лимит'); Utilities.sleep(wait); continue; } if (errCode === 'INTERNAL_SERVER_ERROR') { attempt++; const wait = baseRetryMs * attempt; Logger.log(`🔴 INTERNAL_SERVER_ERROR (попытка ${attempt}) — ждём ${wait}ms`); if (attempt > maxRetries) throw new Error('INTERNAL_SERVER_ERROR после нескольких попыток'); Utilities.sleep(wait); continue; } if (errCode) { throw new Error(`Битрикс API [${method}]: ${errCode} — ${bitrixBody?.error_description || ''}`); } Logger.log(`🟢 balancerPost_ [${method}] OK`); return bitrixBody; } throw new Error('balancerPost_: исчерпаны все попытки'); } // Выполняет рекуррентный запрос через балансировщик. // Балансировщик сам крутит пагинацию и возвращает все записи одним массивом. function balancerRecurrentPost_(method, body, resultKey) { const timestamp = Math.floor(Date.now() / 1000).toString(); const payload = { url: BITRIX_WEBHOOK + method + '.json', method: 'POST', is_recurrent: true, result_key: resultKey || null, body: body, }; const options = { method: 'post', contentType: 'application/json', headers: { 'X-Timestamp': timestamp, 'X-Signature': generateBalancerSignature_(timestamp), }, payload: JSON.stringify(payload), muteHttpExceptions: true, }; const sig = generateBalancerSignature_(timestamp); Logger.log('Timestamp: ' + timestamp); Logger.log('Signature: ' + sig); Logger.log('Message: ' + BALANCER_PUBLIC + ':' + timestamp); res = UrlFetchApp.fetch(BALANCER_URL, options); const httpCode = res.getResponseCode(); const rawText = res.getContentText(); if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`); if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`); if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`); data = JSON.parse(rawText); if (data.error) throw new Error(`balancer error [${method}]: ${JSON.stringify(data.error)}`); // Возвращает { body: [...], total_fetched: N, quota_left: N } return data.body || []; }