Question

I managed to connect via Oauth 2 with Analytics but can not find the way to do it with webmaster tools. I got the "scope" of webmaster tools at: https://developers.google.com/oauthplayground/

and I'm using the code here: https://code.google.com/p/google-api-php-client/

but I can not work me. If anyone can guide me would be grateful.

PS: May this year XD

Was it helpful?

Solution

following code will help to get access token and refresh token for webmaster tools API access through Oauth Flow

Make sure that the Redirect Uri that you have mentioned in your API console should be same as the filename in which you will place the following code.

For eg. If the redirect uri is:-somesitename.com/google_oauth.php(with http:// or https://) then following script should be placed in :- google_oauth.php (path:somesitename.com/google_oauth.php (with http:// or 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>

You can then use this token to query webmaster tools API for data.

Also you can use the same code that you have used for your Oauth analytics access,just replace this url:https://www.googleapis.com/auth/analytics.readonly with https://www.google.com/webmasters/tools/feeds/ in your oauth code that you are using for analytics while querying webmaster tools API data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top