欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将Google Analytics API v3与PHP结合使用:获取数据

程序员文章站 2022-06-11 12:22:22
...

In the first part of our series, we introduced the Google Analytics API, including the basic usage. In this part, we will continue creating our demo and see how we can extend it with more functionality.

在本系列的第一部分中,我们介绍了Google Analytics(分析)API,包括基本用法。 在这一部分中,我们将继续创建演示并查看如何使用更多功能对其进行扩展。

Google Analytics API (Google Analytics API)

管理API (Management API)

As we discussed in the first part, the Management API is responsible for getting user accounts, properties, views… for our first example we will retrieve the list of accounts available for our authenticated user.

正如我们在第一部分中讨论的那样,Management API负责获取用户帐户,属性,视图……对于我们的第一个示例,我们将检索可用于已认证用户的帐户列表。

// app/src/GA_Service.php
public function accounts(){
	if( !$this->isLoggedIn() ){
		//login
	}
	
	$service = new Google_AnalyticsService($this->client);
	$man_accounts = $service->management_accounts->listManagementAccounts();
	$accounts = [];

	foreach ($man_accounts['items'] as $account) {
		$accounts[] = [ 'id' => $account['id'], 'name' => $account['name'] ];
	}

	return $accounts;
}//accounts

// app/controllers/HomeController.php
public function accounts(){
	$accounts = $this->ga->accounts();

	return $accounts;
}//accounts

// app/routes.php
Route::get('/accounts', 'aaa@qq.com');

Inside GA_Service::accounts we create a new Google_AnalyticsService with our authorized client and then query the API for the list of accounts.

GA_Service::accounts内部,我们使用授权的客户端创建了一个新的Google_AnalyticsService ,然后在API中查询帐户列表。

In this case the result is an array, but the API also makes use of objects, we just need to specify that inside our GA_Service::init function. In the following examples, I’m going to use array results.

在这种情况下,结果是一个数组,但是API也使用了对象,我们只需要在GA_Service::init函数中指定该对象即可。 在以下示例中,我将使用数组结果。

$this->client->setUseObjects(true);

The listManagementAccounts function returns an array containing:

listManagementAccounts函数返回一个包含以下内容的数组:

{
    kind: "analytics#accounts",
    username: "aaa@qq.com",
    totalResults: 3,
    startIndex: 1,
    itemsPerPage: 1000,
    items: [
        {
            id: "4449308",
            kind: "analytics#account",
            selfLink: "https://www.googleapis.com/analytics/v3/management/accounts/4449308",
            name: "aaa@qq.com",
            permissions: {
                effective: [
                    "COLLABORATE",
                    "EDIT",
                    "MANAGE_USERS",
                    "READ_AND_ANALYZE"
                ]
            },
            created: "2013-10-01T11:04:28.478Z",
            updated: "2013-10-01T11:04:28.478Z",
            childLink: {
                type: "analytics#webproperties",
                href: "https://www.googleapis.com/analytics/v3/management/accounts/4449308/webproperties"
            }
        }
    ]
}

Note that when you return an array as a response, Laravel automatically encodes the result as a JSON response and sends it to the browser.

请注意,当您返回数组作为响应时,Laravel会自动将结果编码为JSON响应,并将其发送到浏览器。

The result contains information about the total results and some pagination info as well. The items column contains the list of accounts with their IDs, permissions, etc., but we looped through items to extract only the id and name from the accounts.

结果包含有关总结果的信息以及一些分页信息。 items列包含具有其ID,权限等的帐户列表,但是我们循环浏览items以仅从帐户中提取idname

If you would like to have result pagination, you can always pass more options to listManagementAccount:

如果您希望进行结果分页,则始终可以将更多选项传递给listManagementAccount

$service->management_accounts->listManagementAccounts( [ 'max-results' => $max_results, 'start-index' => $start_index ] );

Let’s assume that we’re going to show our users their list of accounts, and when they select one, we load the list of properties associated with it.

假设我们要向用户显示其帐户列表,并且当他们选择一个帐户时,我们将加载与其关联的属性列表。

