微信公众平台百度天气预报开发
1.登录百度ak申请:
2.实现天气信息功能
baiduWeather.php
<?php
/**
* 使用百度天气预报接口获取城市天气信息案例实现
*/
//获取城市天气信息
function getWeatherInfo($cityName){
if($cityName == "" || (strstr($cityName,"+"))){
return "发送城市加天气,例如北京天气";
}
//获取到的ak
$ak = your ak;
//获取到的sk
$sk = your sk;
//调用接口
$url = http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sk=%s;
$uri = /telematics/v3/weather;
$location = $cityName;
$output = json;
$querystring_arrays = array(
ak => $ak,
location => $location,
output => $output
);
$querystring = http_build_query($querystring_arrays);
//生成sn
$sn = md5(urlencode($uri.?.$querystring.$sk));
$targetUrl = sprintf($url,$ak,urlencode($location),$output,$sn);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$targetUrl);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result,true);
if($result["error"]!=0){
return $result["status"];
}
$curHour = (int)date(H,time());
$weather = $result["results"][0];
$weatherArray[]=array("Title"=>$weather[currentCity]."天气预报","Description"=>"","PicUrl"=>"","Url"=>"");
for($i = 0;$i<count($weather["weather_data"]);$i++){
$weatherArray[] = array("Title"=>
$weather["weather_data"][$i]["date"]."
".
$weather["weather_data"][$i]["weather"].
$weather["weather_data"][$i]["wind"].
$weather["weather_data"][$i]["temperature"],
"Description"=>"",
"PicUrl"=>(($curHour>=6)&&($curHour<
18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"],"URL"=>""
);
}
return $weatherArray;
}
3.实现天气消息事件
