Skip to content

Commit

Permalink
Use public API (add auth and geolocationName + forecastpoint requests)
Browse files Browse the repository at this point in the history
  • Loading branch information
munterkofler committed Oct 2, 2023
1 parent d586bf8 commit 9d82096
Showing 1 changed file with 57 additions and 7 deletions.
64 changes: 57 additions & 7 deletions wp-plugin/srf-weather-widget/meteo.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<!-- api-key: ' .$key.' api secret:' . $secret . ' -->';

$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 .
'<div class="srf-weather-widget"
data-size="'.esc_html($widgetAtts['size']).'"
data-geolocation="'.esc_html($widgetAtts['geolocation']).'"
data-location-name="'.esc_html($widgetAtts['locationname']).'"></div>';
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.'\'>
</div>';
}

// add backend styles
Expand Down

0 comments on commit 9d82096

Please sign in to comment.