Syncing Google Contacts between two Google Workspace gmail ids using Google Apps Script

We have written the following code to sync contacts between two gmail ids, such that if a new contact is being added to one email id and the Google Apps Script is run, the new contacts get synced to the other email id too:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const CLIENT_ID = 'client_id'; const CLIENT_SECRET = 'client_secret';
// Replace with the initial refresh tokens for both users
const USER1_REFRESH_TOKEN = 'Reftoken1';
const USER2_REFRESH_TOKEN = 'Reftoken2';
function syncContacts() {
try {
// Get fresh access tokens for both users
const user1AccessToken = refreshAccessToken(USER1_REFRESH_TOKEN);
const user2AccessToken = refreshAccessToken(USER2_REFRESH_TOKEN);
// Fetch contacts from both accounts
const user1Contacts = fetchContacts(user1AccessToken);
const user2Contacts = fetchContacts(user2AccessToken);
// Sync contacts between accounts
addUniqueContacts(user1Contacts, user2AccessToken);
addUniqueContacts(user2Contacts, user1AccessToken);
Logger.log('Contacts synced successfully!');
} catch (error) {
Logger.log(`Error during sync: ${error.message}`);
}
}
function fetchContacts(accessToken) {
const url = 'https://people.googleapis.com/v1/people/me/connections?pageSize=2000&personFields=names,emailAddresses,phoneNumbers';
const options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + accessToken,
},
muteHttpExceptions: true,
};
try {
const response = UrlFetchApp.fetch(url, options);
const result = JSON.parse(response.getContentText());
if (response.getResponseCode() === 200 && result.connections) {
Logger.log(`Fetched ${result.connections.length} contacts.`);
return result;
} else {
Logger.log('Error fetching contacts: ' + response.getContentText());
return null;
}
} catch (error) {
Logger.log('Error fetching contacts: ' + error.message);
return null;
}
}
function addUniqueContacts(sourceAccessToken, targetAccessToken) {
const sourceContacts = fetchContacts(sourceAccessToken);
const targetContacts = fetchContacts(targetAccessToken);
if (!sourceContacts || !targetContacts) {
Logger.log('Failed to fetch contacts. Aborting synchronization.');
return;
}
const targetPhoneNumbers = new Set(
targetContacts.connections.flatMap(contact =>
contact.phoneNumbers?.map(phone => formatPhoneNumber(phone.value)) || []
)
);
const uniqueContacts = sourceContacts.connections.filter(contact =>
(contact.phoneNumbers || []).some(phone =>
!targetPhoneNumbers.has(formatPhoneNumber(phone.value))
)
);
Logger.log(`Found ${uniqueContacts.length} unique contacts.`);
uniqueContacts.forEach(contact => {
const sanitizedContact = sanitizeContact(contact); // Sanitize before creating
try {
createContact(targetAccessToken, sanitizedContact);
} catch (error) {
Logger.log('Error adding unique contact: ' + error.message);
}
});
}
function sanitizeContact(contact) {
// Remove metadata, resourceName, etag, and other unnecessary fields
return {
names: contact.names?.map(name => ({
displayName: name.displayName,
givenName: name.givenName,
})),
emailAddresses: contact.emailAddresses?.map(email => ({
value: email.value,
})),
phoneNumbers: contact.phoneNumbers?.map(phone => ({
value: phone.value,
})),
};
}
function createContact(accessToken, contact) {
const url = 'https://people.googleapis.com/v1/people:createContact';
const options = {
method: 'post',
headers: {
Authorization: 'Bearer ' + accessToken,
},
contentType: 'application/json',
muteHttpExceptions: true,
payload: JSON.stringify(contact),
};
try {
const response = UrlFetchApp.fetch(url, options);
const result = JSON.parse(response.getContentText());
if (response.getResponseCode() === 200) {
Logger.log('Contact Created: ' + JSON.stringify(result));
} else {
Logger.log('Error creating contact: ' + response.getContentText());
}
} catch (error) {
Logger.log('Error creating contact: ' + error.message);
throw new Error('Failed to create contact.');
}
}
function refreshAccessToken(refreshToken) {
const url = 'https://oauth2.googleapis.com/token';
const payload = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
refresh_token: refreshToken,
grant_type: 'refresh_token',
};
const options = {
method: 'post',
contentType: 'application/x-www-form-urlencoded',
payload: Object.keys(payload)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
.join('&'),
muteHttpExceptions: true, // Capture full error details
};
try {
const response = UrlFetchApp.fetch(url, options);
const result = JSON.parse(response.getContentText());
// Log the response for debugging
Logger.log(`Token refresh response: ${JSON.stringify(result)}`);
if (result.access_token) {
Logger.log('Access token refreshed successfully.');
return result.access_token;
} else {
throw new Error(result.error_description || 'Failed to refresh access token.');
}
} catch (error) {
Logger.log(`Error refreshing access token: ${error.message}`);
throw new Error('Access token refresh failed.');
}
}
function formatPhoneNumber(phone) {
// Standardize phone numbers for comparison
return phone.replace(/[^d+]/g, ''); // Removes non-digit and non-'+' characters
}
</code>
<code>const CLIENT_ID = 'client_id'; const CLIENT_SECRET = 'client_secret'; // Replace with the initial refresh tokens for both users const USER1_REFRESH_TOKEN = 'Reftoken1'; const USER2_REFRESH_TOKEN = 'Reftoken2'; function syncContacts() { try { // Get fresh access tokens for both users const user1AccessToken = refreshAccessToken(USER1_REFRESH_TOKEN); const user2AccessToken = refreshAccessToken(USER2_REFRESH_TOKEN); // Fetch contacts from both accounts const user1Contacts = fetchContacts(user1AccessToken); const user2Contacts = fetchContacts(user2AccessToken); // Sync contacts between accounts addUniqueContacts(user1Contacts, user2AccessToken); addUniqueContacts(user2Contacts, user1AccessToken); Logger.log('Contacts synced successfully!'); } catch (error) { Logger.log(`Error during sync: ${error.message}`); } } function fetchContacts(accessToken) { const url = 'https://people.googleapis.com/v1/people/me/connections?pageSize=2000&personFields=names,emailAddresses,phoneNumbers'; const options = { method: 'get', headers: { Authorization: 'Bearer ' + accessToken, }, muteHttpExceptions: true, }; try { const response = UrlFetchApp.fetch(url, options); const result = JSON.parse(response.getContentText()); if (response.getResponseCode() === 200 && result.connections) { Logger.log(`Fetched ${result.connections.length} contacts.`); return result; } else { Logger.log('Error fetching contacts: ' + response.getContentText()); return null; } } catch (error) { Logger.log('Error fetching contacts: ' + error.message); return null; } } function addUniqueContacts(sourceAccessToken, targetAccessToken) { const sourceContacts = fetchContacts(sourceAccessToken); const targetContacts = fetchContacts(targetAccessToken); if (!sourceContacts || !targetContacts) { Logger.log('Failed to fetch contacts. Aborting synchronization.'); return; } const targetPhoneNumbers = new Set( targetContacts.connections.flatMap(contact => contact.phoneNumbers?.map(phone => formatPhoneNumber(phone.value)) || [] ) ); const uniqueContacts = sourceContacts.connections.filter(contact => (contact.phoneNumbers || []).some(phone => !targetPhoneNumbers.has(formatPhoneNumber(phone.value)) ) ); Logger.log(`Found ${uniqueContacts.length} unique contacts.`); uniqueContacts.forEach(contact => { const sanitizedContact = sanitizeContact(contact); // Sanitize before creating try { createContact(targetAccessToken, sanitizedContact); } catch (error) { Logger.log('Error adding unique contact: ' + error.message); } }); } function sanitizeContact(contact) { // Remove metadata, resourceName, etag, and other unnecessary fields return { names: contact.names?.map(name => ({ displayName: name.displayName, givenName: name.givenName, })), emailAddresses: contact.emailAddresses?.map(email => ({ value: email.value, })), phoneNumbers: contact.phoneNumbers?.map(phone => ({ value: phone.value, })), }; } function createContact(accessToken, contact) { const url = 'https://people.googleapis.com/v1/people:createContact'; const options = { method: 'post', headers: { Authorization: 'Bearer ' + accessToken, }, contentType: 'application/json', muteHttpExceptions: true, payload: JSON.stringify(contact), }; try { const response = UrlFetchApp.fetch(url, options); const result = JSON.parse(response.getContentText()); if (response.getResponseCode() === 200) { Logger.log('Contact Created: ' + JSON.stringify(result)); } else { Logger.log('Error creating contact: ' + response.getContentText()); } } catch (error) { Logger.log('Error creating contact: ' + error.message); throw new Error('Failed to create contact.'); } } function refreshAccessToken(refreshToken) { const url = 'https://oauth2.googleapis.com/token'; const payload = { client_id: CLIENT_ID, client_secret: CLIENT_SECRET, refresh_token: refreshToken, grant_type: 'refresh_token', }; const options = { method: 'post', contentType: 'application/x-www-form-urlencoded', payload: Object.keys(payload) .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`) .join('&'), muteHttpExceptions: true, // Capture full error details }; try { const response = UrlFetchApp.fetch(url, options); const result = JSON.parse(response.getContentText()); // Log the response for debugging Logger.log(`Token refresh response: ${JSON.stringify(result)}`); if (result.access_token) { Logger.log('Access token refreshed successfully.'); return result.access_token; } else { throw new Error(result.error_description || 'Failed to refresh access token.'); } } catch (error) { Logger.log(`Error refreshing access token: ${error.message}`); throw new Error('Access token refresh failed.'); } } function formatPhoneNumber(phone) { // Standardize phone numbers for comparison return phone.replace(/[^d+]/g, ''); // Removes non-digit and non-'+' characters } </code>
const CLIENT_ID = 'client_id'; const CLIENT_SECRET = 'client_secret';