// app/src/GA_Service.php
public function properties( $account_id ){
	if( !$this->isLoggedIn() ){
		//login
	}

	try {
		$service = new Google_AnalyticsService($this->client);
		$man_properties = $service->management_webproperties->listManagementWebproperties($account_id);
		$properties = [];

		foreach ($man_properties['items'] as $property) {
			$properties[] = [ 'id' => $property['id'], 'name' => $property['name'] ];
		}//foreach

		return json_encode($properties);
	} catch (Google_ServiceException $e) {
		return Response::json([
			'status'	=> 0,
			'code'		=> 3,
			'message'	=> $e->getMessage()
		]);
	}//catch

}//properties

// app/controllers/HomeController.php
public function properties( $account_id ){
	$properties = $this->ga->properties( $account_id );

	return $properties;
}//properties
	
	
// app/routes.php
Route::get( '/properties/{account_id}', [ 'uses' => 'aaa@qq.com' ] )->where('account_id', '\d+');

The GA_Service::properties accepts an account ID, and returns the list of properties for that account. We basically have the same process, like retrieving accounts.

GA_Service::properties接受一个帐户ID,并返回该帐户的属性列表。 我们基本上有相同的过程,例如取回帐户。

[
    {
        id: "UA-52317977-1",
        name: "Prop1"
    },
    {
        id: "UA-52317977-2",
        name: "Prop1"
    }
]

Every property has a subset of views. By default, Google adds a view called All Web Site Data for every new property.

每个属性都有一个视图子集。 默认情况下,Google为每个新属性添加一个称为“ All Web Site Data的视图。

Using an ID from the list of properties and the account ID grabbed from the first part, we will query Google Analytics API for the list of available views for a given account property.

使用属性列表中的ID和第一部分中获取的帐户ID,我们将查询Google Analytics(分析)API,以获取给定帐户属性的可用视图列表。

// app/src/GA_Service.php
public function views( $account_id, $property_id ){
	if( !$this->isLoggedIn() ){
			//login
	}
		
	try {
		$service = new Google_AnalyticsService($this->client);
		$man_views = $service->management_profiles->listManagementProfiles( $account_id, $property_id );
		$views = [];

		foreach ($man_views['items'] as $view) {
			$views[] = [ 'id' => $view['id'], 'name' => $view['name'] ];
		}//foreach

		return json_encode($views);
	} catch (Google_ServiceException $e) {
		return Response::json([
			'status'	=> 0,
			'code'		=> 3,
			'message'	=> $e->getMessage()
		]);
	}//catch
}//views

// app/controllers/HomeController.php
public function views( $account_id, $property_id ){
	$views = $this->ga->views( $account_id ,$property_id );

	return $views;
}//properties
	
// app/routes.php
Route::get( '/views/{account_id}/{property_id}', [ 'uses' => 'aaa@qq.com' ] )->where([ 'account_id', '\d+', 'property_id', '\d+' ]);

In the browser, when hitting /views/{account_id}/{property_id} route, we should get something similar to:

在浏览器中,当点击/views/{account_id}/{property_id}路由时,我们应该得到类似于以下内容的信息:

// http://localhost:8000/views/44493065/UA-44493083

[
 {
    id: "77278619",
    name: "All Web Site Data"
 }
]

元数据API (Metadata API)

To query some statistics from Google Analytics we need to provide a set of dimensions and metrics.

要从Google Analytics(分析)中查询一些统计信息,我们需要提供一组维度和指标。

  • Metrics: metrics are the individual measurements of user activity on your property, such as sessions and pageviews..

    指标:指标是您对媒体资源中用户活动(例如会话和综合浏览量)的单独测量。
  • Dimensions: dimensions break down metrics across some common criteria, such as country or browser.

    维度:维度可以按照一些常见标准(例如国家/地区或浏览器)细分指标。

To grab the list of available metadata you can simply use curl to query data from the following url https://www.googleapis.com/analytics/v3/metadata/ga/columns.

要获取可用元数据的列表,您只需使用curl即可从以下网址https://www.googleapis.com/analytics/v3/metadata/ga/columns查询数据。

Google Analytics gives us an etag attribute that can be used for caching the response so that we don’t have to query the API on every request.

Google Analytics(分析)为我们提供了一个etag属性,该属性可用于缓存响应,因此我们不必在每次请求时都查询API。

