<?php
require_once 'Google/Api/Ads/AdWords/Lib/AdWordsUser.php';
$clientSecret = "xxxxxxxxxxxx";
function GetOAuth2Credential($user, $callbackUrl) {
try{
$redirectUri = $callbackUrl;
$offline = TRUE;
$extra_para = array('approval_prompt' => 'force');
// Get the authorization URL for the OAuth2 token.
// Pass in a redirect URL back to the application,
// Passing true for the second parameter ($offline) will provide us a refresh
// token which can used be refresh the access token when it expires.
$OAuth2Handler = $user->GetOAuth2Handler();
$authorizationUrl = $OAuth2Handler->GetAuthorizationUrl($user->GetOAuth2Info(), $redirectUri, $offline, $extra_para);
}
catch(Exception $e)
{
print_r($e->getMessage());
}
return $authorizationUrl;
}
if ($_REQUEST['code']){
$authCode = $_REQUEST['code'];
// --------------------
// Generate
// --------------------
$params = array(
"code" => $authCode,
"client_id" => $clientId,
"client_secret" => $clientSecret,
"redirect_uri" => $callbackUrl,
"grant_type" => "authorization_code"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$result = json_decode ($curlData);
// print_r($result);
$access_token = $result->access_token;
$refresh_token = $result->refresh_token;
$token_type = $result->token_type;
$expires_in = $result->expires_in;
echo "<h3 style=\"padding:0; margin:0;\">General informations</h3>";
echo "<strong>My client id --></strong> ".$clientId;
echo "<br><strong>My secret key --></strong> ".$clientSecret;
echo "<br><strong>Callback url --></strong> ".$callbackUrl;
echo "<br><br>";
echo "<h3 style=\"padding:0; margin:0;\">Autorisation code</h3>";
echo "<strong>Auth code --></strong> ".$authCode;
echo "<br><br>";
echo "<h3 style=\"padding:0; margin:0;\">Generate auth token</h3>";
echo "<strong>Access token --></strong> ".$access_token;
echo "<br><strong>Refresh token --></strong> ".$refresh_token;
echo "<br><strong>Token type --></strong> ".$token_type;
echo "<br><strong>Expires in --></strong> ".$expires_in;
echo "<br><br><br><br>";
// --------------------
// I need to access user data. Whats next ?
// --------------------
}
else
{
// Create a new user and set the oAuth settings
$user = new AdWordsUser();
$user->LogAll();
$user->SetOAuth2Info(array(
"client_id" => $clientId,
"client_secret" => $clientSecret
));
// Generate an authorization URL given the callback URL
$authUrl = GetOAuth2Credential($user, $callbackUrl);
//header("Location:". $authUrl);
echo '<a href="'.$authUrl.'">Start process</a>';
}
?>