讀古今文學網 > 微信公眾平台開發:從零基礎到ThinkPHP5高性能框架實踐 > 4.4.2 調用API實現圖文天氣預報 >

4.4.2 調用API實現圖文天氣預報

百度地圖提供天氣預報查詢接口API,可以根據經緯度/城市名查詢天氣情況,因此可以在微信公眾平台開發中調用這一接口。

調用百度地圖API需要註冊百度賬號,然後申請AK(訪問密鑰),申請地址為http://lbsyun.baidu.com/apiconsole/key。

打開申請地址頁面,如圖4-16所示。

圖4-16 應用列表

點擊「創建應用」按鈕,彈出創建應用頁面,如圖4-17所示。

「應用名稱」可以隨便填寫,「應用類型」選擇「服務端」,「啟用服務」裡面的選項可以全部選擇,「請求校驗方式」選擇「sn校驗方式」,然後點擊「提交」按鈕,回到控制台。在頁面上可以看到AK參數的值,如圖4-18所示。

再點擊「設置」鏈接,可以看到該應用的SK參數,如圖4-19所示。

百度地圖天氣預報API接口如下:


http:// api.map.baidu.com/place/v2/search
  

圖4-17 創建應用

圖4-18 應用的AK參數

圖4-19 應用的SK參數

該接口的參數說明如表4-14所示。

表4-14 百度地圖天氣預報API參數說明

該接口調用舉例如下:


http:// api.map.baidu.com/telematics/v3/weather?ak=WT7idirGGBgA6BNdGM36f3kZ&locati
on=%E6%B7%B1%E5%9C%B3&output=json&sn=66116881b46a72e3380f29989c883bec
  

返回結果列表如下所示:


{
    "error":0,
    "status":"success",
    "date":"2016-06-29",
    "results":[
        {
            "currentCity":"深圳",
            "pm25":"18",
            "index":[
                {
                    "title":"穿衣",
                    "zs":"炎熱",
                    "tipt":"穿衣指數",
                    "des":"天氣炎熱,建議著短衫、短裙、短褲、薄型T恤衫等清涼夏季服裝。"
                },
                {
                    "title":"洗車",
                    "zs":"不宜",
                    "tipt":"洗車指數",
                    "des":"不宜洗車,未來24小時內有雨,如果在此期間洗車,雨水和路上的泥水
                    可能會再次弄髒您的愛車。"
                },
                {
                    "title":"旅遊",
                    "zs":"一般",
                    "tipt":"旅遊指數",
                    "des":"天氣較熱,有微風,但較強降雨的天氣將給您的出行帶來很多的不便,若
                    堅持旅行建議帶上雨具。"
                },
                {
                    "title":"感冒",
                    "zs":"少發",
                    "tipt":"感冒指數",
                    "des":"各項氣象條件適宜,發生感冒概率較低。但請避免長期處於空調房間中,以
                    防感冒。"
                },
                {
                    "title":"運動",
                    "zs":"較不宜",
                    "tipt":"運動指數",
                    "des":"有較強降水,建議您選擇在室內進行健身休閒運動。"
                },
                {
                    "title":"紫外線強度",
                    "zs":"弱",
                    "tipt":"紫外線強度指數",
                    "des":"紫外線強度較弱,建議出門前塗擦SPF在12-15之間、PA+的防曬護膚品。"
                }
            ],
            "weather_data":[
                {
                    "date":"週三 06月29日 (實時:31℃)",
                    "dayPictureUrl":"http:// api.map.baidu.com/images/weather/day/
                    zhongyu.png",
                    "nightPictureUrl":"http:// api.map.baidu.com/images/weather/night/
                    zhongyu.png",
                    "weather":"中雨",
                    "wind":"微風",
                    "temperature":"33 ~ 27℃"
                },
                {
                    "date":"週四",
                    "dayPictureUrl":"http:// api.map.baidu.com/images/weather/day/dayu.
                    png",
                    "nightPictureUrl":"http:// api.map.baidu.com/images/weather/night/
                    dayu.png",
                    "weather":"中到大雨",
                    "wind":"微風",
                    "temperature":"32 ~ 26℃"
                },
                {
                    "date":"週五",
                    "dayPictureUrl":"http:// api.map.baidu.com/images/weather/day/
                    dayu.png",
                    "nightPictureUrl":"http:// api.map.baidu.com/images/weather/night/
                    dayu.png",
                    "weather":"中到大雨",
                    "wind":"微風",
                    "temperature":"30 ~ 26℃"
                },
                {
                    "date":"週六",
                    "dayPictureUrl":"http:// api.map.baidu.com/images/weather/day/
                    zhenyu.png",
                    "nightPictureUrl":"http:// api.map.baidu.com/images/weather/night/
                    zhenyu.png",
                    "weather":"陣雨",
                    "wind":"微風",
                    "temperature":"32 ~ 26℃"
                }
            ]
        }
    ]
}
 

上述返回結果字段說明如表4-15所示。

表4-15 天氣預報接口返回字段說明

根據上述接口,可編寫獲取天氣預報的代碼如下。


 1 function getWeatherInfo($cityName)
 2 {    
 3     $ak = 'WT7idirGGBgA6BNdGM36f3kZ';
 4     $sk = 'uqBuEvbvnLKC8QbNVB26dQYpMmGcSEHM'; 
 5     $url = 'http:// api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&o
       utput=%s&sn=%s';
 6     $uri = '/telematics/v3/weather';
 7     $location = $cityName;
 8     $output = 'json';
 9     $querystring_arrays = array(
10         'ak' => $ak,
11         'location' => $location,
12         'output' => $output
13     );
14     $querystring = http_build_query($querystring_arrays);
15     $sn = md5(urlencode($uri.'?'.$querystring.$sk));
16     $targetUrl = sprintf($url, $ak, urlencode($location), $output, $sn);
17     
18     $ch = curl_init;
19     curl_setopt($ch, CURLOPT_URL, $targetUrl);
20     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
21     $result = curl_exec($ch);
22     curl_close($ch);
23     
24     $result = json_decode($result, true);
25     if ($result["error"] != 0){
26         return $result["status"];
27     }
28     $curHour = (int)date('H',time);
29     $weather = $result["results"][0];
30     $weatherArray = array("Title" =>$weather['currentCity']."天氣預報", "Desc
       ription" =>"", "PicUrl" =>"", "Url" =>"");
31     for ($i = 0; $i < count($weather["weather_data"]); $i++) {
32         $weatherArray = array("Title"=>
33             $weather["weather_data"][$i]["date"]."\n".
34             $weather["weather_data"][$i]["weather"]." ".
35             $weather["weather_data"][$i]["wind"]." ".
36             $weather["weather_data"][$i]["temperature"],
37         "Description"=>"", 
38         "PicUrl"=>(($curHour >= 6) && ($curHour < 18))?$weather["weather_data"][$i]
       ["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"], "Url"=>"");
39     }
40     return $weatherArray;
41 }
  

上述代碼解讀如下。

第3~16行:構造查詢請求URL。

第18~22行:獲取查詢結果。

第24~39行:根據查詢結果提取天氣信息內容並封裝成圖文消息。

一個查詢成功的結果如圖4-20所示。