4

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.

4
  • api key is used for public apis you are trying to get private data use Oauth2. github.com/google/google-api-php-client/blob/master/examples/… Commented Oct 9, 2015 at 6:34
  • @DalmTo, do u mean, that I have to use client_id, client_secret, redirect_uri instead of API key? And will it be better to do it using an example according to your link, if I want to retrieve search data? Commented Oct 9, 2015 at 10:25
  • 1
    Yes you need to use client id and client secret which is Oauth2 instead of api key which is not Oauth2. I don't have an example of Oauth2 with search data you can read that tutorial and edit it once you understand how it works. Commented Oct 9, 2015 at 10:28
  • Can u help me with understanding? U said, that API key || OAuth 2.0 is used. But here, in 1st table I saw, that in some cases key && OAuth 2 are used. What are these cases? Thanks. Commented Oct 10, 2015 at 14:24

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Please, how did you find all the documentation in order to work with that google client? I can't find anything. In Google - they only show how to use the Books service, but where is the documentation for webmaters service?
Thanks for this fast answer Boollean! But ive already visited these links. I downloaded the php client and in their example it's only for the Books service, i need search console service. And the other link os for java, im using php. How did you know how to use Google_Service_Webmasters_SearchAnalyticsQueryRequest for example, and all that program you did?
@Upsilon42 I don't remember how exactly, but remember, that it was difficult. But today I've found docs with examples . I didn't try it, but looks not as scary as 2 years ago.
We tried this code .. We receive the following error Error calling POST googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.mysite.in/…: (403) User does not have sufficient permission for site 'mysite.in'. See also: support.google.com/webmasters/answer/2451999.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.