Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving Google Search Analytics by "google-api-php-client" library

I'm still a beginner in any API, so need help. As I understand, service "Webmasters" in google-api-php-client library allows me to receive data like CTR, Clicks, etc.

I downloaded lib files from github and puted it into localhost. Then in Google Developers Console I created project (dont't really understand, for what? This project doesn't contain any info about site, which search info I need). And after that created server key for project (by "Add credentials" in Google Developers Console, without typing any ip for it). Google Search Console API is enable. I'm full user for my site (I can see it in Google Search Console). Also I have Google account, sure, and logged in.

My source file created in examples folder of lib, among other examples:

include_once "templates/base.php";    
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$apiKey = "AIzaSyCOJ56353XByxh8rCpfgfhgfhZzopSLUe"; // Value of server key, that I created in for my project ().

if (strpos($apiKey, "<") !== false) {
  echo missingApiKeyWarning();
  exit;
}
$client->setDeveloperKey($apiKey);

//here are my efforts
$service = new Google_Service_Webmasters($client);
var_dump($service->searchanalytics->query(
'http://sschesnok.com.ua',
 new Google_Service_Webmasters_SearchAnalyticsQueryRequest())); //I'm not sure about correctness of 2nd param

I see error:

<b>Fatal error</b>:  Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/webmasters/v3/sites?key=AIzaSyCOJXByxh8rCpfZzopSLUerl6LjWmziqhw: (401) Login Required' in    G:\server\www\gwt\gs\src\Google\Http\REST.php:110
Stack trace:
#0 G:\server\www\gwt\gs\src\Google\Http\REST.php(62):   Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client))
#1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
#2 G:\server\www\gwt\gs\src\Google\Task\Runner.php(174): call_user_func_array(Array, Array)
#3 G:\server\www\gwt\gs\src\Google\Http\REST.php(46): Google_Task_Runner-&gt;run()
#4 G:\server\www\gwt\gs\src\Google\Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 G:\server\www\gwt\gs\src\Google\Service\Resource.php(237): Google_Client-&gt;execute(Object(Google_Http_Request))
#6 G:\server\www\gwt\gs\src\Google\Service\Webmasters.php(492): Google_Service_Resource-&gt;call('list', A in <b>G:\server\www\gwt\gs\src\Google\Http\REST.php</b> on line <b>110</b><br />

(401) Login Required - where am I wrong? What login and where need I to pass?

And 2nd question - what need I to pass as second param to query method?

Please, help me to figure it out: to retrieve search info vie this lib. I have never worked with any API, so understand almost nothing in it.

like image 701
Boolean_Type Avatar asked Dec 11 '22 20:12

Boolean_Type


1 Answers

Here is my working code. I used dev-master version of this lib.

include_once "templates/base.php";
session_start();

require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');

$client_id = '**********************.apps.googleusercontent.com';
$client_secret = '*******************';
$redirect_uri = 'http://localhost/gwt/gr/examples/user-example.php';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/webmasters");

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

if ($client->getAccessToken()) {
  $_SESSION['access_token'] = $client->getAccessToken();

    $q = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();

    $q->setStartDate('2015-09-01');
    $q->setEndDate('2015-09-01');
    $q->setDimensions(['page']);
    $q->setSearchType('web');
    try {
       $service = new Google_Service_Webmasters($client);
       $u = $service->searchanalytics->query('http://sschesnok.com.ua', $q);
       echo '<table border=1>';
       echo '<tr>
          <th>#</th><th>Clicks</th><th>CTR</th><th>Imp</th><th>Page</th><th>Avg. pos</th>';
          for ($i = 0; $i < count($u->rows); $i++) {
            echo "<tr><td>$i</td>";
            echo "<td>{$u->rows[$i]->clicks}</td>";
            echo "<td>{$u->rows[$i]->ctr}</td>";
            echo "<td>{$u->rows[$i]->impressions}</td>";
            echo "<td>{$u->rows[$i]->keys[0]}</td>";
            echo "<td>{$u->rows[$i]->position}</td>";

            /* foreach ($u->rows[$i] as $k => $value) {
                //this loop does not work (?)
            } */
            echo "</tr>";
          }             
        echo '</table>';
     } catch(\Exception $e ) {
        echo $e->getMessage();
     }  
}

<div class="request">
<?php 
    if (isset($authUrl)) {
      echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
    } else {
      echo <<<END
     <form id="url" method="GET" action="{$_SERVER['PHP_SELF']}">
       <input name="url" class="url" type="text">
       <input type="submit" value="Shorten">
     </form>
     <a class='logout' href='?logout'>Logout</a>
END;
}
?>
</div>

Access token expires perodically.

like image 91
Boolean_Type Avatar answered Feb 22 '23 23:02

Boolean_Type