您的位置:首页 > 移动开发 > 微信开发

微信公众平台开发(82) 天气预报

2014-02-26 13:57 501 查看
在这篇教程中,我们将介绍如何在微信公众平台上开发天气预报功能。我们将使用中国天气网的气象数据接口来获取天气信息。

这篇教程将介绍以下内容:

获取中国天气网的气象数据

在微信公众平台中回复天气

[b]一、中国天气网[/b]

中国天气网提供了丰富的气象数据接口。下面我们介绍主要的几个:

国家根节点接口:

http://flash.weather.com.cn/wmaps/xml/china.xml


该接口以XML格式列出所有的省(自治区、直辖市)的中文名称(quName)和拼音名称(pyName)及省会城市的天气信息,其中广东的数据如下:

<city quName="广东" pyName="guangdong" cityname="广州" state1="2" state2="7" stateDetailed="阴转小雨" tem1="8" tem2="15" windState="微风"/>


该接口的主要功能是通过它获取省级节点的拼音名称。以广东为例:其pyName是“Guangdong”。

省级节点接口(以广东为例):

http://flash.weather.com.cn/wmaps/xml/Guangdong.xml


该接口以XML格式列出当前省下辖所有市的中文名称(quName)、拼音名称(pyName)、中心坐标、天气信息以及城市编码。其中深圳的数据如下所示:

<city cityX="409" cityY="257" cityname="深圳" centername="深圳" fontColor="FFFFFF" pyName="shenzhen" state1="1" state2="1" stateDetailed="多云" tem1="12" tem2="18" temNow="12" windState="微风" windDir="东北风" windPower="1级" humidity="74%" time="21:15" url="101280601"/>


在这个接口中主要获取城市名称及相应的城市编码。例如,深圳的城市编码为:101280601。可以编写程序将全国城市拓扑结构采集下来。也可以使用方倍工作室已经采集好的,点击这里下载

实时天气数据(以深圳为例):

http://www.weather.com.cn/data/sk/101280601.html


该接口以JSON格式列出当前城市的实时天气状况。如下所示:

{
"weatherinfo": {
"city": "深圳",
"cityid": "101280601",
"temp": "12",
"WD": "东北风",
"WS": "1级",
"SD": "75%",
"WSE": "1",
"time": "21:20",
"isRadar": "1",
"Radar": "JC_RADAR_AZ9755_JB"
}
}


实时天气数据参数说明下所示:



六日天气数据(以深圳为例):

http://m.weather.com.cn/data/101280601.html


该接口以JSON格式列出当前城市的六日天气状况。如下所示:

{
"weatherinfo": {
"city": "深圳",
"city_en": "shenzhen",
"date_y": "2014年2月15日",
"date": "",
"week": "星期六",
"fchh": "18",
"cityid": "101280601",
"temp1": "12℃~18℃",
"temp2": "16℃~21℃",
"temp3": "17℃~23℃",
"temp4": "11℃~18℃",
"temp5": "10℃~15℃",
"temp6": "12℃~17℃",
"tempF1": "53.6℉~64.4℉",
"tempF2": "60.8℉~69.8℉",
"tempF3": "62.6℉~73.4℉",
"tempF4": "51.8℉~64.4℉",
"tempF5": "50℉~59℉",
"tempF6": "53.6℉~62.6℉",
"weather1": "多云",
"weather2": "阴",
"weather3": "多云",
"weather4": "中雨",
"weather5": "多云",
"weather6": "阴",
"img1": "1",
"img2": "99",
"img3": "2",
"img4": "99",
"img5": "1",
"img6": "99",
"img7": "8",
"img8": "99",
"img9": "1",
"img10": "99",
"img11": "2",
"img12": "99",
"img_single": "1",
"img_title1": "多云",
"img_title2": "多云",
"img_title3": "阴",
"img_title4": "阴",
"img_title5": "多云",
"img_title6": "多云",
"img_title7": "中雨",
"img_title8": "中雨",
"img_title9": "多云",
"img_title10": "多云",
"img_title11": "阴",
"img_title12": "阴",
"img_title_single": "多云",
"wind1": "微风",
"wind2": "微风",
"wind3": "微风",
"wind4": "东北风3-4级",
"wind5": "微风",
"wind6": "微风",
"fx1": "微风",
"fx2": "微风",
"fl1": "小于3级",
"fl2": "小于3级",
"fl3": "小于3级",
"fl4": "3-4级",
"fl5": "小于3级",
"fl6": "小于3级",
"index": "较舒适",
"index_d": "建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。",
"index48": "较舒适",
"index48_d": "建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。",
"index_uv": "最弱",
"index48_uv": "最弱",
"index_xc": "适宜",
"index_tr": "适宜",
"index_co": "舒适",
"st1": "19",
"st2": "13",
"st3": "23",
"st4": "16",
"st5": "24",
"st6": "18",
"index_cl": "适宜",
"index_ls": "适宜",
"index_ag": "不易发"
}
}


未来六日天气数据主要参数说明如下表所示:



以上接口是我们做天气预报功能将使用到的接口。

[b]二、微信公众平台开发[/b]

1. 需要将城市编码对照表导入到数据库中,以下是SAE导入后截图



2. 将城市名转为城市代码的方法,这将在用户发送城市名的时候调用

