使用OAuth 2.0无法连接网站管理员工具?

时间:2013-10-28 11:14:28

标签: php oauth-2.0 google-webmaster-tools

我设法通过Oauth 2与Google Analytics进行连接,但无法通过网站管理员工具找到解决方法。 我在以下网址获得了网站管理员工具的“范围”:https://developers.google.com/oauthplayground/

我在这里使用代码: https://code.google.com/p/google-api-php-client/

但是我无法工作。如果有人能指导我,我将不胜感激。

PS:今年5月XD

1 个答案:

答案 0 :(得分:0)

以下代码将有助于通过Oauth Flow获取访问令牌和刷新令牌以进行网站管理员工具API访问

确保您在API控制台中提到的重定向Uri应与放置以下代码的文件名相同。

例如。如果重定向uri为:-somesitename.com/google_oauth.php(使用http://或https://),则应将以下脚本放入: - google_oauth.php(路径:somesitename.com/google_oauth.php(带有http://或https://))

<?php

    $OAuth = array(
        'oauth_uri' => 'https://accounts.google.com/o/oauth2/auth',
        'client_id' => '#clientId',
        'client_secret' => '#clientSecret',
        'access_type' => 'offline',
        'redirect_uri' => 'http://somesite.com/google_oauth.php',   //this url should be same as you had registered in your api console as redirect uri()
        'oauth_token_uri' => 'https://accounts.google.com/o/oauth2/token'

    );
    $token = array(
        'access_token' => '',
        'token_type' => '',
        'expires_in' => '',
        'refresh_token' => ''
    );

    $title = 'No Code';
    $AuthCode = 'Null';

    // see if error parameter exisits
    $error = _get_url_param($_SERVER['REQUEST_URI'], 'error');
    if ($error != NULL)
    {   // this means the user denied api access to GWMTs
        $title = $error;
    }
    else
    {   // does the code parameter exist?
        $AuthCode = _get_url_param($_SERVER['REQUEST_URI'], 'code');
        if ($AuthCode == NULL)
        {   // get authorization code
            $OAuth_request = _formatOAuthReq($OAuth, "https://www.google.com/webmasters/tools/feeds/");

            header('Location: ' . $OAuth_request);
            exit; // the redirect will come back to this page and $code will have a value
        }
        else
        {
            $title = 'Got Authorization Code';
            // now exchange Authorization code for access token and refresh token
            $token_response = _get_auth_token($OAuth, $AuthCode);
            $json_obj = json_decode($token_response);
            $token['access_token'] = $json_obj->access_token;
            $token['token_type'] = $json_obj->token_type;
            $token['expires_in'] = $json_obj->expires_in;
            $token['refresh_token'] = $json_obj->refresh_token;
            echo 'access_token = ' . $json_obj->access_token;
        }
    }

    function _get_auth_token($params, $code)
    {
        $url = $params['oauth_token_uri'];

        $fields = array(
            'code' => $code,
            'client_id' => $params['client_id'],
            'client_secret' => $params['client_secret'],
            'redirect_uri' => $params['redirect_uri'],
            'grant_type' => 'authorization_code'
        );
        $response = _do_post($url, $fields);
        return $response;
    }

    function _do_post($url, $fields)
    {
        $fields_string = '';

        foreach ($fields as $key => $value)
        {
            $fields_string .= $key . '=' . $value . '&';
        }
        $fields_string = rtrim($fields_string, '&');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    function _formatOAuthReq($OAuthParams, $scope)
    {
        $uri = $OAuthParams['oauth_uri'];
        $uri .= "?client_id=" . $OAuthParams['client_id'];
        $uri .= "&redirect_uri=" . $OAuthParams['redirect_uri'];
        $uri .= "&scope=" . $scope;
        $uri .= "&response_type=code";
        $uri .= "&access_type=offline";


        return $uri;
    }

    function _get_url_param($url, $name)
    {
        parse_str(parse_url($url, PHP_URL_QUERY), $params);
        return isset($params[$name]) ? $params[$name] : null;
    }

    function _get_refresh_token($params, $code)
    {
        $url = $params['oauth_token_uri'];

        $fields = array(
            'code' => $code,
            'client_id' => $params['client_id'],
            'client_secret' => $params['client_secret'],
            'refresh_token' => $token['refresh_token'],
            'grant_type' => 'refresh_token'
        );
        $response = _do_post($url, $fields);
        return $response;
    }
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title><?= $title; ?></title>
        </head>
        <body>
            <h1>OAuth2 Authorization Code</h1>
            <p>Authorization Code: <?= $AuthCode; ?></p>
            <p>access token: <?= $token['access_token']; ?></p>
            <p>expires in: <?= $token['expires_in']; ?></p>
            <p>refresh token: <?= $token['refresh_token']; ?></p>
            <p></p>

        </body>
    </html>

然后,您可以使用此令牌向网站管理员工具API查询数据。

此外,您可以使用与Oauth分析访问权限相同的代码,只需在您查询网站管理员工具时用于分析的oauth代码中将此{ur} https://www.googleapis.com/auth/analytics.readonly替换为https://www.google.com/webmasters/tools/feeds/ API数据。