3
我已經創建了一個使用Google Analytics API的php腳本,我希望每小時運行一次cron作業。它在我的瀏覽器中工作正常,但我需要不時登錄我的Gmail帳戶並授予訪問權限。Google API Oauth 2.0 cron工作?
如何將我的gmail登錄數據保存在php腳本中,以便自動登錄?這個腳本只會使用我的登錄數據,所以它可以被硬編碼。
<?php
require_once 'Google/autoload.php';
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'xxxxxxxx';
$client_secret = 'xxxxxxxx';
$redirect_uri = 'http://example.com/xxxx';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline'); // Gets us our refreshtoken
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
print "Access from google: " . $_SESSION['token']."<br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "<b>Account:</b> ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo '-----<b>WebProperty:</b> ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
// note sometimes a web property does not have a profile/view
foreach($wp->getProfiles() as $view) {
echo '----------<b>View:</b> ' ,$view['name'], " " , $view['id'], "<br /> \n";
} // closes profile
}
} // Closes web property
} // closes account summaries
}
//Adding Dimensions
$params = array('dimensions' => 'ga:pagePath', 'metrics' => 'ga:timeOnPage,ga:uniquePageviews');
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", date("Y-m-d"), date("Y-m-d"), "ga:users,ga:sessions", $params);
?><html>
<?php echo date("Y-m-d") . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
if($row[1]<7.0 && $row[2]>100){
$length = strlen($row[0]);
if($length<12){
$row[0] = substr($row[0], 3);
print $row[0];
$short_url=$row[0];
$blocked=1;
//PDO
// configuration
$dbhost = "localhost";
$dbname = "xxxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpass = "xxxxx";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE urls SET blocked = :blocked WHERE short_url = :short_url";
$q = $conn->prepare($sql);
$q->execute(array(':short_url'=>$short_url,
':blocked'=>$blocked));
}
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td></tr>";
}
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
?>
撕開@DalmTo嘿,這是正確的做法。但目前我只能得到「結果日期:2014-12-14 ga:userType \t ga:users \t ga:sessions 行返回0」。我添加了我的憑據,下載了.p12並在Google Analytics中以用戶身份添加了電子郵件。 – Vaze
您可能想考慮將請求更改爲對您有效的請求,您不覺得嗎?該代碼僅請求「2014-12-14」,「2014-12-14」, – DaImTo
的數據哦,是的,我剛注意到它。現在它非常完美,非常感謝你:) – Vaze