最近有项目需求给微信公众号上增加了天气预报功能,使用百度提供的车联网api v3.0中的天气查询功能实现.先上一张最终效果图:
项目需求:有连接好的微信平台,有百度注册帐号,需要在百度lbs开放云平台,添加应用,获取ak代码,php代码编辑器,如editplus等
下面详细介绍下开发步骤:
第一步:准备工作
登录微信公众平台,检查服务器配置是否已启用,url(服务器地址) 是否已配置token(令牌),与自己写的微信入口文件中的token(令牌一致),如下图:然后点击提交,只至网页上提示绿色背景的提交成功信息,则完成本步骤的操作
第二步:微信天气预报数据源准备
用已注册好的百度帐号,登录百度lbs云平台,添加一个应用,获取访问应用ak,及了解车联api v3.0,天气查询功能相应的接口说明文件,以按需调用需要的天气信息.
第三步:微信公众平台,接口文件编写 jiekou.php
responsemsg();}else{ $wechatobj->valid();}class wechatcallbackapitest{ //验证签名 public function valid() { $echostr = $_get[echostr]; $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){ echo $echostr; exit; } } public function responsemsg() { // $poststr = $globals[http_raw_post_data]; $poststr = file_get_contents(php://input); if (!empty($poststr)){ $this->logger(r .$poststr); $postobj = simplexml_load_string($poststr, 'simplexmlelement', libxml_nocdata); $rx_type = trim($postobj->msgtype); $result = ; 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) { switch ($object->event) { case subscribe: $content = 欢迎关注无忧电脑技巧网 ; break; } $result = $this->transmittext($object, $content); return $result; } private function receivetext($object) { $keyword = trim($object->content); //获得用户输入的信息 //判断天气 if(!empty( $keyword )){ //!empty 函数,判断 $keyword获得的值是否为空 $city = mb_substr($keyword, 0, 2, 'utf-8'); //取用户输入内容前两个字符,如黄冈天气 最终取值黄冈 include(weather.php); //调用天气接口文件 $content = getweatherinfo($city); //执行天气接口文件中的 getweatherinfo方法.查询 黄冈天气. } else{ $content = date(y-m-d h:i:s,time()).\n技术支持 无忧电脑技巧网\n; //发送其它内容默认回复的内容. } if(is_array($content)){ if (isset($content[0]['picurl'])){ $result = $this->transmitnews($object, $content); }else if (isset($content['musicurl'])){ $result = $this->transmitmusic($object, $content); } }else{ $result = $this->transmittext($object, $content); } return $result; } private function transmittext($object, $content) { if (!isset($content) || empty($content)){ return ; } $texttpl = %s; $result = sprintf($texttpl, $object->fromusername, $object->tousername, time(), $content); return $result; } private function transmitnews($object, $newsarray) { if(!is_array($newsarray)){ return ; } $itemtpl = ; $item_str = ; foreach ($newsarray as $item){ $item_str .= sprintf($itemtpl, $item['title'], $item['description'], $item['picurl'], $item['url']); } $newstpl = %s%s$item_str; $result = sprintf($newstpl, $object->fromusername, $object->tousername, time(), count($newsarray)); return $result; } private function logger($log_content) { }}
第四步:使用百度车联api v3.0接口,及访问应用ak码,编号微信天气接口源码:
weatger.php
