谷歌oauth2得到用户详细信息不工作和挂起PHP

时间:2014-03-14 05:35:48

标签: php oauth-2.0

我从php sdk中包含的测试文件夹中复制了这个。它会按预期重定向到Google进行身份验证,但在调用$oauth2->userinfo->get()时,它会挂起。云控制台说错误是400 ,但我不知道我可能做错了什么。

我根据页面上的内容更新了设置。我已经找了2个小时的答案。请帮忙:(

        /* OAuth settings */
        $clientID = 'blahblah.apps.googleusercontent.com';
        $clientSecret = 'secret';
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        $developerKey = 'key';

        $client = new Google_Client();
        $client->setApplicationName("Study-Corner");
        $client->setClientId($clientID);
        $client->setClientSecret($clientSecret);
        $client->setRedirectUri($redirect);
        $client->setDeveloperKey($developerKey);
        $oauth2 = new Google_Oauth2Service($client);

        if(isset($_GET['code'])) {
            $client->authenticate($_GET['code']);

            // get the access token
            $_SESSION['token'] = $client->getAccessToken();

            // redirect back
            header('Location: '. filter_var($redirect, FILTER_SANITIZE_URL));
            return;
        }

        if(isset($_SESSION['token'])) {
            // set the access token
            $client->setAccessToken($_SESSION['token']);
        }

        /* check if we have access */
        if($client->getAccessToken()) {
            $user = $oauth2->userinfo->get();

            // These fields are currently filtered through the PHP sanitize filters.
            // See http://www.php.net/manual/en/filter.filters.sanitize.php
            $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
            $img = filter_var($user['picture'], FILTER_VALIDATE_URL);

            print $email;

            // The access token may have been updated lazily.
            $_SESSION['token'] = $client->getAccessToken();
        } else {
            $authUrl = $client->createAuthUrl();
            header("Location: ".$authUrl);
            die;
        }

1 个答案:

答案 0 :(得分:0)

$client->setScopes('profile);添加到您的客户详细信息中。