Search code examples
phpgoogle-apigoogle-appsgoogle-contacts-api

How do I access my Google Contacts with PHP using a service account?


I've got an application on my phone server that used to access my Google Contacts using Client Login to allow my SIP phone to look them up. Now that Client Login was killed, I have not yet found a way to access my Google Contacts with PHP without requiring the user (me and my wife) to authenticate anything.

// create the instance of the Google Client
$this->googleclient = new Google_Client();
$this->googleclient->setApplicationName(GOOGLE_CLIENTID);

// define the credentials and access level (analytics readonly)
$credentials = new Google_Auth_AssertionCredentials(
    GOOGLE_EMAIL,
    array(
        'https://www.googleapis.com/auth/contacts.readonly',
    ),
    file_get_contents("config/key.p12"),
    "notasecret"
);

// set the user it wants to impersonate
$credentials->sub = GOOGLE_USER;

// throw the credentials into the client object
$this->googleclient->setAssertionCredentials($credentials);

// authenticate the application and fetch the token
$this->googleclient->setClientId(GOOGLE_CLIENTID);
$this->googleclient->getAuth()->refreshTokenWithAssertion();

$tokenData = json_decode($this->googleclient->getAccessToken());
$accessToken = $tokenData->access_token;

$val = file_get_contents("https://www.google.com/m8/feeds/contacts/".GOOGLE_USER."/full"
                        ."?v=3.0&access_token=".$accessToken);

print_r($val);

It works when I remove the GOOGLE_USER constant and just allow the service account to access its own data, but that's not my contact data and not that of my wife. I know that there is contact delegation within Google Apps and also Apps admins can delegate the stuff to allow the service account to access it.

But how do I do this as a non-Apps user? It seems like Google forgot this when they killed Client Login :(


Solution

  • A service account is not you and does not by default have access to any data. Think of a service account as a dummy user. If you take the service account email address and add it as a user on a folder in your google drive it will have access to that folder on google drive. If you take the service account email address and give it access to one of your calendars on Google Calendar it will have access to the calendar.

    There is no way to my knowledge to grant another user access to your google contacts.

    I suggest you try using Oauth2.