From 9d82096736a9fd99d25351233c311e75129bc325 Mon Sep 17 00:00:00 2001 From: Markus Unterkofler <157289+munterkofler@users.noreply.github.com> Date: Mon, 2 Oct 2023 15:40:06 +0200 Subject: [PATCH] Use public API (add auth and geolocationName + forecastpoint requests) --- wp-plugin/srf-weather-widget/meteo.php | 64 +++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/wp-plugin/srf-weather-widget/meteo.php b/wp-plugin/srf-weather-widget/meteo.php index da2b3c7..ce77df4 100644 --- a/wp-plugin/srf-weather-widget/meteo.php +++ b/wp-plugin/srf-weather-widget/meteo.php @@ -29,20 +29,70 @@ function meteo_widget($atts = [], $content = null, $tag = '') { return 'Not a valid widget size set.'; } + // generate basic auth token $key = get_option(SrfWeatherWidgetSettings::SRF_WEATHER_API_KEY); $secret = get_option(SrfWeatherWidgetSettings::SRF_WEATHER_API_SECRET); - $commentedKeys = ''; - $encoded = base64_encode($key.':'.$secret); - // TODO: send request for data and add it to data attribute + + $apiDomain = 'https://api.srgssr.ch'; + $apiBaseUrl = $apiDomain.'/srf-meteo/v2'; + + + // login + $response = wp_remote_post( + $apiDomain.'/oauth/v1/accesstoken?grant_type=client_credentials', + [ + 'headers' => [ + 'Authorization' => 'Basic '.$encoded, + 'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8' + ], + ] + ); + $body = json_decode(wp_remote_retrieve_body($response), true); + $accessToken = $body['access_token']; + + + // search by name + $response = get_transient('srf_weather_geolocation_names'); + if (false === $response) { + $response = wp_remote_get( + $apiBaseUrl . '/geolocationNames?zip=8600', + [ + 'headers' => [ + 'Authorization' => 'Bearer ' . $accessToken, + ], + ] + ); + set_transient('srf_weather_geolocation_names', $response, 60 * 60); + } + $body = json_decode(wp_remote_retrieve_body($response), true); + $geolocationId = $body['geolocation']['id']; + + + // get forecast data + $response = get_transient('srf_weather_forecastpoint'); + if (false === $response) { + $response = wp_remote_get( + $apiBaseUrl . '/forecastpoint/' . $geolocationId, + [ + 'headers' => [ + 'Authorization' => 'Bearer ' . $accessToken, + ], + ] + ); + set_transient('srf_weather_forecastpoint', $response, 60 * 60); + } + $forecastpoint = wp_remote_retrieve_body($response); return - $commentedKeys . '
'; + data-size="'.esc_html($widgetAtts['size']).'" + data-geolocation="'.esc_html($widgetAtts['geolocation']).'" + data-location-name="'.esc_html($widgetAtts['locationname']).'" + data-mode="'.esc_html($widgetAtts['mode']).'" + data-forecast-point=\''.$forecastpoint.'\'> + '; } // add backend styles