Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Access Google Contact API and return contact's
/**
* Contact Google via Oauth + API
* All getenv() referances are application configuration variables
* $this->curlGoole(/*...*/) is a typical cURL call capable of GET and POST
*/
public function actionGoogle()
{
// holder vars
$queryStringArray = [];
$returnData = null;
// create the requestor link
/* $client = new \Google_Client();
$client->setApplicationName(getenv('GOOGLE_CLIENT_NAME'));
$client->setClientid(getenv('GOOGLE_CLIENT_ID'));
$client->setClientSecret(getenv('GOOGLE_CLIENT_SECRET'));
$client->setRedirectUri(getenv('GOOGLE_RECOM_RETURNURL'));
$client->setAccessType('online');
$client->setScopes(getenv('GOOGLE_RECOM_SCOPE'));
echo '<a href="'. $client->createAuthUrl() .'"> Import google contacts </a>'; */
// the return from the link contains an application code
if (isset($_GET['code'])) {
$queryStringArray = [
'code' => $_GET['code'],
'client_id' => getenv('GOOGLE_CLIENT_ID'),
'client_secret' => getenv('GOOGLE_CLIENT_SECRET'),
'redirect_uri' => getenv('GOOGLE_RECOM_RETURNURL'),
'grant_type' => 'authorization_code'
];
// request a access token by POSTing the application code
$response = json_decode(
$this->curlGoogleAPI(
'https://accounts.google.com/o/oauth2/token',
http_build_query($queryStringArray)
)
);
// if a valid access token is returned
if (isset($response->access_token)) {
$queryStringArray = [
'alt' => getenv('GOOGLE_API_FORMAT'),
'max-results' => getenv('GOOGLE_PAGE_SIZE'),
'oauth_token' => $response->access_token,
'v' => getenv('GOOGLE_API_VERSION'),
];
// use the access token to request the target users email list
$contacts = json_decode(
$this->curlGoogleAPI(
'https://www.google.com/m8/feeds/contacts/default/full?'.http_build_query($queryStringArray)
),
true
);
// convert/format the target users contact list
if (!empty($contacts['feed']['entry'])) {
foreach($contacts['feed']['entry'] as $contact) {
$returnData[] = [
'name' => $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
];
}
}
} else {
echo 'access token validation failed.<br />';
}
}
// display response data
echo '<pre>';
print_r( $returnData );
echo '</pre>';
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.