公众平台开发(82)天⽓预报
在这篇教程中,我们将介绍如何在公众平台上开发天⽓预报功能。我们将使⽤中国天⽓⽹的⽓象数据接⼝来获取天⽓信息。
这篇教程将介绍以下内容:
1. 获取中国天⽓⽹的⽓象数据
2. 在公众平台中回复天⽓
⼀、中国天⽓⽹
中国天⽓⽹提供了丰富的⽓象数据接⼝。下⾯我们介绍主要的⼏个:
国家根节点接⼝:
flash.weather/wmaps/l
该接⼝以XML格式列出所有的省(⾃治区、直辖市)的中⽂名称(quName)和拼⾳名称(pyName)及省会城市的天⽓信息,其中⼴东的数据如下:
<city quName="⼴东" pyName="guangdong" cityname="⼴州" state1="2" state2="7" stateDetailed="阴转⼩⾬" tem1="8" tem2="15" windState="微风"/>
该接⼝的主要功能是通过它获取省级节点的拼⾳名称。以⼴东为例:其pyName是“Guangdong”。
省级节点接⼝(以⼴东为例):
flash.weather/wmaps/l
该接⼝以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
在这个接⼝中主要获取城市名称及相应的城市编码。例如,深圳的城市编码为:101280601。可以编写程序将全国城市拓扑结构采集下来。也可以使⽤⽅倍⼯作室已经采集好
的,。
实时天⽓数据(以深圳为例):
www.weather/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"
}
}
实时天⽓数据参数说明下所⽰:
六⽇天⽓数据(以深圳为例):
m.weather/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": "阴",html特效代码天气时钟
"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_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": "不易发"
}
}
未来六⽇天⽓数据主要参数说明如下表所⽰:
以上接⼝是我们做天⽓预报功能将使⽤到的接⼝。
⼆、公众平台开发
1. 需要将城市编码对照表导⼊到数据库中,以下是SAE导⼊后截图
2. 将城市名转为城市代码的⽅法,这将在⽤户发送城市名的时候调⽤
1function fromNameToCode($name)
2 {
3$mysql_host = SAE_MYSQL_HOST_M;
4$mysql_host_s = SAE_MYSQL_HOST_S;
5$mysql_port = SAE_MYSQL_PORT;
6$mysql_user = SAE_MYSQL_USER;
7$mysql_password = SAE_MYSQL_PASS;
8$mysql_database = SAE_MYSQL_DB;
9
10$mysql_table = "weather";
11$mysql_state = "SELECT * FROM ".$mysql_table." WHERE `cityName` = '".$name."'";
12
13$con = mysql_connect($mysql_host.':'.$mysql_port, $mysql_user, $mysql_password, true);
14if (!$con){
15die('Could not connect: ' . mysql_error());
16    }
17mysql_query("SET NAMES 'UTF8'");
18mysql_select_db($mysql_database, $con);
19$result = mysql_query($mysql_state);
20$cityCode = "";
21while($row = mysql_fetch_array($result))
22    {
23$cityCode = $row['cityCode'];
24break;
25    }
26mysql_close($con);
27return$cityCode;
28 }
3. 编写接⼝调⽤函数,⽤于向天⽓⽹发送cURL请求,获取数据
1function httpRequest($url)
2 {
3$ch = curl_init();
4    curl_setopt($ch, CURLOPT_URL, $url);
5    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
6$output = curl_exec($ch);
7    curl_close($ch);
8if ($output === FALSE){
9return "cURL Error: ". curl_error($ch);
10    }
11return$output;
12 }
4. 编写获取天⽓数据的函数,这⾥获取实时天⽓和未来3⽇天⽓,并将返回结果封装成图⽂信息的数组 1function getWeatherInfo($cityName)
2 {
3$cityCode = fromNameToCode($cityName);
4
5if ($cityCode == "")
6    {
7return "错误的城市名或者此城市不在数据库中!";
8    }
9
10//获取实时天⽓
11$url = "www.weather/data/sk/".$cityCode.".html";
12$output = httpRequest($url);
13$weather = json_decode($output, true);
14$info = $weather['weatherinfo'];
15
16$weatherArray = array();
17$weatherArray[] = array("Title"=>$info['city']."天⽓预报", "Description"=>"", "PicUrl"=>"", "Url" =>"");
18if ((int)$cityCode < 101340000){
19$result = "实况温度:".$info['temp']."℃湿度:".$info['SD']." 风速:".$info['WD'].$info['WSE']."级";
20$weatherArray[] = array("Title"=>str_replace("%", "﹪", $result), "Description"=>"", "PicUrl"=>"", "Url" =>"");
21    }
22
24$url = "m.weather/data/".$cityCode.".html";
25$output = httpRequest($url);
26$weather = json_decode($output, true);
27$info = $weather['weatherinfo'];
28
29if (!empty($info['index_d'])){
30$weatherArray[] = array("Title" =>$info['index_d'], "Description" =>"", "PicUrl" =>"", "Url" =>"");
31    }
32
33$weekArray = array("⽇","⼀","⼆","三","四","五","六");
34$maxlength = 3;
35for ($i = 1; $i <= $maxlength; $i++) {
36$offset = strtotime("+".($i-1)." day");
37$subTitle = date("m⽉d⽇",$offset)." 周".$weekArray[date('w',$offset)]." ".$info['temp'.$i]." ".$info['weather'.$i]." ".$info['wind'.$i];
38$weatherArray[] = array("Title" =>$subTitle, "Description" =>"", "PicUrl" =>"discuzli/weixin/weather/"."d".sprintf("%02u",$info['img'.(($i *2)-1)]).".jpg", "Url" =>"");
39    }
40
41return$weatherArray;
42 }
5. 在公众平台接⼝函数中处理收到的⽂本消息时,⽂本将为城市名,直接调⽤获取天⽓的函数
1/*
2⽅倍⼯作室
3    CopyRight 2013 All Rights Reserved
4*/
5
6define("TOKEN", "weixin");
7
8$wechatObj = new wechatCallbackapiTest();
9if (!isset($_GET['echostr'])) {
10$wechatObj->responseMsg();
11 }else{
12$wechatObj->valid();
13 }
14
15class wechatCallbackapiTest
16 {
17public function valid()
18    {
19$echoStr = $_GET["echostr"];
20if($this->checkSignature()){
21echo$echoStr;
22exit;
23        }
24    }
25
26private function checkSignature()
27    {
28$signature = $_GET["signature"];
29$timestamp = $_GET["timestamp"];
30$nonce = $_GET["nonce"];
31$token = TOKEN;
32$tmpArr = array($token, $timestamp, $nonce);
33sort($tmpArr);
34$tmpStr = implode($tmpArr);
35$tmpStr = sha1($tmpStr);
36
37if($tmpStr == $signature){
38return true;
39        }else{
40return false;
41        }
42    }
43
44public function responseMsg()
45    {
46$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
47if (!empty($postStr)){
48$this->logger("R ".$postStr);
49$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
50$RX_TYPE = trim($postObj->MsgType);
51
52switch ($RX_TYPE)
53            {
54case "event":
55$result = $this->receiveEvent($postObj);
56break;
57case "text":
58$result = $this->receiveText($postObj);
59break;
60            }
61$this->logger("T ".$result);
62echo$result;
63        }else {
64echo "";
65exit;
66        }
67    }
68
69private function receiveEvent($object)
70    {
71$content = "";
72switch ($object->Event)
73        {
74case "subscribe":
75$content = "欢迎关注⽅倍⼯作室 ";
76break;
77case "unsubscribe":
78$content = "取消关注";
79break;
80        }
81$result = $this->transmitText($object, $content);
82return$result;
83    }
84
85private function receiveText($object)
86    {
87$keyword = trim($object->Content);
88
89include("weather.php");
90$content = getWeatherInfo($keyword);
91$result = $this->transmitNews($object, $content);
92return$result;
93    }
94
95
96private function transmitText($object, $content)
97    {
98$textTpl = "<xml>
99 <ToUserName><![CDATA[%s]]></ToUserName>
102 <MsgType><![CDATA[text]]></MsgType>
103 <Content><![CDATA[%s]]></Content>
104 </xml>";
105$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
106return$result;
107    }
108
109private function transmitNews($object, $arr_item)
110    {
111if(!is_array($arr_item))
112return;
113
114$itemTpl = "    <item>
115        <Title><![CDATA[%s]]></Title>
116        <Description><![CDATA[%s]]></Description>
117        <PicUrl><![CDATA[%s]]></PicUrl>
118        <Url><![CDATA[%s]]></Url>
119    </item>
120 ";
121$item_str = "";
122foreach ($arr_item as$item)
123$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
124
125$newsTpl = "<xml>
126 <ToUserName><![CDATA[%s]]></ToUserName>
127 <FromUserName><![CDATA[%s]]></FromUserName>
128 <CreateTime>%s</CreateTime>
129 <MsgType><![CDATA[news]]></MsgType>
130 <Content><![CDATA[]]></Content>
131 <ArticleCount>%s</ArticleCount>
132 <Articles>
133$item_str</Articles>
134 </xml>";
135
136$result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
137return$result;
138    }
139
140private function logger($log_content)
141    {
142    }
143 }
三、效果演⽰
四、如何扩展
五、关于接⼝更新
1. 中国天⽓⽹已经停步上述免费接⼝的更新,需要调⽤天⽓数据需要申请SWA接⼝。
2. 中国天⽓⽹的智慧天⽓接⼝在公众平台上的实现⽅法在《公众平台开发最佳实践》⼀书有讲解

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。