// Replace with the initial refresh tokens for both users
const USER1_REFRESH_TOKEN = 'Reftoken1';
const USER2_REFRESH_TOKEN = 'Reftoken2';

function syncContacts() {
  try {
    // Get fresh access tokens for both users
    const user1AccessToken = refreshAccessToken(USER1_REFRESH_TOKEN);
    const user2AccessToken = refreshAccessToken(USER2_REFRESH_TOKEN);

    // Fetch contacts from both accounts
    const user1Contacts = fetchContacts(user1AccessToken);
    const user2Contacts = fetchContacts(user2AccessToken);

    // Sync contacts between accounts
    addUniqueContacts(user1Contacts, user2AccessToken);
    addUniqueContacts(user2Contacts, user1AccessToken);

    Logger.log('Contacts synced successfully!');
  } catch (error) {
    Logger.log(`Error during sync: ${error.message}`);
  }
}

function fetchContacts(accessToken) {
  const url = 'https://people.googleapis.com/v1/people/me/connections?pageSize=2000&personFields=names,emailAddresses,phoneNumbers';
  const options = {
    method: 'get',
    headers: {
      Authorization: 'Bearer ' + accessToken,
    },
    muteHttpExceptions: true,
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const result = JSON.parse(response.getContentText());

    if (response.getResponseCode() === 200 && result.connections) {
      Logger.log(`Fetched ${result.connections.length} contacts.`);
      return result;
    } else {
      Logger.log('Error fetching contacts: ' + response.getContentText());
      return null;
    }
  } catch (error) {
    Logger.log('Error fetching contacts: ' + error.message);
    return null;
  }
}


function addUniqueContacts(sourceAccessToken, targetAccessToken) {
  const sourceContacts = fetchContacts(sourceAccessToken);
  const targetContacts = fetchContacts(targetAccessToken);

  if (!sourceContacts || !targetContacts) {
    Logger.log('Failed to fetch contacts. Aborting synchronization.');
    return;
  }

  const targetPhoneNumbers = new Set(
    targetContacts.connections.flatMap(contact =>
      contact.phoneNumbers?.map(phone => formatPhoneNumber(phone.value)) || []
    )
  );

  const uniqueContacts = sourceContacts.connections.filter(contact =>
    (contact.phoneNumbers || []).some(phone =>
      !targetPhoneNumbers.has(formatPhoneNumber(phone.value))
    )
  );

  Logger.log(`Found ${uniqueContacts.length} unique contacts.`);

  uniqueContacts.forEach(contact => {
    const sanitizedContact = sanitizeContact(contact); // Sanitize before creating
    try {
      createContact(targetAccessToken, sanitizedContact);
    } catch (error) {
      Logger.log('Error adding unique contact: ' + error.message);
    }
  });
}

function sanitizeContact(contact) {
  // Remove metadata, resourceName, etag, and other unnecessary fields
  return {
    names: contact.names?.map(name => ({
      displayName: name.displayName,
      givenName: name.givenName,
    })),
    emailAddresses: contact.emailAddresses?.map(email => ({
      value: email.value,
    })),
    phoneNumbers: contact.phoneNumbers?.map(phone => ({
      value: phone.value,
    })),
  };
}

function createContact(accessToken, contact) {
  const url = 'https://people.googleapis.com/v1/people:createContact';
  const options = {
    method: 'post',
    headers: {
      Authorization: 'Bearer ' + accessToken,
    },
    contentType: 'application/json',
    muteHttpExceptions: true,
    payload: JSON.stringify(contact),
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const result = JSON.parse(response.getContentText());

    if (response.getResponseCode() === 200) {
      Logger.log('Contact Created: ' + JSON.stringify(result));
    } else {
      Logger.log('Error creating contact: ' + response.getContentText());
    }
  } catch (error) {
    Logger.log('Error creating contact: ' + error.message);
    throw new Error('Failed to create contact.');
  }
}

        function refreshAccessToken(refreshToken) {
  const url = 'https://oauth2.googleapis.com/token';
  const payload = {
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    refresh_token: refreshToken,
    grant_type: 'refresh_token',
  };

   const options = {
    method: 'post',
    contentType: 'application/x-www-form-urlencoded',
    payload: Object.keys(payload)
      .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
      .join('&'),
    muteHttpExceptions: true, // Capture full error details
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const result = JSON.parse(response.getContentText());

    // Log the response for debugging
    Logger.log(`Token refresh response: ${JSON.stringify(result)}`); 

     if (result.access_token) {
      Logger.log('Access token refreshed successfully.');
      return result.access_token;
    } else {
      throw new Error(result.error_description || 'Failed to refresh access token.');
    }
  } catch (error) {
    Logger.log(`Error refreshing access token: ${error.message}`);
    throw new Error('Access token refresh failed.');
  }
} 

         function formatPhoneNumber(phone) {
  // Standardize phone numbers for comparison
  return phone.replace(/[^d+]/g, ''); // Removes non-digit and non-'+' characters
}

However, I keep getting this error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Error fetching contacts: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
</code>
<code>Error fetching contacts: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } } </code>
Error fetching contacts: {
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

These are the following ways I have tried trouble shooting:

  1. Check if People API is enabled for both email ids.

  2. Set up Credentials from one account and share with the other.

  3. Set up these following redirect URI’s:
    http://localhost, https://script.google.com/oauthcallback, https://developers.google.com/oauthplayground

  4. Have authorised API in Google playground from both id’s and stored correct refresh tokens

I am not sure how to rectify this error. Would be really helpful if someone could guide?

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật