Posted on: 03.09.2020 Posted by: Alex D Comments: 0

Example code for connecting to API Yandex Metrika

  1. Application registration.

Follow the link oauth.yandex.ru/client/new and register a new application on the Yandex OAuth server.

After registering the application, we get “ID” and “Password” to access the application.

An example of obtaining a token for accessing the Yandex API in PHP.

Reference Information yandex.ru/dev/oauth/doc/dg/concepts/about-docpage.

We create two files php for work.

File Y_get_start_yandex_token.php will be for authorization at yandex. The file will be Y_get_end_yandex_token.php to receive the token.

Create file Y_get_start_yandex_token.php.

File logic.

Application ID.

$clientId     = '0000000';

Application password.

$clientSecret = '111111111111111';

User’s forwarding address after authorization.

$redirectUri  = 'https://spage.me/user/token/Y_get_end_yandex_token.php';

Create a link for authorization.

The list of access rights the application needs at the moment, separated by a space. The rights must be requested from the list determined when registering the application. You can find out the allowed rights by following the link https://oauth.yandex.ru/client/f7d5d7d7262246fabef5fc2761b03c22/info, specifying the application ID instead of . If the scope parameter is not passed, then the token will be issued with the rights specified during application registration. The parameter allows you to get a token with only the rights that the application needs at the moment.

$params = array(
  'client_id'     => $clientId,
  'redirect_uri'  => $redirectUri,
  'response_type' => 'code',
  'scope'         => 'metrika:write appmetrica:read appmetrica:write metrika:read',
);

Display a link to open the authorization dialog window.

echo '<P>To do this, click the link: <A href="https://oauth.yandex.ru/authorize?' . http_build_query( $params ) . '">Get statistics</A></P>';

The system displays an authorization window to the client.

After authorization, the Y_get_start_yandex_token.php file is loaded.

Full code Y_get_start_yandex_token.php.

<?php
$clientId     = '00000';
$clientSecret = '11111';
$redirectUri  = 'https://spage.me/user/token/Y_get_end_yandex_token.php';
$params = array(
  'client_id'     => $clientId,
  'redirect_uri'  => $redirectUri,
  'response_type' => 'code',
  'scope'         => 'metrika:write appmetrica:read appmetrica:write metrika:read',
);
echo '<P>To do this, click the link: <A href="https://oauth.yandex.ru/authorize?' . http_build_query( $params ) . '"> '.$array_lang[$sp_lang]["Get statistics"].' Yandex Metrika </A></P>';
?>

Create file Y_get_end_yandex_token.php.

File logic.

We handle the error.

$error = $_GET['error'];
$error_description = $_GET['error_description'];
if ($error) echo "<BR>error".$error;
if ($error_description) echo "<BR>error_description".$error_description;

Enter the application ID and password.

$clientId     = '00000';
$clientSecret = '11111';

Create a POST request.

$query = array(
  'grant_type'    => 'authorization_code',
  'code'          => $_GET['code'],
  'client_id'     => $clientId,
  'client_secret' => $clientSecret
);
$query = http_build_query( $query );

$header = "Content-type: application/x-www-form-urlencoded";

$opts    = array(
  'http' =>
    array(
      'method'  => 'POST',
      'header'  => $header,
      'content' => $query
    )
);
$context = stream_context_create( $opts );

Making a POST request.

if ( ! $content = @file_get_contents( 'https://oauth.yandex.ru/token', false, $context ) ) {
  $error = error_get_last();
  throw new Exception( 'HTTP request failed. Error: ' . $error['message'] );
}

Convert rezult to PHP variable.

$response = json_decode( $content );

We look at errors.

if ( isset( $response->error ) ) {
  throw new Exception( $array_lang[$sp_lang]["An error occurred while getting the token"].'. Error: ' . $response->error . '. Error description: ' . $response->error_description );
}

This is the Yandex OAuth token.

$accessToken = $response->access_token;

Token lifetime in seconds. Must be 1 year old.

$expiresIn   = $response->expires_in;

Refresh Token to extend the life of the main OAuth token. More details here

$refreshToken = $response->refresh_token;

Save token on the database.

if ( $accessToken ) {
  //Open your database.
  //Save token on the database
}

Full code Y_get_end_yandex_token.php.

<?php
$error = $_GET['error'];
$error_description = $_GET['error_description'];
if ($error) echo "<BR>error".$error;
if ($error_description) echo "<BR>error_description".$error_description;
$clientId     = '0000000';
$clientSecret = '111111111';
$redirectUri  = 'https://spage.me/user/token/Y_get_end_yandex_token.php';
$params = array(
  'client_id'     => $clientId,
  'redirect_uri'  => $redirectUri,
  'response_type' => 'code',
  'scope'         => 'metrika:write appmetrica:read appmetrica:write metrika:read',
);
if ( isset( $_GET['code'] ) ) {
  $query = array(
	'grant_type'    => 'authorization_code',
	'code'          => $_GET['code'],
	'client_id'     => $clientId,
	'client_secret' => $clientSecret
  );
  $query = http_build_query( $query );
  $header = "Content-type: application/x-www-form-urlencoded";
  $opts    = array(
    'http' =>
    array(
	  'method'  => 'POST',
	  'header'  => $header,
	  'content' => $query
    )
  );
  $context = stream_context_create( $opts );
  if ( ! $content = @file_get_contents( 'https://oauth.yandex.ru/token', false, $context ) ) {
    $error = error_get_last();
    throw new Exception( 'HTTP request failed. Error: ' . $error['message'] );
  }
  $response = json_decode( $content );
  if ( isset( $response->error ) ) {
    throw new Exception( 'An error occurred while getting the token. Error: ' . $response->error . '. Error description: ' . $response->error_description );
  }
  $accessToken = $response->access_token;
  $expiresIn   = $response->expires_in;
  $refreshToken = $response->refresh_token;
  if ($accessToken) {
	echo "<P>Yandex Metrika statistics successfully connected.</P>";
	$link = mysqli_connect("localhost", $LG, $PS, $NM);
	mysqli_set_charset($link, 'utf8');
	$query_id_site_user = "UPDATE `site` SET `yandex_token`='".$accessToken."',`refresh_token_yandex`='".$refreshToken."' WHERE `id`='".$id_site."' AND `id_user`='".$id_user."'";
	$DB_id_site_user = mysqli_query($link, $query_id_site_user);
	mysqli_close($link);
	echo '<P><A href="https://spage.me/user/profile.php">Back to site profile editing.</A><P>';
  }else {
    echo "<P>Statistics Yandex Metric is not connected. Yandex Token not found.</P>";
  };
} elseif ( isset( $_GET['error'] ) ) {
	throw new Exception( 'An error occurred while logging in. Error: ' . $_GET['error']
	                     . '. Error description: ' . $_GET['error_description'] );
}
?>

Use the token to get statistics Yandex Metrika.

Create file Get_stat_yandex.php.

File logic.

Function request to Yandex metric.

function curl_file_get_contents($url,$authToken){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-yametrika+json', 'Authorization: OAuth '.$authToken]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$obj = curl_exec($ch);
curl_close($ch);
return $obj;
}

Function preparing data for a request.

function get_yandex_statist($start_data,$end_data,$Yandex_ids,$Yandex_oauth_token,$webpage){
  $url = 'https://api-metrika.yandex.ru/stat/v1/data';

  $params = [
	    'ids'         => $Yandex_ids,
	    'metrics'     => 'ym:s:visits',
	    'dimensions'  => 'ym:s:%3Cattribution%3ETrafficSource,ym:s:%3Cattribution%3ESourceEngine',
	    'dimensions'  => 'ym:s:lastSearchEngine,ym:s:startURL',
	    'date1'       => $start_data,
	    'date2'       => $end_data,
	    'limit'       => '10000',
	    'offset'      => '1',
	    'filters'     => 'ym:s:startURL=@\''.$webpage.'\'',
  ];
  $postData = curl_file_get_contents($url . '?' . http_build_query($params),$Yandex_oauth_token);
  return $postData;
}

The counter ID is located on the counter page https://metrika.yandex.ru/list/.

You received the $Yandex_oauth_token token from file Y_get_end_yandex_token.php.

$Yandex_ids = "00000";//from metrika.yandex.ru/list
$Yandex_oauth_token = "11111";//from Y_get_end_yandex_token.php
$start_data = "2020-08-27";//start data query
$end_data = "2020-08-28";//end data query
$webpage = "/";//path page of the your site

We make a request to Yandex metric.

$postData = get_yandex_statist($start_data,$end_data,$Yandex_ids,$Yandex_oauth_token,$webpage);
$obj=json_decode($postData, true);//true - it is now an array.
$obj_yandex_totals = $obj['totals']['0'];//total all period
for ($y=0; $y<count($obj['data']); $y++){
  $favicon = $obj['data'][$y]['dimensions']['0']['favicon'];
  $metrics = $obj['data'][$y]['metrics']['0'];
  $date = "";
  echo "<BR>".$date." ".$favicon." ".$metrics;
}

You can look at the keys of the array $obj. And access the fields of the array.

echo $url;

You will receive a link.

Install the plugin / extension JSON Viewer Awesome in your Chrome browser.

Now paste the link into the browser and at JSON Viewer Awesome you will see the structure of your array, fields and keys.

Now you know the structure of your array. Now you can build a graph. How to plot a graph from an array? Look here.

DEMO

Categories:

Leave a Comment