微信公众平台开发入门:[7]开发天气预报功能

2025-12-26 18:29:28

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

2、国家根节点接口

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

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

微信公众平台开发入门:[7]开发天气预报功能

微信公众平台开发入门:[7]开发天气预报功能

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

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

在这个接口中主要获取城市名称及相应的城市编码。例如,深圳的城市编码为:101280601。可以编写程序将全国城市拓扑结构采集下来。

微信公众平台开发入门:[7]开发天气预报功能

微信公众平台开发入门:[7]开发天气预报功能

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

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

{

    "weatherinfo": {

        "city": "深圳",

        "cityid": "101280601",

        "temp": "12",

        "WD": "东北风",

        "WS": "1级",

        "SD": "75%",

        "WSE": "1",

        "time": "21:20",

        "isRadar": "1",

        "Radar": "JC_RADAR_AZ9755_JB"

    }

}

实时天气数据参数说明,如下所示(3)

微信公众平台开发入门:[7]开发天气预报功能

微信公众平台开发入门:[7]开发天气预报功能

微信公众平台开发入门:[7]开发天气预报功能

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

该接口以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": "不易发"

    }

}

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

微信公众平台开发入门:[7]开发天气预报功能

微信公众平台开发入门:[7]开发天气预报功能

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

微信公众平台开发入门:[7]开发天气预报功能

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)

    {

    }

}

1、成型后的演示效果如下

微信公众平台开发入门:[7]开发天气预报功能

1、在数据库加入邮编、区号、拼音等字段,可以扩展成使用区号等方式查询

2、拥有高级接口的用户,可以使用结合语音识别+中文分词技术,实现语音版的智能查询

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