OAuth getting CURL token

Getting the first experience with CURL, I decided to take on a complex project right away, get the number of visits from the metric. To do this, you need to log in to Yandex, chose the method by login and password. I do this (documentation):

<?php
$url = 'https://oauth.yandex.ru/token';
$login = 'umur';
$pass = '123';
$id = 'f5aaID09853427c8c1244850357a899';
$header = array('POST /token HTTP/1.1','Host: oauth.yandex.ru','Content-type:application/x-www-form-urlencoded','Content-Length: 64');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch,CURLOPT_POSTFIELDS,'grant_type=password&client_id=$id&username=$login&password=$pass');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
curl_setopt($ch,CURLOPT_TIMEOUT,60);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
$query = curl_exec($ch);
curl_close($ch);
echo($query);
?>

But with Content-Length: 64, an error occurs:

HTTP/1.1 400 Bad Request Vary: Accept-Language Content-Type: application/json Content-Language: ru Cache-Control: no-store Transfer-Encoding: chunked Date: Mon, 18 Jul 2011 10:10:27 GMT Server: lighttpd/1.4.26 {"error": "invalid_client_credentials"}

And with Content-Length: 65 it freezes for more than 30 seconds, as a result:

Fatal error: Maximum execution time of 30 seconds exceeded in Z:\home\test\www\index.php on line 17

What’s the problem?


Answer 1, authority 100%

  1. $header = array(‘POST /token HTTP/1.1’– highlighted in bold – not needed. To do this, you specified: curl_setopt($ch,CURLOPT_POST,1);
  2. Content-Length should be: strlen('grant_type=password&client_id=$id&username=$login&password=$pass')
  3. grant_type=password – what is it? Act according to the documentation, since it is in Russian, so I don’t understand at all what problems may arise.

Answer 2

If you want to work with $query, use RETURNTRANSFER, 1; CURLOPT_HTTPHEADER– remove this altogether, if it doesn’t work, sniff it – you will see what is passed there (CURLOPT_POSTFIELDS).


Answer 3

To get a token,

$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $yandexConfig['oauthUrl']);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=" .$yandexConfig['yandexOauthLogin']. "&password="
        .$yandexConfig['yandexOauthPass']. "&client_id=" .$yandexConfig['metricsAppId']. "&client_secret="
        .$yandexConfig['metricsAppSecret']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $authData = curl_exec($ch);
    curl_close($ch);
    $authDataObj = json_decode($authData);

where

  • $yandexConfig['oauthUrl']– url by which we are trying to get a token
  • $yandexConfig['yandexOauthLogin']– login
  • $yandexConfig['yandexOauthPass']– password
  • $yandexConfig['metricsAppId']– your application id
  • $yandexConfig['metricsAppSecret']– application secret key