分享

微信公众平台开发(五) 天气预报功能开发

 Be_The_Change 2013-11-27

一、简介

前面几篇文章对微信公众平台的开通及简单使用做了简单的介绍,但都没有涉及到实际使用中的问题,例如天气查询,公交查询,快递查询等。接下来的几篇文章将对实际生活中会经常使用到的一些功能进行开发讲解,以供读者参考。

这一篇文章将对大家每天都会关心的天气查询进行开发,例如,用户发送消息 “苏州天气”,则会返回苏州实时天气状况,以及未来两天甚至未来五天的天气状况。

二、思路分析

首先要对用户发送过来的消息进行判断,判断消息里是否含有“天气”关键字,如果含有,则需要继续提取地区信息,然后再通过中国天气网(http://www.weather.com.cn)提供的开放API进行相关地区天气查询。

三、关键字判断与地区读取

用户发送过来查询天气的消息的格式是固定好的,即 “地区+天气”,所以首先截取后两个字,判断是否为 “天气” 关键字。

使用php函数 mb_substr() 截取,关于该函数的用法:

  1. mb_substr — 获取字符串的部分

  2.   string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

  3. 说明:根据字符数执行一个多字节安全的 substr() 操作。 位置是从 str 的开始位置进行计数。 第一个字符的位置是 0。第二个字符的位置是 1,以此类推。

  4. 参数:
  5. str
  6. 从该 string 中提取子字符串。

  7. start
  8. str 中要使用的第一个字符的位置。
  9. 正数 -> 从字符串开头指定位置开始;
  10. 负数 -> 从字符串结尾指定位置开始;

  11. length
  12. str 中要使用的最大字符数。
  13. 正数 -> 从 start 处开始最多包括 length 个字符;
  14. 负数 -> string 末尾处的 length 个字符将会被漏掉(若 start 是负数则从字符串开头算起)。

  15. encoding
  16. encoding 参数为字符编码。如果省略,则使用内部字符编码。

  17. 返回值:
  18. mb_substr() 函数根据 start 和 length 参数返回 str 中指定的部分。
复制代码

$str = mb_substr($keyword,-2,2,"UTF-8");

从消息的结尾数第二个字符开始截取,截取两个字符,然后加以判断是否为 “天气” 关键字。

下面进行地区提取,还是使用 mb_substr() 函数。

$str_key = mb_substr($keyword,0,-2,"UTF-8");

从消息的开头开始,截掉末尾的两个字符(天气),既得地区关键字。

然后进行判断,继而调用函数查询天气数据。

  1. if($str == '天气' && !empty($str_key))
  2. {
  3.      //调用函数查询天气数据
  4. }
复制代码

四、调用 weather() 函数查询

我们这里调用的是中国国家气象局提供的天气预报API接口,接口地址:http://m.weather.com.cn/data/101190401.html

URL中的数字指代城市的编号101190401(苏州),其他城市对应关系将在下面提供。

该接口返回信息比较全面,也是以json格式提供,格式如下:

  1. {"weatherinfo":{
  2. //基本信息;
  3. "city":"苏州","city_en":"suzhou",
  4. "date_y":"2013年7月9日","date":"","week":"星期二","fchh":"18","cityid":"101190401",
  5. //摄氏温度
  6. "temp1":"30℃~37℃",
  7. "temp2":"30℃~37℃",
  8. "temp3":"29℃~35℃",
  9. "temp4":"27℃~33℃",
  10. "temp5":"27℃~31℃",
  11. "temp6":"27℃~35℃",
  12. //华氏温度;
  13. "tempF1":"86℉~98.6℉",
  14. "tempF2":"86℉~98.6℉",
  15. "tempF3":"84.2℉~95℉",
  16. "tempF4":"80.6℉~91.4℉",
  17. "tempF5":"80.6℉~87.8℉",
  18. "tempF6":"80.6℉~95℉",
  19. //天气描述;
  20. "weather1":"晴转多云",
  21. "weather2":"晴转多云",
  22. "weather3":"晴转多云",
  23. "weather4":"多云",
  24. "weather5":"雷阵雨转中雨",
  25. "weather6":"雷阵雨转多云",
  26. //天气描述图片序号
  27. "img1":"0",
  28. "img2":"1",
  29. "img3":"0",
  30. "img4":"1",
  31. "img5":"0",
  32. "img6":"1",
  33. "img7":"1",
  34. "img8":"99",
  35. "img9":"4",
  36. "img10":"8",
  37. "img11":"4",
  38. "img12":"1",
  39. //图片名称;
  40. "img_single":"1",
  41. "img_title1":"晴",
  42. "img_title2":"多云",
  43. "img_title3":"晴",
  44. "img_title4":"多云",
  45. "img_title5":"晴",
  46. "img_title6":"多云",
  47. "img_title7":"多云",
  48. "img_title8":"多云",
  49. "img_title9":"雷阵雨",
  50. "img_title10":"中雨",
  51. "img_title11":"雷阵雨",
  52. "img_title12":"多云",
  53. "img_title_single":"多云",
  54. //风速描述
  55. "wind1":"西南风3-4级",
  56. "wind2":"西南风3-4级",
  57. "wind3":"东南风3-4级",
  58. "wind4":"东南风3-4级转4-5级",
  59. "wind5":"东南风4-5级转西南风3-4级",
  60. "wind6":"西南风3-4级转4-5级",
  61. //风速级别描述
  62. "fx1":"西南风",
  63. "fx2":"西南风",
  64. "fl1":"3-4级",
  65. "fl2":"3-4级",
  66. "fl3":"3-4级",
  67. "fl4":"3-4级转4-5级",
  68. "fl5":"4-5级转3-4级",
  69. "fl6":"3-4级转4-5级",
  70. //今日穿衣指数;
  71. "index":"炎热",
  72. "index_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
  73. //48小时穿衣指数
  74. "index48":"炎热",
  75. "index48_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
  76. //紫外线及48小时紫外线
  77. "index_uv":"中等",
  78. "index48_uv":"中等",
  79. //洗车指数
  80. "index_xc":"适宜",
  81. //旅游指数
  82. "index_tr":"较不宜",
  83. //舒适指数
  84. "index_co":"很不舒适",
  85. "st1":"36",
  86. "st2":"28",
  87. "st3":"36",
  88. "st4":"28",
  89. "st5":"34",
  90. "st6":"27",
  91. //晨练指数
  92. "index_cl":"较适宜",
  93. //晾晒指数
  94. "index_ls":"适宜",
  95. //过敏指数
  96. "index_ag":"不易发"}}
复制代码

我们可以通过解析JSON,获取相应城市的天气数据。

weather() 函数如下:

  1. private function weather($n){
  2.     include("weather_cityId.php");
  3.     $c_name=$weather_cityId[$n];
  4.     if(!empty($c_name)){
  5.         $json=file_get_contents("http://m.weather.com.cn/data/".$c_name.".html");
  6.         return json_decode($json);
  7.     } else {
  8.         return null;
  9.     }
  10. }
复制代码

这里include 了一个城市对应关系文件 weather_cityId.php,格式如下:

  1. <?php
  2. $weather_cityId = array("北京"=>"101010100","上海"=>"101020100","苏州"=>"101190401");
  3. ?>
复制代码

根据传入的城市名,得到城市代码,如果不为空,则调用中国天气网的API进行查询,返回json格式的数据,然后进行解析并返回数据,如果为空,则返回null值。

五、组织回复消息形式

判断返回数据是否为空,若为空,则 $contentStr = "抱歉,没有查到\"".$str_key."\"的天气信息!";

若返回数据不为空,则:


  1. <font color="#333333"><font face="verdana, Arial, Helvetica, sans-serif">$contentStr = "【".$data->weatherinfo->city."天气预报】\n".$data->weatherinfo->date_y." ".$data->weatherinfo->fchh."时发布"."\n\n实时天气\n".$data->weatherinfo->weather1." ".$data->weatherinfo->temp1." ".$data->weatherinfo->wind1."\n\n温馨提示:".$data->weatherinfo->index_d."\n\n明天\n".$data->weatherinfo->weather2." ".$data->weatherinfo->temp2." ".$data->weatherinfo->wind2."\n\n后天\n".$data->weatherinfo->weather3." ".$data->weatherinfo->temp3." ".$data->weatherinfo->wind3;</font></font>
复制代码

说明:

$data->weatherinfo->city  //获取城市名,这里为苏州

$data->weatherinfo->date_y  //获取日期,这里为2013年7月9日

$data->weatherinfo->fchh  //数据发布时间

$data->weatherinfo->weather1  //实时天气

$data->weatherinfo->temp1  //实时温度

$data->weatherinfo->wind1  //实时风向和风速

$data->weatherinfo->index_d  //穿衣指数

weather2, temp2, wind2 分别代表了明天的天气,温度和风向风速,其他的以此类推。

\n  //表示换行

六、测试

七、完整代码

  1. <?php
  2. /**
  3.   * wechat php test
  4.   */

  5. //define your token
  6. define("TOKEN", "zhuojin");
  7. $wechatObj = new wechatCallbackapiTest();
  8. $wechatObj->responseMsg();
  9. //$wechatObj->valid();

  10. class wechatCallbackapiTest
  11. {
  12.     /*public function valid()
  13.     {
  14.         $echoStr = $_GET["echostr"];

  15.         //valid signature , option
  16.         if($this->checkSignature()){
  17.             echo $echoStr;
  18.             exit;
  19.         }
  20.     }*/

  21.     public function responseMsg()
  22.     {
  23.         //get post data, May be due to the different environments
  24.         $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

  25.           //extract post data
  26.         if (!empty($postStr)){
  27.                 
  28.                   $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  29.                 $RX_TYPE = trim($postObj->MsgType);

  30.                 switch($RX_TYPE)
  31.                 {
  32.                     case "text":
  33.                         $resultStr = $this->handleText($postObj);
  34.                         break;
  35.                     case "event":
  36.                         $resultStr = $this->handleEvent($postObj);
  37.                         break;
  38.                     default:
  39.                         $resultStr = "Unknow msg type: ".$RX_TYPE;
  40.                         break;
  41.                 }
  42.                 echo $resultStr;
  43.         }else {
  44.             echo "";
  45.             exit;
  46.         }
  47.     }

  48.     public function handleText($postObj)
  49.     {
  50.         $fromUsername = $postObj->FromUserName;
  51.         $toUsername = $postObj->ToUserName;
  52.         $keyword = trim($postObj->Content);
  53.         $time = time();
  54.         $textTpl = "<xml>
  55.                     <ToUserName><![CDATA[%s]]></ToUserName>
  56.                     <FromUserName><![CDATA[%s]]></FromUserName>
  57.                     <CreateTime>%s</CreateTime>
  58.                     <MsgType><![CDATA[%s]]></MsgType>
  59.                     <Content><![CDATA[%s]]></Content>
  60.                     <FuncFlag>0</FuncFlag>
  61.                     </xml>";             
  62.         if(!empty( $keyword ))
  63.         {
  64.             $msgType = "text";

  65.             //天气
  66.             $str = mb_substr($keyword,-2,2,"UTF-8");
  67.             $str_key = mb_substr($keyword,0,-2,"UTF-8");
  68.             if($str == '天气' && !empty($str_key)){
  69.                 $data = $this->weather($str_key);
  70.                 if(empty($data->weatherinfo)){
  71.                     $contentStr = "抱歉,没有查到\"".$str_key."\"的天气信息!";
  72.                 } else {
  73.                     $contentStr = "【".$data->weatherinfo->city."天气预报】\n".$data->weatherinfo->date_y." ".$data->weatherinfo->fchh."时发布"."\n\n实时天气\n".$data->weatherinfo->weather1." ".$data->weatherinfo->temp1." ".$data->weatherinfo->wind1."\n\n温馨提示:".$data->weatherinfo->index_d."\n\n明天\n".$data->weatherinfo->weather2." ".$data->weatherinfo->temp2." ".$data->weatherinfo->wind2."\n\n后天\n".$data->weatherinfo->weather3." ".$data->weatherinfo->temp3." ".$data->weatherinfo->wind3;
  74.                 }
  75.             } else {
  76.                 $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待...";
  77.             }
  78.             $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  79.             echo $resultStr;
  80.         }else{
  81.             echo "Input something...";
  82.         }
  83.     }

  84.     public function handleEvent($object)
  85.     {
  86.         $contentStr = "";
  87.         switch ($object->Event)
  88.         {
  89.             case "subscribe":
  90.                 $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待...";
  91.                 break;
  92.             default :
  93.                 $contentStr = "Unknow Event: ".$object->Event;
  94.                 break;
  95.         }
  96.         $resultStr = $this->responseText($object, $contentStr);
  97.         return $resultStr;
  98.     }
  99.     
  100.     public function responseText($object, $content, $flag=0)
  101.     {
  102.         $textTpl = "<xml>
  103.                     <ToUserName><![CDATA[%s]]></ToUserName>
  104.                     <FromUserName><![CDATA[%s]]></FromUserName>
  105.                     <CreateTime>%s</CreateTime>
  106.                     <MsgType><![CDATA[text]]></MsgType>
  107.                     <Content><![CDATA[%s]]></Content>
  108.                     <FuncFlag>%d</FuncFlag>
  109.                     </xml>";
  110.         $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
  111.         return $resultStr;
  112.     }

  113.     private function weather($n){
  114.         include("weather_cityId.php");
  115.         $c_name=$weather_cityId[$n];
  116.         if(!empty($c_name)){
  117.             $json=file_get_contents("http://m.weather.com.cn/data/".$c_name.".html");
  118.             return json_decode($json);
  119.         } else {
  120.             return null;
  121.         }
  122.     }

  123.     private function checkSignature()
  124.     {
  125.         $signature = $_GET["signature"];
  126.         $timestamp = $_GET["timestamp"];
  127.         $nonce = $_GET["nonce"];    
  128.                 
  129.         $token = TOKEN;
  130.         $tmpArr = array($token, $timestamp, $nonce);
  131.         sort($tmpArr);
  132.         $tmpStr = implode( $tmpArr );
  133.         $tmpStr = sha1( $tmpStr );
  134.         
  135.         if( $tmpStr == $signature ){
  136.             return true;
  137.         }else{
  138.             return false;
  139.         }
  140.     }
  141. }

  142. ?>
复制代码

关于城市对应关系文件 weather_cityId.php,目前更新到了2564个城市,以后还会继续增加,请到QQ群 203773954 下载吧。

八、关注

请关注 卓锦苏州 微信公众账号,卓锦苏州 基于BAE 平台开发,针对于主流的微信功能进行开发测试。

您可以关注 卓锦苏州 公众账号进行功能测试,以及获取新的应用开发。

1. 登录微信客户端,通讯录 -> 添加朋友 -> 查找公众号 -> zhuojinsz,查找并关注。

2. 扫描二维码:

卓锦苏州 功能列表。


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多