$gcurl = new Google_CurlIO;
$response = $gcurl->makeRequest( 
    			new Google_HttpRequest(
    			    "https://www.googleapis.com/analytics/v3/metadata/ga/columns" 
    		));
  • Google_CurlIO: a class wrapped with some curlutilities for dealing with caching, authentication, etc – by using this class we ensure the response is cached using the etagattribute.

    Google_CurlIO :一个包装有一些curl工具的类,用于处理缓存,身份验证等-通过使用此类,我们确保使用etag属性缓存响应。

  • Google_HttpRequest: is a class representing a single HTTP request.

    Google_HttpRequest :是表示单个HTTP请求的类。

The makeRequest method returns a Google_HttpRequest instance, and we can use the getResponseBody to get our metadata response.

makeRequest方法返回一个Google_HttpRequest实例,我们可以使用getResponseBody让我们的元数据响应。

// app/src/GA_Service.php

public function metadata(){
	$gcurl = new Google_CurlIO;
	$response = $gcurl->makeRequest( 
		new Google_HttpRequest( "https://www.googleapis.com/analytics/v3/metadata/ga/columns" ) 
	);

	//verify returned data
	$data = json_decode($response->getResponseBody());
	
	$items = $data->items;
	$data_items = [];
	$dimensions_data = [];
	$metrics_data = [];

	foreach( $items as $item ){
		if( $item->attributes->status == 'DEPRECATED' )
			continue;

		if( $item->attributes->type == 'DIMENSION' )
			$dimensions_data[ $item->attributes->group ][] = $item;

		if( $item->attributes->type == 'METRIC' )
			$metrics_data[ $item->attributes->group ][] = $item;
	}//foreach

	$data_items['dimensions'] = $dimensions_data;
	$data_items['metrics'] = $metrics_data;

	return $data_items;
}//metadata

// app/controllers/HomeController.php
public function metadata(){
	$metadata = $this->ga->metadata();

	return $metadata;
}//metadata
	
// app/routes.php
Route::get('/metadata', 'aaa@qq.com');

Now, when accessing the /metadata route in your browser you should get an array of dimensions and another one for metrics, and each one of them contains a list of grouped elements.

现在,在浏览器中访问/metadata路由时,您应该获得一个维度数组和另一个维度指标,并且每个维度都包含一组分组元素。

{
dimensions: {
    User: [
        {
            id: "ga:userType",
            kind: "analytics#column",
                attributes: {
                type: "DIMENSION",
                dataType: "STRING",
                group: "User",
                status: "PUBLIC",
                uiName: "User Type",
                description: "A boolean indicating if a user is new or returning. Possible values: New Visitor, Returning Visitor.",
                allowedInSegments: "true"
                }
        },
        ...
    ]
},
metrics: {
    ...
    }
}

To speed up the process we will use bootsnipp. If the user is logged in, we will show the home page.

为了加快该过程,我们将使用bootsnipp 。 如果用户已登录,我们将显示主页。

将Google Analytics API v3与PHP结合使用:获取数据

We need to update our aaa@qq.com to show the home page view.

我们需要更新aaa@qq.com以显示主页视图。

// app/controllers/HomeController.php
public function index(){
    if( $this->ga->isLoggedIn() ){
    	$metadata = $this->metadata();
    	$dimensions = $metadata['dimensions'];
    	$metrics = $metadata['metrics'];
    	
    	return View::make('home', [ 
    	    'dimensions' => $dimensions, 
    	    'metrics' => $metrics 
        ]);
    }//if
    else{
    	$url = $this->ga->getLoginUrl();
    	return View::make('login', [ 'url' => $url ]);
    }
}//index

As you can see from the screenshot, when the user selects an account we asynchronously change the property and the view accordingly. To achieve that, I wrote some simple JS which you can check in the final repo.

从屏幕截图中可以看到,当用户选择一个帐户时,我们会异步更改属性和视图。 为此,我编写了一些简单的JS,您可以在最终的repo中进行检查。

报表API (Reporting API)

By providing the selected view, metrics and dimensions we can get detailed statistics about users and interactions. The result after the user submission will be something similar to:

通过提供选定的视图,指标和维度,我们可以获得有关用户和互动的详细统计信息。 用户提交后的结果将类似于:

array(3) {
  ["items"]=>
  array(10) {
    [0]=>
    array(2) {
      [0]=>
      string(9) "Argentina"
      [1]=>
      string(1) "2"
    }
    [1]=>
    array(2) {
      [0]=>
      string(6) "Brazil"
      [1]=>
      string(2) "31"
    }
    [2]=>
    array(2) {
      [0]=>
      string(6) "France"
      [1]=>
      string(1) "1"
    }
    [3]=>
    array(2) {
      [0]=>
      string(7) "Germany"
      [1]=>
      string(1) "1"
    }
    [4]=>
    array(2) {
      [0]=>
      string(6) "Greece"
      [1]=>
      string(1) "1"
    }
    //...
  }
  ["columnHeaders"]=>
  array(2) {
    [0]=>
    array(3) {
      ["name"]=>
      string(10) "ga:country"
      ["columnType"]=>
      string(9) "DIMENSION"
      ["dataType"]=>
      string(6) "STRING"
    }
    [1]=>
    array(3) {
      ["name"]=>
      string(12) "ga:pageviews"
      ["columnType"]=>
      string(6) "METRIC"
      ["dataType"]=>
      string(7) "INTEGER"
    }
  }
  ["totalResults"]=>
  int(15)
}

Our GA_Service::report accepts four arguments: a view ID, a start and end date and an array of metrics.

我们的GA_Service::report接受四个参数:视图ID,开始日期和结束日期以及一组指标。

Google can’t return all your legacy data – instead we provide a start and end date. In my example, I queried the last month’s results.

Google无法返回您所有的旧数据-相反,我们提供了开始日期和结束日期。 在我的示例中,我查询了上个月的结果。

The third parameter is the list of metrics which we already have from the user selection.

第三个参数是我们已经从用户选择中获得的指标列表。

The fourth optional parameter is an array of options. – max-results: the maximum number of results. (we used 10 to speed up the response). – dimensions: a comma separated list of values. (ga:country,ga:city) – filters: a comma separated list of rules to be appilied to the result .(ga:country!=usa,ga:pageviews>100) In this example we excluded USA from the list of dimensions and only showed pageviews that are greater than 100. – segment: advanced segment ID to be applied to the data. – sort: order results by dimensions or metrics. Can combine multiple dimensions and metrics. (ga:country,-ga:pageviews = order by ga:country ascending, and by ga:pageviews descending. – start-index: can be used for pagination.

第四个可选参数是选项数组。 – max-results :最大结果数。 (我们使用10来加快响应速度)。 – dimensions :用逗号分隔的值列表。 ( ga:country,ga:city )– filters :以逗号分隔的规则列表,适用于该结果。( ga:country!=usa,ga:pageviews>100 )在此示例中,我们从维度列表中排除了USA并且只显示了大于100的综合浏览量。– segment :要应用于数据的高级细分ID。 – sort :按维度或指标sort结果进行sort 。 可以结合多个维度和指标。 ( ga:country,-ga:pageviews = ga:country升序, ga:pageviews降序。– start-index :可用于分页。

// app/src/GA_Service.php

public function report( $view, $dimensions, $metrics ){
	// to make the request quicker
	$max_results = 10;
	
	// query the last month analytics
	$now = new DateTime();
	$end_date = $now->format('Y-m-d');
	$start_date = $now->modify('-1 month')->format('Y-m-d');

	// if( !is_array( $dimensions ) )
	// 	$dimensions = array( $dimensions );

	$dimensions = implode( ",", $dimensions );
	$metrics = implode( ",", $metrics );

	try{
		$analytics = new Google_AnalyticsService($this->client);
		$options = [];

		$options['dimensions'] = $dimensions;
		$options['max-results'] = $max_results;

		$data = $analytics->data_ga->get( $view, $start_date, $end_date, $metrics,
			$options
		);

		$res = [
			'items' => isset($data['rows']) ? $data['rows'] : [],
			'columnHeaders'	=> $data['columnHeaders'],
			'totalResults'	=> $data['totalResults']
		];

	}catch( Google_ServiceException $ex ){
		return Response::json([
			'status'	=> 0,
			'code'		=> 2,
			'message'	=> 'Google analytics internal server error: (Technical details) ' . $ex->getErrors()[0]['message']
		]);
	}//catch

	return $res;
}//report

// app/controller/HomeController.php
public function report(){
	if( !$this->ga->isLoggedIn() )
		return Response::json([
			'status'	=> 0,
			'code'		=> 1,
			'message'	=> 'Login required'
		]);

	if( !Input::has('dimensions') || !Input::has('metrics') || !Input::has('view') )
		return Response::json([
			'status'	=> 0,
			'code'		=> 1,
			'message'	=> 'Invalid request parametter'
		]);

	$view = 'ga:' . Input::get('view');
	$dimensions = Input::get('dimensions');
	$metrics = Input::get('metrics');

	$report = $this->ga->report( $view, $dimensions, $metrics );

	return View::make('report', [ 'columns' => $report['columnHeaders'], 'items' => $report['items'], 'totalResults' => $report['totalResults' ] ]);
}//metadata

// app/routes.php
Route::post('/report', 'aaa@qq.com');

After calling the get Google_AnalyticsService::get method, we use the list of result items, column headers, and total results to output the result as a table.

调用get Google_AnalyticsService::get方法后,我们使用结果项列表,列标题和总计结果将结果输出为表格。

将Google Analytics API v3与PHP结合使用:获取数据

扩展演示 (Extending The Demo)

Now let’s see how we can extend our demo with filters, sorting and segments.

现在,让我们看看如何使用过滤器,排序和细分来扩展我们的演示。

筛选器 (Filters)

Filters are a way to exclude some data from the returned result. They take the following form:

过滤器是一种从返回结果中排除某些数据的方法。 它们采用以下形式:

ga:column operator value
  • ga:column: dimension or metric id (Ex: ga:country)

    ga:column :维度或指标ID(例如ga:country )

  • operator: the operator depends on the choice of metric or dimension column id, check the docs for the list of operators.

    operator :运算符取决于指标或维度列ID的选择,请在docs中查看运算符列表。

  • value: the value can be a number, a string, or a regex.

    value :值可以是数字,字符串或正则表达式。

You can combine multiple filters: you can use comma (,) as an OR operator and a semi-colon (;) as an AND operator.

您可以组合多个过滤器:可以将逗号(,)用作OR运算符,可以将分号(;)用作AND运算符。

区隔 (Segments)

By default Google Analytics group all your data in one group called All Sessions. However, you can always choose from the built in segments or create a new one depending on your needs. You can group data by referral, device type, age, gender, etc.

默认情况下,Google Analytics(分析)会将您的所有数据All Sessions为一个名为“ All Sessions组。 但是,您始终可以根据需要从内置细分中选择或创建一个新细分。 您可以按引荐,设备类型,年龄,性别等对数据进行分组。

You can extend the demo by adding a new select element with the available segment list, and pass the ID to the get method as discussed previously.

您可以通过使用可用的细分列表添加新的select元素来扩展演示,并将ID传递给get方法,如前所述。

// app/src/GA_Service.php
public function segments(){
	if( !$this->isLoggedIn() ){
		//login
	}

	$service = new Google_AnalyticsService($this->client);
	$segments = $service->management_segments->listManagementSegments();

	return $segments;
}//segments

// app/controllers/HomeController.php

public function segments(){
	$segments = $this->ga->segments();

	return $segments;
}//segments

// app/routes.php

Route::get('/segments', 'aaa@qq.com');

You can visit the /segments page to see the list of available segments with their IDs, and you can of course use this as an option as we saw earlier.

您可以访问/segments页面,以查看具有ID的可用细分的列表,当然,可以像我们之前看到的那样使用它作为选项。

结语 (Wrapping up)

The Google Analytics API is very flexible and provides a lot of features, but the documentation is not complete yet, and doesn’t provide good examples of use. You get a lot more by digging into the source code and testing possibilities and limits.

Google Analytics(分析)API非常灵活,并提供了许多功能,但是文档还不完整,并且没有提供很好的使用示例。 通过深入研究源代码并测试可能性和限制,您可以获得更多收益。

In this series, we focused on the basic usage of Google Analytics, but you can extend the demo with options from the Google Analytics dashboard.

在本系列中,我们重点介绍了Google Analytics(分析)的基本用法,但是您可以使用Google Analytics(分析)仪表板中的选项扩展演示。

You can check the final repo for the source code of this tutorial.

您可以检查最终存储以获取本教程的源代码。

Questions? Comments? Let me know!

有什么问题吗 注释? 让我知道!

翻译自: https://www.sitepoint.com/using-google-analytics-api-v3-php-fetching-data/