Skip to content

Instantly share code, notes, and snippets.

@absent1706
Created April 8, 2016 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save absent1706/3ce4213f2eb8da372eee545018becb53 to your computer and use it in GitHub Desktop.
Save absent1706/3ce4213f2eb8da372eee545018becb53 to your computer and use it in GitHub Desktop.
PHP:yandex API example
<?php
/*
Пример программного кода для работы с API сервиса Яндекс.Директ
В примере использован рекомендуемый синтаксис для работы с API сервиса Яндекс.Директ
на языке PHP с использованием протокола JSON и авторизацией по токенам.
Обращаем внимание, что все текстовые данные должны быть в кодировке UTF8
Подробнее про получение токена читайте в документации:
https://tech.yandex.ru/oauth/doc/dg/
*/
require_once "HTTP/Request.php";
// Важно: данные отправляем POST-методом
$req =& new HTTP_Request("https://api-sandbox.direct.yandex.ru/v4/json/");
$req->setMethod(HTTP_REQUEST_METHOD_POST);
// Инициализация параметров для авторизации
$data = array(
'token' => "6bfc962472504a2b99fb6a5b0b181d98"
);
// Параметры для запроса метода GetClientInfo
$data['method'] = "GetClientInfo";
$data['param'] = array('igorxlib');
/*
Если ваша версия php не поддерживает встроенной функции json_encode/json_decode,
можно воспользоваться библиотекой: http://pear.php.net/package/Services_JSON
*/
// require_once 'Classes/json.php';
// $json = new Services_JSON;
// $json_data = $json->encode($data);
$json_data = json_encode($data);
/*
Если встроенные функции json_encode/json_decode поддерживаются, то программа может выглядеть так:
$json_data = json_encode($data);
$decoded_result = json_decode($result);
*/
$req->addRawPostData($json_data);
$response = $req->sendRequest();
$errmsg = \PEAR::isError($response);
if (! $errmsg) {
$result = $req->getResponseBody();
$decoded_result = json_decode($result);
if (isset($decoded_result->data)) {
// Обработка ответа метода
print_r($decoded_result);
} else if ($decoded_result->error_code) {
// Если ошибку вернул сервер API
echo "Error: code = ".$decoded_result->error_code
.", str = ".$decoded_result->error_str
.", detail = ".$decoded_result->error_detail;
} else {
echo "Unknown error";
}
} else {
// Если ошибка произошла при попытке запроса
echo "Request error: ".$errmsg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment