laravel - Google AnalyticsAPI身份验证

时间:2016-07-08 23:41:24

标签: php api laravel google-analytics laravel-socialite

我正在尝试创建一个网络应用,其中包含一个简单的信息中心,其中包含使用Google登录的帐户的Google Analytics数据。我正在使用Laravel和Socialite包,我现在可以使用Google登录用户。我有我的开发人员客户端密钥和客户端密钥。我为Analytics只读和离线访问设置了范围,我在我的数据库中存储了客户名称,电子邮件,Google ID,访问令牌和刷新令牌。我可以毫无问题地登录用户。

我现在要做的是,只需访问Google Analytics帐户目前拥有的个人资料。我遵循了Analytics API文档示例,但无法使其正常运行。由于我正在存储访问令牌和刷新令牌,我认为我应该能够对当前用户进行身份验证并获取他们的Google Analytics数据,但我找不到客户端和Google Analytics库中的任何简单方法。我需要离线访问他们的Analytics数据,这就是为什么我认为我应该能够使用访问令牌和刷新令牌授权我的请求,但是我没有从用户登录过程中获取任何特定于Analytics的数据。我现在完全迷失了,如何授权我对Anayltics API的请求?我使用AdWords API的时间已超过8个月,而且AdWords API文档中的所有内容都非常清晰,但我无法使用Analytics API。

这些是我的用户登录方法:

public function redirectToProvider()
{
    $parameters = ['access_type' => 'offline'];
    return Socialite::driver('google')
        ->scopes(['https://www.googleapis.com/auth/analytics.readonly'])
        ->with($parameters)
        ->redirect();
}

/**
 * Obtain the user information from Google.
 *
 * @return Response
 */
public function handleProviderCallback()
{
    $outsiderLogin = Socialite::driver('google')->stateless()->user();


    $user = User::where('googleID', $outsiderLogin->id)->first();

    // Register the user if there is no user with that id.
    if (!$user) {
        $user = new User;
        $user->name         = $outsiderLogin->name;
        $user->googleID     = $outsiderLogin->id;
        $user->email        = $outsiderLogin->email;
        $user->token        = $outsiderLogin->token;
        $user->refreshToken = $outsiderLogin->refreshToken;
        $user->save();
    }
    // Log the user in.
    Auth::login($user);

    return redirect('/home');
}

非常感谢。

3 个答案:

答案 0 :(得分:4)

我现在找到了解决方案。起初,我认为我需要使用来自Google的身份验证网址返回的代码,当我检查Socialite包时,我在getCode()中找到了一个受保护的方法\vendor\laravel\socialite\src\Two\AbstractProvider.php,它返回了来自URL。我编辑了包的源文件,并将方法类型从protected更改为public,这使得可以在类之外使用该方法,这允许我从URL访问代码,然后将其存储在DB中以进一步验证要求。但是这个设置存在问题,首先,我应该找到一种方法来保持该包没有任何更新,因为任何更新都将回滚我对源文件所做的更改。我遇到的第二个问题是我存储令牌的方式。默认情况下,Google Client API会返回一个数组,其中包含字段access_tokenrefresh_tokenexpires_inidcreated,并且对这些字段进行身份验证对Analytics服务器的请求。在我的场景中,没有从基本的Socialite登录过程返回的标准数组。有access_tokenrefresh_tokenexpires变量,我也将它们全部存储在我的数据库中。这导致了谷歌库的一个问题,它要求一个结构化数组,我甚至没有变量expires_increated,这就是为什么我设置一个假数组,告诉谷歌每次刷新令牌请求,这也不是一个好习惯。

最后,我无法理解如何在线使用任何包,我编写了自己的简单身份验证,我不知道它是否有任何漏洞,但它对我有用,它也适用于那些需要的人它

以下是我的路线:

Route::get('auth/google', [
            'as' => 'googleLogin',   
            'uses' => 'Auth\AuthController@redirectToProvider'
]);
Route::get('auth/google/callback', [
            'as' => 'googleLoginCallback',   
            'uses' => 'Auth\AuthController@handleProviderCallback'
]);

