侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

微信公众平台开发之天气预报功能

微信(小程序)  /  管理员 发布于 5年前   423

最近有项目需求给微信公众号上增加了天气预报功能,使用百度提供的车联网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技术支持 无忧电脑技巧网\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 = "%s"; $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content); return $result; } private function transmitNews($object, $newsArray) { if(!is_array($newsArray)){  return ""; } $itemTpl = "  <![CDATA[%s]]>    "; $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

 $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代码:请申请好后,自行填入

如要不明白的地方,可以关注我的百度空间.留言和我联系!

微信天气预报开发最新代码:

  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 = "   %s    ";  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 = "   %s    "; $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; } } ?>

您可能感兴趣的文章:

  • android 仿微信聊天气泡效果实现思路
  • 微信公众平台天气预报功能开发


  • 上一条:
    微信公众平台开发之处理图片.Net代码解析
    下一条:
    微信支付 开发账号体系各参数详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 微信模板消息改版后发送规则记录(微信订阅消息参数值内容限制说明)(1个评论)
    • 微信支付v3对接所需工具及命令(0个评论)
    • 2023年9月1日起:微信小程序必须备案才能上线运营(0个评论)
    • 腾讯官方客服回应了:微信好友上限约10000个!(1个评论)
    • 2023年做微信小程序的老铁注意:新增收费项、微信小程序获取手机号也收费了(2个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-10
    • 2018-01
    • 2020-03
    • 2021-06
    • 2021-10
    • 2022-03
    • 2023-02
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客