微信公众平台开发之天气预报功能,公众平台天气预报
最近有项目需求给微信公众号上增加了天气预报功能,使用百度提供的车联网API V3.0中的天气查询功能实现.先上一张最终效果图:
项目需求:有连接好的微信平台,有百度注册帐号,需要在百度LBS开放云平台,添加应用,获取AK代码,PHP代码编辑器,如EditPlus等
下面详细介绍下开发步骤:
第一步:准备工作
登录微信公众平台,检查服务器配置是否已启用,URL(服务器地址) 是否已配置Token(令牌),与自己写的微信入口文件中的Token(令牌一致),如下图:然后点击提交,只至网页上提示绿色背景的提交成功信息,则完成本步骤的操作
第二步:微信天气预报数据源准备
用已注册好的百度帐号,登录百度LBS云平台,添加一个应用,获取访问应用AK,及了解车联API V3.0,天气查询功能相应的接口说明文件,以按需调用需要的天气信息.
第三步:微信公众平台,接口文件编写 jiekou.php
<?php /* 无忧电脑技巧网 微信公众号功能源码 CopyRight 2015 All Rights Reserved */ define("TOKEN", "weixin2015"); $wechatObj = new wechatCallbackapiTest(); if (!isset($_GET['echostr'])) { $wechatObj->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技术支持 无忧电脑技巧网\nwww.51pcjq.com"; //发送其它内容默认回复的内容. } 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 = "<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, $newsArray) { if(!is_array($newsArray)){ return ""; } $itemTpl = " <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> "; $item_str = ""; foreach ($newsArray 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($newsArray)); return $result; } private function logger($log_content) { } }
第四步:使用百度车联API V3.0接口,及访问应用AK码,编号微信天气接口源码:
weatger.php
<?php function getWeatherInfo($cityName){ if ($cityName == "" || (strstr($cityName, "+"))){ return "发送天气+城市,例如'天气深圳'"; }//用户查询天气,回复关键词 规则 $url = "http://api.map.baidu.com/telematics/v3/weather?location=".urlencode($cityName)."&output=json&ak=自已申请的百度车联API AK代码";//构建通过百度车联API V3.0查询天气url链接 $ch = curl_init();//初始化会话 curl_setopt($ch, CURLOPT_URL, $url);//设置会话参数 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置会话参数 $output = curl_exec($ch);//执行curl会话 curl_close($ch);//关闭curl会话 $result = json_decode($output, true);//函数json_decode() 的功能时将json数据格式转换为数组。 if ($result["error"] != 0){ return $result["status"]; } $curHour = (int)date('H',time()); $weather = $result["results"][0];//按照微信公众号开发文档,组建设多图文回复信息 $weatherArray[] = array("Title" => $weather['currentCity']."当前天气:"."温度:".$weather['weather_data'][0]['temperature'].",".$weather['weather_data'][0]['weather'].","."风力:".$weather['weather_data'][0]['wind'].".", "Description" =>"", "PicUrl" =>"http://weixin.51pcjq.com/img/weather_bg.jpg", "Url" =>""); for ($i = 0; $i < count($weather["weather_data"]); $i++) { $weatherArray[] = array("Title"=> $weather["weather_data"][$i]["date"]."\n". $weather["weather_data"][$i]["weather"]." ". $weather["weather_data"][$i]["wind"]." ". $weather["weather_data"][$i]["temperature"]."", "Description"=>"", "PicUrl"=>(($curHour >= 6) && ($curHour < 18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"], "Url"=>""); } return $weatherArray;}?>
注意事项
微信公众平台 TOKEN 与自己编写的微信接口文件中的 TOKEN 的值必须保持一致
编写php代码,需使用专业的php编辑工具,如EditPlus,Dreamweaver等
上述天气接口文件中,百度车联api AK代码已换成 "自已申请的百度车联API AK代码:请申请好后,自行填入
如要不明白的地方,可以关注我的百度空间.留言和我联系!
微信天气预报开发最新代码:
<meta http-equiv="Content-Type" content="text/html; charset=utf" /> <?php header("Content-Type:text/html;charset=UTF-"); date_default_timezone_set("PRC"); /** * 最开始用的是微信提供的demo老是不成功,用了这个网上下载的才成功 */ //define your token define("TOKEN", "djjc"); $wechatObj = new wechatCallbackapiTest(); //微信接入操作,成功接入了直接注释了就行了 $wechatObj->responseMsg(); //$wechatObj->valid(); class wechatCallbackapiTest { /*public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } }*/ public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA); $RX_TYPE = trim($postObj->MsgType); switch($RX_TYPE) { case "text": $resultStr = $this->handleText($postObj); break; case "event": $resultStr = $this->handleEvent($postObj); break; default: $resultStr = "Unknow msg type: ".$RX_TYPE; break; } echo $resultStr; }else { echo ""; exit; } } //测试文字回复 public function handleText($postObj) { $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag></FuncFlag> </xml>"; if(!empty( $keyword )) { $msgType = "text"; switch($keyword){ case "你好": $contentStr = "你好!"; break; case "你叫什么名字": $contentStr = "我是顶尖机器人"; break; //判断是否为天气 case $keywords+"天气"; $str = mb_substr($keyword,-,,"UTF-"); $str_key = mb_substr($keyword,,-,"UTF-"); if($str=="天气"){ $data = $this->weather($str_key)->showapi_res_body; $data=‘[今天白天]‘.$data->f->day_weather."\n"; $data=‘[今天夜间]‘.$data->f->night_weather."\n"; $data=‘[明天白天]‘.$data->f->day_weather."\n"; $data=‘[明天夜间]‘.$data->f->night_weather."\n"; $contentStr = $data.$data.$data.$data; } break; default: $contentStr = "听不懂您在讲什么"; break; } $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } } public function handleEvent($object) { $contentStr = ""; switch ($object->Event) { case "subscribe": $contentStr = "感谢您关注顶尖教程网,在这里您将得到海量免费学习资源!"; break; default : $contentStr = "Unknow Event: ".$object->Event; break; } $resultStr = $this->responseText($object, $contentStr); return $resultStr; } public function responseText($object, $content) { $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag></FuncFlag> </xml>"; $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag); return $resultStr; } 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 = sha( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } //天气预报 此处汉字需要处理,想了很多办法才没乱码 private function weather($k){ $n=urlencode($k); $showapi_appid = ‘‘; //去相关网站申请就行 $showapi_sign = ‘deafcacefdea‘; $showapi_timestamp = date(‘YmdHis‘); $areaid=‘‘; $paramArr = ‘‘; $needHourData=‘‘; $url = iconv(‘gbk‘,‘utf-‘,‘http://route.showapi.com/-?‘.‘area=‘.$n.‘&areaid=&needHourData=&needIndex=&needMoreDay=&showapi_appid=‘.$showapi_appid.‘&showapi_timestamp=‘.$showapi_timestamp.‘&showapi_sign=‘.$showapi_sign); $result = file_get_contents($url); $result = json_decode($result); return $result; } } ?>

微信文件的过期时间需要根据情况来判断:1、如果发送的文件没有打开过,则在72小时以后微信系统会自动清理掉,即过了三天文件就会过期;2、如果已经查看了微信文件,但是并没有下载(当然已经下载的文件也是一样的),那么文件是可以保留180天的,在这180天以内随时都可以去下载。

区别:1、拉黑后对话框从主页消失,但是聊天记录还在;删除后聊天记录全部消失不见了。2、拉黑后还能发给他,但是收不到他的消息;删除后不能发信息了。3、拉黑后双方都不可见彼此的朋友圈;删除对方以后,你看不到对方的朋友圈了,对方是否能看到你的,取决于设置(允许陌生人查看十张照片)与否,如果设置则可以看到朋友圈。

支持微信付款的购物平台有:1、京东,是中国的综合网络零售商;2、唯品会,是一家在线销售品牌折扣商品的互联网公司;3、拼多多,是社交新电商领导者,更懂消费者的购物平台;4、京喜,是京东旗下生活消费商城;5、蘑菇街,一个电子商务网站;6、聚美优品,是一家以销售化妆品为主的时尚购物网站;7、微店,是一个云推广电子商务平台;8、考拉海购,是一个跨境海淘业务为主的会员电商平台。

微信查看ip地址的方法:1、登录电脑版微信,右键点击屏幕下方的任务栏,点击“任务管理器”;2、弹出任务管理器时,点击左下角的“详细信息”;3、任务管理器进入“性能”选项,点击“打开资源监视器”;4、选择“网络”,勾选微信进程“Wechat.exe”;5、点击下面的“TCP连接”即可监视微信网络IP相关情况,发送消息得到回复就会显示他人的IP地址。

可以。未经过实名认证的微信号,可以绑定他人的银行卡,但在绑定过程中需要提供银行卡的开户人姓名、开户行地址、开户时预留的联系方式及银行卡支付密码;已通过实名认证的微信号,无法绑定他人银行卡,只能添加使用自己身份证办理的银行卡。

不是,一个身份证能绑定5个微信。按照微信当前规定,一个身份证可以实名认证5个微信号;如果已经实名认证了5个微信账号,但是还想要继续实名,就要把已经实名认证的一些不用的微信号清除以后,才可以再实名认证新的微信号。

闲鱼是不支持微信支付的,仅支持使用支付宝进行付款;闲鱼是阿里巴巴旗下闲置交易平台App客户端,会员只要使用淘宝或支付宝账户登录,无需经过复杂的开店流程,即可达成包括一键转卖个人淘宝账号中“已买到宝贝”、自主手机拍照上传二手闲置物品、以及在线交易等诸多功能。

电脑微信打字打一个少一个是因为开启了改写状态,其解决办法:1、打开电脑微信;2、在微信聊天窗口输入对话文字内容;3、找到并按下键盘上的Insert键即可正常输入文字内容。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
