Get a token

PHP 5 using the file_get_contents function

This example shows getting an OAuth token in the web service. Recommendations for other types of applications (desktop or mobile) are given in the Yandex.OAuth documentation.

Callback URL

When registering or editing application parameters on the Yandex.OAuth service, you must set the Callback URL to the URL of the script that is receiving the token. For example:

The code of the script is provided below.


The token request requires specifying the application ID and password that were generated during registration on the Yandex.OAuth service.

  1. The application takes the user to the access request page using a link in the format

    On the page that opens, the user clicks Allow.

  2. Yandex.OAuth performs a redirect to the address from Callback URL. In addition, the code parameter is appended to the address. For example:
  3. The script sends a POST request to, passing the following parameters:
    • grant_type = authorization_code


    • client_id = APPLICATION_ID

    • client_secret = APPLICATION_PASSWORD

  4. Yandex.OAuth sends a response in JSON format. The access_token key contains the OAuth token. For example:
    {"access_token": "0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"}

    The received token must be saved and used in requests to the Yandex.Direct API.

Script code

To use this example, specify the application ID and password.

// Application ID
$client_id = 'APPLICATION_ID'; 
// Application ID
$client_secret = 'APPLICATION_PASSWORD';

// If the script was run with the "code" parameter in the URL,
// it executes the request to get a token
if (isset($_GET['code']))
    // Forming parameters of the POST request (the message body) with the authorization code
    $query = array(
      'grant_type' => 'authorization_code',
      'code' => $_GET['code'],
      'client_id' => $client_id,
      'client_secret' => $client_secret
    $query = http_build_query($query);

    // Forming headers for the POST request
    $header = "Content-type: application/x-www-form-urlencoded";

    // Executing the POST request and printing the result
    $opts = array('http' =>
      'method'  => 'POST',
      'header'  => $header,
      'content' => $query
    $context = stream_context_create($opts);
    $result = file_get_contents('', false, $context);
    $result = json_decode($result);

    // Save the token to use in Yandex.Direct API requests
    echo $result->access_token;
// If the script was called without the "code" parameter,
// the user is shown a link to the access request page
      echo '<a href="'.$client_id.'">Access request page</a>';