Google Analytics Reporting API V4 开发之笔记 star.Hou

参考google开发者官网api文档:https://developers.google.com/analytics/devguides/reporting/core/v4/samples
step 1:
凭证授权:
创建凭据

打开“凭据”页面。
点击创建凭据并选择 OAuth 客户端 ID
对于应用类型,选择网络应用。
命名客户端 ID 快速入门,并点击创建。
将“已获授权的 JavaScript 来源”留空,因为本教程不需要该内容。
将“已获授权的重定向 URI”设置为 http://localhost:8080/oauth2callback.php。
点击创建。

从“凭据”页点击进入新创建的客户端 ID,然后点击下载 JSON,并将其另存为 client_secrets.json;在本教程的后面,您将需要用到该 JSON。
step 2:
安装google客户端:

composer require google/apiclient:^2.0

step 3:

        require_once base_path() . '/vendor/autoload.php';
        $KEY_FILE_LOCATION = base_path('public') . '/client_secrets.json';
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName("pageviews");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
        $analytics = new \Google_Service_AnalyticsReporting($client);


        //请求数据
        $VIEW_ID = "ga:xxxxxx";
        // Create the DateRange object:日期对象设置
        $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
        $dateRange->setStartDate('7daysAgo');
        $dateRange->setEndDate('yesterday');

        // Create the Metrics object:指标对象设置
        $pageviews = new \Google_Service_AnalyticsReporting_Metric();
        $pageviews->setExpression("ga:sessions");
        $pageviews->setAlias("sessions");

        //Create the Dimensions object:维度对象设置
        $browser = new \Google_Service_AnalyticsReporting_Dimension();
        $browser->setName("ga:landingPagePath");
        //查询字段排序对象设置
        $orderby = new \Google_Service_AnalyticsReporting_OrderBy();
        $a = $orderby->getOrderType();
        $orderby->setFieldName("ga:sessions");

        // Create the ReportRequest object:报告请求对象设置,传入查询对象
        $request = new \Google_Service_AnalyticsReporting_ReportRequest();
        $request->setViewId($VIEW_ID);
        $request->setDateRanges($dateRange);
        $request->setMetrics(array($pageviews));
        $request->setDimensions(array($browser));
        $request->setOrderBys($orderby);
        $request->setPageSize(2500);
        //设置过滤表达式
        $request->setFiltersExpression('ga:landingPagePath=~/xxxxxx');

        $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
        $body->setReportRequests( array( $request) );
        $data = $analytics->reports->batchGet( $body );
        $data_new = $this->printResults($data);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值