首页 文章

Google Analytics报告Api - PHP:添加用户帐户

提问于
浏览
0

What I want to do

  • 让我的网络应用程序的用户与该应用共享他们的分析帐户 .

  • 将用户重定向到Google身份验证,要求他们批准访问权限

  • 将用户重定向回应用程序 .

  • 根据用户的分析数据和数据为用户生成报告 .

  • 下次用户将生成他们的报告时,我不想再要求他们进行日志记录 .

Where the problem is

我读了这个Google developers PHP guide . 但是,示例代码连接到已与应用共享的第一个帐户 .

我希望看到一段代码,询问用户的凭据,从而提供对其帐户的访问权限 .

在堆栈上我已经找到了这个答案Service Applications and Google Analytics API V3: Server-to-server OAuth2 authentication? . 但是,提到的APP_EMAIL不是特定用户的电子邮件,而是在控制台中创建的应用程序的developer.gserviceaccount.com标识 .

我也找到了这个帖子Google Analytics Core Reporting API Version 3.0 without client login . 似乎在那里解决了类似的主题,但代码的重要部分(从我的角度来看)在那里缺失 .

1 回答

  • 1

    首先,确保通过设置访问类型获取刷新令牌以使其脱机 . 然后创建一个单独的页面进行报告 . 对于所有报告,单独的页面应使用帐户ID和刷新令牌,如果它在令牌上给您一个错误,您可以自己刷新它,或将它们发送回登录页面 .

    您只需要申请一次凭证,即可访问所有帐户 . php指南仅使用第一个帐户,但您可以遍历所有帐户并获得更多

    $client = new Google_Client();
    $client->setAuthConfig(__DIR__ . '/creds/client_secrets.json');
    $client->setIncludeGrantedScopes(true);
    $client->setAccessType("offline");
    $client->setApprovalPrompt('force');
    $client->addScope(Google_Service_Analytics::ANALYTICS_EDIT);
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
    
    // If the user has already authorized this app then get an access token
    // else redirect to ask the user to authorize access to Google Analytics.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);
            // Create an authorized analytics service object.
            $analytics = new Google_Service_Analytics($client);
            $accounts=getAccountIds($analytics);
            foreach($accounts as $acc)
            {
             var_dump($acc);
    }
    }
    else {
            $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    

相关问题