Google Analytics - 无需登录即可访问 api [英] Google Analytics - Access api without login

查看:28
本文介绍了Google Analytics - 无需登录即可访问 api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功配置了谷歌分析 API 并获得了成功的数据.

I had successfully configured google analytics api and get successful data.

我想在不登录 Gmail 的情况下访问分析 API.

即我将硬编码凭据以进行登录,但如何使用 PHP 来实现?

i.e. I will hard code credentials to for login, but how to do it with PHP?

有没有实现这个任务的api函数(对于PHP)

Is there any api function to achive this task (for PHP)

谢谢!

推荐答案

The Hello Analytics API:服务帐户的 PHP 快速入门指南将引导您完成创建服务帐户并将其添加到您现有的 Google Analytics(分析)帐户/属性/视图所需的步骤.

The Hello Analytics API: PHP Quickstart Guide for Service Accounts will walk you through the steps necessary to create and add a service account to your existing Google Analytics Account/Property/View.

一旦您下载了 php 客户端库和从开发者控制台下载的 p12 文件,您就可以创建一个授权的分析服务对象,如下所示:

Once you download have the php client libs and the p12 file downloaded from developer console you can create an authorized analytics service object as follows:

// Creates and returns the Analytics service object.

// Load the Google API PHP Client Library.
require_once 'google-api-php-client/src/Google/autoload.php';

// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$service_account_email = '<Replace with your service account email address.>';
$key_file_location = '<Replace with /path/to/generated/client_secrets.p12>';

// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);

// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_email,
    array(Google_Service_Analytics::ANALYTICS_READONLY),
    $key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

return $analytics;

使用返回的服务对象,您现在可以调用 Google Analytics API:

With the returned service object you can now make calls to the Google Analytics APIs:

// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
$analytics->data_ga->get(
   'ga:' . $profileId,
   '7daysAgo',
   'today',
   'ga:sessions');

这篇关于Google Analytics - 无需登录即可访问 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