function fromNameToCode($name)
{
$mysql_host = SAE_MYSQL_HOST_M;
$mysql_host_s = SAE_MYSQL_HOST_S;
$mysql_port = SAE_MYSQL_PORT;
$mysql_user = SAE_MYSQL_USER;
$mysql_password = SAE_MYSQL_PASS;
$mysql_database = SAE_MYSQL_DB;

$mysql_table = "weather";
$mysql_state = "SELECT * FROM ".$mysql_table." WHERE `cityName` = '".$name."'";

$con = mysql_connect($mysql_host.':'.$mysql_port, $mysql_user, $mysql_password, true);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES 'UTF8'");
mysql_select_db($mysql_database, $con);
$result = mysql_query($mysql_state);
$cityCode = "";
while($row = mysql_fetch_array($result))
{
$cityCode = $row['cityCode'];
break;
}
mysql_close($con);
return $cityCode;
}


3. 编写接口调用函数,用于向天气网发送cURL请求,获取数据

function httpRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
if ($output === FALSE){
return "cURL Error: ". curl_error($ch);
}
return $output;
}


4. 编写获取天气数据的函数,这里获取实时天气和未来3日天气,并将返回结果封装成图文信息的数组

function getWeatherInfo($cityName)
{
$cityCode = fromNameToCode($cityName);

if ($cityCode == "")
{
return "错误的城市名或者此城市不在数据库中!";
}

//获取实时天气
$url = "http://www.weather.com.cn/data/sk/".$cityCode.".html";
$output = httpRequest($url);
$weather = json_decode($output, true);
$info = $weather['weatherinfo'];

$weatherArray = array();
$weatherArray[] = array("Title"=>$info['city']."天气预报", "Description"=>"", "PicUrl"=>"", "Url" =>"");
if ((int)$cityCode < 101340000){
$result = "实况 温度:".$info['temp']."℃ 湿度:".$info['SD']." 风速:".$info['WD'].$info['WSE']."级";
$weatherArray[] = array("Title"=>str_replace("%", "﹪", $result), "Description"=>"", "PicUrl"=>"", "Url" =>"");
}

//获取六日天气
$url = "http://m.weather.com.cn/data/".$cityCode.".html";
$output = httpRequest($url);
$weather = json_decode($output, true);
$info = $weather['weatherinfo'];

if (!empty($info['index_d'])){
$weatherArray[] = array("Title" =>$info['index_d'], "Description" =>"", "PicUrl" =>"", "Url" =>"");
}

$weekArray = array("日","一","二","三","四","五","六");
$maxlength = 3;
for ($i = 1; $i <= $maxlength; $i++) {
$offset = strtotime("+".($i-1)." day");
$subTitle = date("m月d日",$offset)." 周".$weekArray[date('w',$offset)]." ".$info['temp'.$i]." ".$info['weather'.$i]." ".$info['wind'.$i];
$weatherArray[] = array("Title" =>$subTitle, "Description" =>"", "PicUrl" =>"http://discuz.comli.com/weixin/weather/"."d".sprintf("%02u",$info['img'.(($i *2)-1)]).".jpg", "Url" =>"");
}

return $weatherArray;
}


5. 在微信公众平台接口函数中处理收到的文本消息时,文本将为城市名,直接调用获取天气的函数

/*
方倍工作室
CopyRight 2013 All Rights Reserved
*/

define("TOKEN", "weixin");

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
}else{
$wechatObj->valid();
}

class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
exit;
}
}

private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);

if($tmpStr == $signature){
return true;
}else{
return false;
}
}

public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
$this->logger("R ".$postStr);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);

switch ($RX_TYPE)
{
case "event":
$result = $this->receiveEvent($postObj);
break;
case "text":
$result = $this->receiveText($postObj);
break;
}
$this->logger("T ".$result);
echo $result;
}else {
echo "";
exit;
}
}

private function receiveEvent($object)
{
$content = "";
switch ($object->Event)
{
case "subscribe":
$content = "欢迎关注方倍工作室 ";
break;
case "unsubscribe":
$content = "取消关注";
break;
}
$result = $this->transmitText($object, $content);
return $result;
}

private function receiveText($object)
{
$keyword = trim($object->Content);

include("weather.php");
$content = getWeatherInfo($keyword);
$result = $this->transmitNews($object, $content);
return $result;
}

private function transmitText($object, $content)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}

private function transmitNews($object, $arr_item)
{
if(!is_array($arr_item))
return;

$itemTpl = "    <item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
";
$item_str = "";
foreach ($arr_item as $item)
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

$result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
return $result;
}

private function logger($log_content)
{
}
}


[b] 三、效果演示[/b]



[b]四、如何扩展[/b]

1. 在数据库加入邮编、区号、拼音等字段,可以扩展成使用区号等方式查询,请参考:http://www.cnblogs.com/txw1958/archive/2013/02/07/weixin-if4-weather-forecast.html

2. 拥有高级接口的用户,可以使用结合语音识别+中文分词技术,实现语音版的智能查询,请参考:http://www.cnblogs.com/txw1958/archive/2013/02/06/weixin-if40-voice-recognition.html

五、关于接口更新

1. 中国天气网已经停步上述免费接口的更新,需要调用天气数据需要申请SWA接口。

地址 http://smart.weather.com.cn/wzfw/smart/weatherapi.shtml
2. 中国天气网的智慧天气接口在微信公众平台上的实现方法在《微信公众平台开发最佳实践》一书有讲解

地址 /article/4596734.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: