谷歌分析查询报告-PHP

谷歌分析查询报告-PHP,php,yii,google-api,google-analytics-api,google-api-php-client,Php,Yii,Google Api,Google Analytics Api,Google Api Php Client,我正在尝试在我的web应用程序中显示google analytics报告,该报告将显示前10个页面并显示浏览器数量, 我正在使用这个链接来开发它。我在错误下面 调用POST时出错:(401)请求缺少所需的身份验证凭据。预期的OAuth 2访问令牌、登录cookie或其他有效身份验证凭据 代码: $analytics = initializeAnalytics(); $response = getReport($analytics); printResults($response); func

我正在尝试在我的web应用程序中显示google analytics报告,该报告将显示前10个页面并显示浏览器数量, 我正在使用这个链接来开发它。我在错误下面

调用POST时出错:(401)请求缺少所需的身份验证凭据。预期的OAuth 2访问令牌、登录cookie或其他有效身份验证凭据

代码:

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);


function initializeAnalytics()
{

    // Use the developers console and download your service account
    // credentials in JSON format. Place them in this directory or
    // change the key file location if necessary.
    $KEY_FILE_LOCATION = __DIR__ . '/preprod-b18917fe321f.json';

    // Create and configure a new client object.
    $client = new Google_Client();
    $client->setApplicationName("Hello Analytics Reporting");
    $client->setAuthConfig('{"web":{}}'); // provided the .json credentials
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_AnalyticsReporting($client);

    return $analytics;
}


function getReport($analytics) {

    // Replace with your view ID, for example XXXX.
    $VIEW_ID = "xxxxxx";

    // Create the DateRange object.
    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("7daysAgo");
    $dateRange->setEndDate("today");

    // Create the Metrics object.
    $sessions = new Google_Service_AnalyticsReporting_Metric();
    $sessions->setExpression("ga:sessions");
    $sessions->setAlias("sessions");

    // Create the ReportRequest object.
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId($VIEW_ID);
    $request->setDateRanges($dateRange);
    $request->setMetrics(array($sessions));

    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array( $request) );
    return $analytics->reports->batchGet( $body );
}


/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */
function printResults($reports) {
    for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
        $report = $reports[ $reportIndex ];
        $header = $report->getColumnHeader();
        $dimensionHeaders = $header->getDimensions();
        $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
        $rows = $report->getData()->getRows();

        for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
            $row = $rows[ $rowIndex ];
            $dimensions = $row->getDimensions();
            $metrics = $row->getMetrics();
            for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
                print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
            }

            for ($j = 0; $j < count($metrics); $j++) {
                $values = $metrics[$j]->getValues();
                for ($k = 0; $k < count($values); $k++) {
                    $entry = $metricHeaders[$k];
                    print($entry->getName() . ": " . $values[$k] . "\n");
                }
            }
        }
    }
}
$analytics=initializeAnalytics();
$response=getReport($analytics);
打印结果(答复);
函数initializeAnalytics()
{
//使用开发者控制台下载您的服务帐户
//JSON格式的凭据。请将它们放置在此目录或
//如有必要,请更改密钥文件位置。
$KEY_FILE_LOCATION=_DIR__.'/prepod-b18917fe321f.json';
//创建并配置新的客户端对象。
$client=新的Google_客户端();
$client->setApplicationName(“Hello Analytics Reporting”);
$client->setAuthConfig('{“web”:{}}');//提供了.json凭据
$client->setscope(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics=新谷歌服务\分析报告($client);
返回$analytics;
}
函数getReport($analytics){
//替换为视图ID,例如XXXX。
$VIEW_ID=“xxxxxx”;
//创建DateRange对象。
$dateRange=新的Google_服务_分析报告_dateRange();
$dateRange->setStartDate(“7daysAgo”);
$dateRange->setEndDate(“今天”);
//创建度量对象。
$sessions=新Google_服务_分析报告_度量();
$sessions->setExpression(“ga:sessions”);
$sessions->setAlias(“sessions”);
//创建ReportRequest对象。
$request=new Google_Service_analytics reporting_ReportRequest();
$request->setViewId($VIEW\u ID);
$request->setDateRanges($dateRange);
$request->setMetrics(数组($sessions));
$body=新的Google_服务_分析报告_GetReportsRequest();
$body->setReportRequests(数组($request));
返回$analytics->reports->batchGet($body);
}
/**
*解析并打印分析报告API V4响应。
*
*@param分析报告API V4响应。
*/
函数打印结果($报告){
对于($reportIndex=0;$reportIndexgetColumnHeader();
$dimensionHeaders=$header->getDimensions();
$metricHeaders=$header->getMetricHeader()->getMetricHeaderEntries();
$rows=$report->getData()->getRows();
对于($rowIndex=0;$rowIndexgetDimensions();
$metrics=$row->getMetrics();
对于($i=0;$igetValues();
对于($k=0;$kgetName()。“:”$values[$k]。“\n”);
}
}
}
}
}
任何人请给我一个想法来摆脱这个错误

调用POST时出错:(401)请求缺少所需的身份验证凭据。预期的OAuth 2访问令牌、登录cookie或其他有效身份验证凭据

表示您未登录,在运行代码之前未正确验证客户端

服务账户可能存在的问题

  • 检查
    $client->setAuthConfig('{“web”:{}}')确保这是json密钥文件的正确路径。可能应该是
    $KEY\u FILE\u位置
  • 请确保您在Google开发者控制台上创建了服务帐户凭据,而不是其他任何东西。此代码仅适用于服务帐户密钥文件
  • 确保您已授予服务帐户访问您的google analytics帐户的权限。获取服务帐户电子邮件地址,并将其作为用户添加到帐户级别的Google analytics中
  • json文件位置问题

    如果文件仍有问题,可以将该位置放入环境中

    // Load the Google API PHP Client Library.
    require_once __DIR__ . '/vendor/autoload.php';
    // Use the developers console and download your service account
    // credentials in JSON format. Place the file in this directory or
    // change the key file location if necessary.
    putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
    /**
     * Gets the Google client refreshing auth if needed.
     * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
     * Initializes a client object.
     * @return A google client object.
     */
    function getGoogleClient() {
        return getServiceAccountClient();
    }
    /**
     * Builds the Google client object.
     * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
     * Scopes will need to be changed depending upon the API's being accessed. 
     * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
     * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
     * @return A google client object.
     */
    function getServiceAccountClient() {
        try {   
            // Create and configure a new client object.        
            $client = new Google_Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope([YOUR SCOPES HERE]);
            return $client;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
    

    错误告诉我们用户需要登录。您只需添加身份验证部分


    我建议您查看一个示例。

    代码是否提示您访问数据的权限?@DaImTo否,它显示调用POST时出错:(401)请求缺少所需的身份验证凭据。预期OAuth 2访问令牌、登录cookie或其他有效身份验证证书您好,我在这个链接@US-1234中找不到相关代码,这很奇怪,因为我是从该页面复制的。代码的第一部分向下五行。@DalmTo抱歉,我正在使用此链接,我已更新了我的答案,以反映您实际使用的是服务帐户,而不是Oauth2进行身份验证。我已尝试使用key location,它向我显示无效的json,因此我尝试复制json$client->setAuthConfig(“{”web:{}}”);我真的很感谢你把他和我的一个样本联系起来。然而,他遵循官方规定,这可能会让他感到困惑。