这些是AuthController方法:

/**
 * Redirect the user to the Google authentication 
 */
public function redirectToProvider()
{
    // Create the client object and set the authorization configuration from JSON file.
    $client = new Google_Client();
    $client->setAuthConfig('/home/vagrant/Analytics/client_secret.json');
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/auth/google/callback');
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
    $client->addScope("email");
    $client->addScope("profile");
    $client->setAccessType("offline");

    $auth_url = $client->createAuthUrl();
    return redirect($auth_url);

}

/**
 * Obtain the user information from Google.
 *
 * @return redirect to the app.
 */
public function handleProviderCallback()
{
    // Handle authorization flow from the server.
    if (! isset($_GET['code'])) {
        return redirect('auth/google');
    } else {

        // Authenticate the client, and get required informations.
        $client = new Google_Client();
        $client->setAuthConfig('/home/vagrant/Analytics/client_secret.json');
        $client->authenticate($_GET['code']);

        // Store the tokens in the session.
        Session::put('token', $client->getAccessToken());

        $service = new Google_Service_Oauth2($client);
        $userInfo = $service->userinfo->get();

        $user = User::where('googleID', $userInfo->id)->first();

        // If no match, register the user.
        if(!$user) {
            $user = new User;
            $user->name = $userInfo->name;
            $user->googleID = $userInfo->id;
            $user->email = $userInfo->email;
            $user->refreshToken = $client->getRefreshToken();
            $user->code = $_GET['code'];
            $user->save();
        }

        Auth::login($user);
        return redirect('/home');
    }

}

我已将从Google API控制台下载的client_secret.json文件放入指定的文件夹,这可能与您有所不同。我还修改了迁移文件以匹配所需的segemnts。完成这些步骤后,我可以对待该用户,因为它是一个使用基本Laravel身份验证注册的简单用户。

现在我可以查询用户的Google Analytics帐户中的帐户,如下所示:

/**
 * @var $client to be authorized by Google.
 */
private $client;

/**
 * @var $analytics Analytics object to be used.
 */
private $analytics;

public function __construct()
{
    $this->client = $this->AuthenticateCurrentClient();
    $this->analytics = new Google_Service_Analytics($this->client);
}

private function AuthenticateCurrentClient(){
    $user = Auth::user();
    $token = Session::get('token');

    // Authenticate the client.
    $client = new Google_Client();
    $client->setAccessToken($token);
    $client->authenticate($user->code);
    return $client;
}

public function GetAccounts(){

    try {
        $accountsObject = $this->analytics->management_accounts->listManagementAccounts();
        $accounts = $accountsObject->getItems();

        return $accounts;

    } catch (apiServiceException $e) {
        print 'There was an Analytics API service error '
            . $e->getCode() . ':' . $e->getMessage();

    } catch (apiException $e) {
        print 'There was a general API error '
            . $e->getCode() . ':' . $e->getMessage();
    }

}
已经有数千次Stack Overflow帮助了我,我希望这可以帮助别人让事情发挥作用。

答案 1 :(得分:2)

你不是真的会找到你想要的Laravel附带的社交网络包(它更多地用于登录,而且就是关于它)。

您可以找到许多Google Analytic软件包(以及许多其他Laravel软件包),这些软件包可以帮助您进行API调用:

http://packalyst.com/s/google%20analytics

更具体地说,这个包:https://github.com/spatie/laravel-analytics

那,或者运行你自己的Guzzle和cURL脚本。当我需要快速的东西而不构建完整的API时,我会使用Guzzle。

然而,这里有一篇关于使用Socialite访问GA数据的有趣帖子。但你很有限。如果您正在创建用户驱动的仪表板,我会选择单独的包。

https://laracasts.com/discuss/channels/tips/how-i-made-google-analytics-work-with-socialite

答案 2 :(得分:0)

我也在尝试做同样的事情。到目前为止,我已经使用oAuth 2.0和Socialite包进行了用户身份验证。我需要从GA获取的网站列表。我完全被困在那里。如果你可以指导我如何继续前进,那真的很棒。