Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function sincronizarContactosTokko() {
- const hoja = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- const token = 'Token xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
- const baseUrl = 'https://api.tokkobroker.com/v1/inquiries/?format=json&page=';
- const datosHoja = hoja.getDataRange().getValues();
- const contactosExistentes = {};
- for (let i = 1; i < datosHoja.length; i++) {
- const email = datosHoja[i][2];
- if (email) contactosExistentes[email] = i + 1;
- }
- let page = 1;
- let hayMas = true;
- while (hayMas) {
- const url = baseUrl + page;
- const opciones = {
- method: 'get',
- headers: { Authorization: token },
- muteHttpExceptions: true
- };
- try {
- const respuesta = UrlFetchApp.fetch(url, opciones);
- const texto = respuesta.getContentText();
- if (texto.trim().startsWith('<')) {
- Logger.log('⚠️ Respuesta no es JSON (posible error de autenticación o URL):');
- Logger.log(texto);
- return;
- }
- const datos = JSON.parse(texto);
- if (!datos.objects || datos.objects.length === 0) break;
- datos.objects.forEach(contacto => {
- const nombre = contacto.name || '';
- const telefono = contacto.phone || '';
- const email = contacto.email || '';
- const tags = (contacto.tags || []).map(tag => tag.name).join(', ');
- if (!email) return;
- if (contactosExistentes[email]) {
- const fila = contactosExistentes[email];
- const filaDatos = hoja.getRange(fila, 1, 1, 4).getValues()[0];
- if (
- filaDatos[0] !== nombre ||
- filaDatos[1] !== telefono ||
- filaDatos[3] !== tags
- ) {
- hoja.getRange(fila, 1, 1, 4).setValues([[nombre, telefono, email, tags]]);
- }
- } else {
- hoja.appendRow([nombre, telefono, email, tags]);
- }
- });
- hayMas = datos.meta && datos.meta.next !== null;
- page++;
- } catch (e) {
- Logger.log('❌ Error de conexión o formato JSON inválido:');
- Logger.log(e);
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement