Google AnalyticsAPI PHP“OAuth客户端已被禁用”

时间:2013-12-23 19:24:16

标签: php oauth google-analytics google-analytics-api

我在将google analytics api与我的php网站集成时遇到了问题。我试图在没有用户登录谷歌的情况下在我的网站上显示数据,因此我使用了服务帐户方法。我还尝试使用hello world分析代码,这给了我同样的错误。

这是完整的错误消息: 刷新OAuth2令牌时出错,消息:' {"错误" :" disabled_client"," error_description" :" OAuth客户端已被禁用。" }'

<?php 
require_once('google-api/Google_Client.php');
require_once('google-api/contrib/Google_AnalyticsService.php');

session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$KEY_FILE = 'path_to_key_file/123-privatekey.p12'; //KEY FILE     

$client = new Google_Client();
$client->setApplicationName('AppName'); //APP NAME

$account = 'abcd@developer.gserviceaccount.com'; //FOUND IN CLIENT SERVICE EMAIL ADDRESS



$client->setAssertionCredentials(new Google_AssertionCredentials(
  $account,
  array('https://www.googleapis.com/auth/analytics.readonly'),
  file_get_contents($KEY_FILE))
);

$client->setClientId('123.apps.googleusercontent.com'); //CLIENT ID
$client->setAccessType('offline_access');  // this may be unnecessary?


if (!$client->getAccessToken() && false) {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";

} else {
  // Create analytics service object. See next step below.
    if ($client) 
    {
       // Create analytics service object. See next step below.
        //$analytics = new Google_AnalyticsService($client);
        //runDemo($analytics);
        $ids = "ga:" . "46052980";
        $startDate="2013-12-12";
        $endDate="2013-12-20";
        $metrics="ga:visits";
        try {
            $analytics = new Google_AnalyticsService($client);
            $results = $analytics->data_ga->get($ids,
                            $startDate,
                                $endDate,'ga:visits');
            /*echo '<b>Number of visits this week:</b> ';
            echo $results['totalsForAllResults']['ga:visits'];
            */
        } catch(Exception $e) {
            echo 'There was an error : - ' . $e->getMessage();
        }


    } else {
        echo "error";
        echo $key;
    }
}

if ($client->getAccessToken()) {
  $_SESSION['token'] = $client->getAccessToken();
  echo $_SESSION['token'];
}

?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您现在必须使用OAuth2。看看sample code for PHP。请注意,您必须先在Google API控制台中注册您的应用,以获取客户端ID,客户端密码和API密钥。