@Negative1
быдлокодер object pascal

Как подключиться к API Яндекс.Погода?

Зарегистрировал тестовый токен. Пытаюсь получить ответ, приходит 403 Forbidden. В кабинете Яндекса статистика чистая.
AJAX запрос
<!DOCTYPE HTML>
<html>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script >      
             $.ajax({
                 url: 'https://api.weather.yandex.ru/v1/forecast?lat=56.852728&lon=53.213253',
				 headers: {
                            'X-Yandex-API-Key' : 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'
				    	  },
                 type: 'GET',
                 dataType: 'jsonp',
                 success: function (data) {
                      console.log(data);
                 },
				  error: function(response) {
					console.log(JSON.stringify(response));
				  }          
             });      
</script>
</html>

Нативный XMLHTTPRequest
<!DOCTYPE HTML>
<html>
	<script>      
			try {
				var xhttp = new XMLHttpRequest();
				xhttp.open('GET', 'https://api.weather.yandex.ru/v1/forecast?lat=56.852728&lon=53.213253&extra=true', false);
				xhttp.setRequestHeader('Content-type', 'text/html', 'X-Yandex-API-Key: xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx');
				xhttp.send();
				var response = JSON.parse(xhttp.response);
				console.log(xhttp.response);
			}
			catch (error) {
				console.log(error.message);
			}

	</script>
</html>
  • Вопрос задан
  • 6394 просмотра
Пригласить эксперта
Ответы на вопрос 1
<?php
header("Access-Control-Allow-Origin: *");
setlocale(LC_ALL, "ru_RU");
date_default_timezone_set("Europe/Moscow");

$opts = array(
  'http' => array(
    'method' => "GET",
    'header' => "X-Yandex-API-Key: ----------- ваш ключ ----------"
  )
);

$url = "https://api.weather.yandex.ru/v1/forecast?lat=52.886894&lon=40.509112&limit=1&hours=false&extra=false";
$context = stream_context_create($opts);
$contents = file_get_contents($url, false, $context);
$clima = json_decode($contents);

$time_unix = $clima->fact->obs_time;
$temp = $clima->fact->temp;
$humidity = $clima->fact->humidity;
$speed = $clima->fact->wind_speed;
$pressure = $clima->fact->pressure_mm;
$icon = $clima->fact->icon . ".svg";

$today = date("j/m/Y, H:i");
$time = date("j/m/Y, H:i", $time_unix);

echo "Дата/Вреемя:" . " - " . $today . "<br>";
echo "Обновлено:" . " - " . $time . "<br>";
echo "Температура: " . $temp . " &deg;C<br>";
echo "Влажность: " . $humidity . " %<br>";
echo "Ветер: " . $speed . " м/с<br>";
echo "Давление: " . $pressure . " мм р/с<br>";
echo "<img src='https://yastatic.net/weather/i/icons/blueye/color/svg/" . $icon . "'/ width='50'>";


// var_dump(json_decode($contents));
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы