Advertisement
DWC-cristo

Untitled

Apr 16th, 2025
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. function sincronizarContactosTokko() {
  2. const hoja = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  3. const token = 'Token xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
  4. const baseUrl = 'https://api.tokkobroker.com/v1/inquiries/?format=json&page=';
  5.  
  6. const datosHoja = hoja.getDataRange().getValues();
  7. const contactosExistentes = {};
  8.  
  9. for (let i = 1; i < datosHoja.length; i++) {
  10. const email = datosHoja[i][2];
  11. if (email) contactosExistentes[email] = i + 1;
  12. }
  13.  
  14. let page = 1;
  15. let hayMas = true;
  16.  
  17. while (hayMas) {
  18. const url = baseUrl + page;
  19. const opciones = {
  20. method: 'get',
  21. headers: { Authorization: token },
  22. muteHttpExceptions: true
  23. };
  24.  
  25. try {
  26. const respuesta = UrlFetchApp.fetch(url, opciones);
  27. const texto = respuesta.getContentText();
  28.  
  29. if (texto.trim().startsWith('<')) {
  30. Logger.log('⚠️ Respuesta no es JSON (posible error de autenticación o URL):');
  31. Logger.log(texto);
  32. return;
  33. }
  34.  
  35. const datos = JSON.parse(texto);
  36. if (!datos.objects || datos.objects.length === 0) break;
  37.  
  38. datos.objects.forEach(contacto => {
  39. const nombre = contacto.name || '';
  40. const telefono = contacto.phone || '';
  41. const email = contacto.email || '';
  42. const tags = (contacto.tags || []).map(tag => tag.name).join(', ');
  43.  
  44. if (!email) return;
  45.  
  46. if (contactosExistentes[email]) {
  47. const fila = contactosExistentes[email];
  48. const filaDatos = hoja.getRange(fila, 1, 1, 4).getValues()[0];
  49.  
  50. if (
  51. filaDatos[0] !== nombre ||
  52. filaDatos[1] !== telefono ||
  53. filaDatos[3] !== tags
  54. ) {
  55. hoja.getRange(fila, 1, 1, 4).setValues([[nombre, telefono, email, tags]]);
  56. }
  57. } else {
  58. hoja.appendRow([nombre, telefono, email, tags]);
  59. }
  60. });
  61.  
  62. hayMas = datos.meta && datos.meta.next !== null;
  63. page++;
  64.  
  65. } catch (e) {
  66. Logger.log('❌ Error de conexión o formato JSON inválido:');
  67. Logger.log(e);
  68. return;
  69. }
  70. }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement