· 6 years ago · Jun 13, 2019, 10:28 AM
1<?php
2
3class WheatherAPi
4{
5 private $params = [];
6 private $oAuth = [];
7 const API_URL = 'https://weather-ydn-yql.media.yahoo.com/forecastrss';
8 const AppId = 'lwH4bW32';
9 const ConsumerKey = 'dj0yJmk9dkZ2NXJYQ1hiWTUzJmQ9WVdrOWJIZElOR0pYTXpJbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PTVj';
10 const SecretKey = '164668f9f61461ece9ff947308a8235553d8b44f';
11 const Format = 'json';
12 const Method = 'GET';
13 public function __construct($city, $country)
14 {
15 $this->setParams($city,$country);
16
17 $this->setOAuth();
18 }
19
20 public function __toString()
21 {
22 return $this->getMonitor();
23 }
24
25 public function getOAuth(){
26 return $this->oAuth;
27 }
28 public function getParams()
29 {
30 return $this->params;
31 }
32 public function setOAuth(){
33 $this->oAuth = [
34 'oauth_consumer_key' => self::ConsumerKey,
35 'oauth_nonce' => uniqid(mt_rand(1, 1000)),
36 'oauth_signature_method' => 'HMAC-SHA1',
37 'oauth_timestamp' => time(),
38 'oauth_version' => '1.0'
39 ];
40 return $this;
41 }
42 public function setParams($city, $country)
43 {
44
45 $this->params = [
46 'location' =>$city.','.$country,
47 'format' => self::Format
48 ];
49
50 return $this;
51 }
52
53 public function buildAuthorizationHeader() {
54 $result = 'Authorization: OAuth ';
55 $values = array();
56 foreach($this->getOAuth() as $key=>$value) {
57 $values[] = "$key=\"" . rawurlencode($value) . "\"";
58 }
59 $result .= implode(', ', $values);
60 return $result;
61 }
62 public function buildUrl(){
63 $result = [];
64 $params = array_merge($this->getParams(), $this->getOAuth());
65 ksort($params);
66 foreach($params as $key => $value) {
67 $result[] = "$key=" . $value;
68 }
69
70 return self::Method . "&" . rawurlencode(self::API_URL) ."&". rawurlencode(implode('&', $result));
71 }
72 public function getWheather()
73 {
74 $base_info = $this->buildUrl();
75 $composite_key = rawurlencode(self::SecretKey.'&');
76 $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
77 $this->oAuth['oauth_signature'] = $oauth_signature;
78 $header = array(
79 $this->buildAuthorizationHeader($this->getOAuth()),
80 'X-Yahoo-App-Id: ' . self::AppId
81 );
82
83
84 $options = array(
85 CURLOPT_HTTPHEADER => $header,
86 CURLOPT_HEADER => false,
87 CURLOPT_URL => self::API_URL . '?' . http_build_query($this->getParams()),
88 CURLOPT_RETURNTRANSFER => true,
89 CURLOPT_SSL_VERIFYPEER => false
90 );
91 print_r($options);
92 $ch = curl_init();
93 curl_setopt_array($ch, $options);
94 $response = curl_exec($ch);
95 curl_close($ch);
96 print_r($response);
97 $return_data = json_decode($response);
98 print_r($return_data);
99
100 }
101}
102
103
104try {
105 $wheather = new WheatherAPi('katowice','pl');
106 $wheather->getWheather();
107
108} catch (Exception $e) {
109 echo $e;
110}