Google Contacts Api

Introduction: Google provides facility to save contacts on google by back-end java code.
In my last blog we learnt google YouTube Api to upload video from java code

Use case:   In many applications user want to save contacts on google to provide sync contacts at real time and its also provides support teams facility to call or whats app without save invest more time.

In this blog i will explain how we can save contacts using service account with impersonate user.

We need to do follow some steps:
  1. Need to setup admin for domain
  2. Create project in console.developer.google.com
  3. Create service account
  4. Enable G-suit domain wide deligation
  5. Copy client id and enable client id to admin.google account
  6. Give required access to domin email id in project IAM roles.
  7. Code changes.


I am assuming you have domain so can do domain wise delegation.

Step 1 : Create domain account https://admin.google.com/
This account will create one admin user we can use that same user to access for contacts or
we can add user to give access of contacts

Per user price 210 rs INR/month


Create a service account by following link

In place of enabling contacts api please use people Api, Contacts api is no longer supported by google.
Once service account created, enable domain wide delegation then it will create unique client id


Save P12 file for authentication.



Then go to advance setting:


Paste client id in client name annd api scope as :


We should add application :  go security -> app access control 


Add application by client id:

ACCESS : to user account:
Go to IAM and Admin
Add domain user in project and give below roles:
Changes in java code: 
Need service account, p12 file and user account (domain account email id)
Use this code to create google credential:
 GoogleCredential credential = new GoogleCredential.Builder()
  .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY)
  .setServiceAccountId(
  "dummy@dummy.iam.gserviceaccount.com")
  .setServiceAccountPrivateKeyFromP12File(new
  File(Auth.class.getClassLoader().getResource(
  "filename.p12").getFile()))
  .setServiceAccountScopes(scopes)
  .setServiceAccountUser("support@domain.com").build(); return
  credential;


Java Code:

import java.util.ArrayList;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.people.v1.PeopleService;
import com.google.api.services.people.v1.model.ListConnectionsResponse;
import com.google.api.services.people.v1.model.Name;
import com.google.api.services.people.v1.model.Person;
import com.google.api.services.people.v1.model.PhoneNumber;
import com.google.common.collect.Lists;

public class PeopleContacts {
public static void main(String[] args) {
// This OAuth 2.0 access scope allows for read-only access to the
        // authenticated user's account, but not other types of account access.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/contacts");

        try {
            // Authorize the request.
            Credential credential = Auth.authorize(scopes);
            credential.refreshToken();

            Person contactToCreate = new Person();
            
            List<Name> names = new ArrayList<Name>();
            names.add(new Name().setGivenName("Donald").setFamilyName("Hmmm"));
            contactToCreate.setNames(names);
            List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();
            phoneNumbers.add(new PhoneNumber().setValue("9928606766"));
            contactToCreate.setPhoneNumbers(phoneNumbers);

            PeopleService peopleService =
                    new PeopleService.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("google-contacts-person").build();
            Person createdContact = peopleService.people().createContact(contactToCreate).execute();
            
            
            ListConnectionsResponse response = peopleService.people().connections().list("people/me")
                .setPersonFields("names,phoneNumbers")
                .execute();
            
         // Print display name of connections if available.
            List<Person> connections = response.getConnections();
            if (connections != null && connections.size() > 0) {
                for (Person person : connections) {
               
                person.getResourceName();
                    List<Name> nameList = person.getNames();
                    if (nameList != null && nameList.size() > 0) {
                        System.out.println("Name: " + person.getNames().get(0)
                                .getDisplayName());
                    } else {
                        System.out.println("No names available for connection.");
                    }
                    if(person.getPhoneNumbers()!=null && person.getPhoneNumbers().get(0)!=null) {
                    System.out.println(person.getPhoneNumbers().get(0).getValue());
                    }
                }
            } else {
                System.out.println("No connections found.");
            }
            
        } catch (GoogleJsonResponseException e) {
            e.printStackTrace();
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());

        } catch (Throwable t) {
            t.printStackTrace();
        }

}
}


Auth.java:

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;

/**
 * Shared class used by every sample. Contains methods for authorizing a user and caching credentials.
 */
public class Auth {

    /**
     * Define a global instance of the HTTP transport.
     */
    public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    /**
     * Define a global instance of the JSON factory.
     */
    public static final JsonFactory JSON_FACTORY = new JacksonFactory();

    /**
     * Authorizes the installed application to access user's protected data.
     *
     * @param scopes list of scopes needed to run youtube.
     * @throws GeneralSecurityException 
     */
    public static Credential authorize(List<String> scopes) throws IOException, GeneralSecurityException {

    HttpTransport httpTransport =  GoogleNetHttpTransport.newTrustedTransport();
   
  GoogleCredential credential = new GoogleCredential.Builder()
  .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY)
  .setServiceAccountId(
  "raj@teacheron-sales-rajsoni.iam.gserviceaccount.com")
  .setServiceAccountPrivateKeyFromP12File(new
  File(Auth.class.getClassLoader().getResource(
  "file.p12").getFile()))
  .setServiceAccountScopes(scopes)
  .setServiceAccountUser("kartavya.soni@rajsonithewaart.com").build(); return
  credential;
    }
}


Contact will populate in google contact user account:


Note: IAM access take approx 7 min to reflect changes in console.develperment.google.com 
And API access in admin.google.com can take 24 to 48 hours.

Reference:



Comments

Post a Comment