php微信开发之百度天气预报


Posted in PHP onNovember 18, 2016

本文实例为大家分享了php微信百度天气预报的开发代码,供大家参考,具体内容如下

1.登录百度ak申请:http://lbsyun.baidu.com/apiconsole/key

php微信开发之百度天气预报

2.实现天气信息功能

baiduWeather.php 

<?php 
/** 
 * 使用百度天气预报接口获取城市天气信息案例实现 
 */ 
 
 //获取城市天气信息 
 function getWeatherInfo($cityName){ 
  if($cityName == "" || (strstr($cityName,"+"))){ 
   return "发送城市加天气,例如北京天气"; 
  } 
  //获取到的ak 
  $ak = your ak; 
  //获取到的sk 
  $sk = your sk; 
  //调用接口 
  $url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sk=%s'; 
  $uri = '/telematics/v3/weather'; 
 
  $location = $cityName; 
  $output = 'json'; 
  $querystring_arrays = array( 
   'ak' => $ak, 
   'location' => $location, 
   'output' => $output 
  ); 
 
  $querystring = http_build_query($querystring_arrays); 
  //生成sn 
  $sn = md5(urlencode($uri.'?'.$querystring.$sk)); 
  $targetUrl = sprintf($url,$ak,urlencode($location),$output,$sn); 
 
  $ch = curl_init(); 
  curl_setopt($ch,CURLOPT_URL,$targetUrl); 
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
  $result = curl_exec($ch); 
  curl_close($ch); 
  $result = json_decode($result,true); 
 
  if($result["error"]!=0){ 
   return $result["status"]; 
  } 
 
  $curHour = (int)date('H',time()); 
  $weather = $result["results"][0]; 
  $weatherArray[]=array("Title"=>$weather['currentCity']."天气预报","Description"=>"","PicUrl"=>"","Url"=>""); 
  for($i = 0;$i<count($weather["weather_data"]);$i++){ 
   $weatherArray[] = array("Title"=> 
    $weather["weather_data"][$i]["data"]."\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; 
 }

3.实现天气消息事件

<?php 
/* 
 CopyRight 2016 All Rights Reserved 
*/ 
 
define("TOKEN", "weixin"); 
/** 
 * 百度天气预报案例实现 
 * 实现思路: 
 * 1.申请百度ak、sk 
 * 2.使用百度天气预报接口 
 * 3.实现天气信息功能 
 * 4.实现事件响应功能 
 */ 
$wechatObj = new wechatCallbackapiTest(); 
if (!isset($_GET['echostr'])) { 
 $wechatObj->responseMsg(); 
}else{ 
 $wechatObj->valid(); 
} 
 
class wechatCallbackapiTest 
{ 
 //验证签名 
 public function valid() 
 { 
  $echoStr = $_GET["echostr"]; 
  if($this->checkSignature()){ 
   header('content-type:text'); 
   echo $echoStr; 
   exit; 
  } 
 } 
 
 public 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; 
    default: 
     $result = "unknown msg type: ".$RX_TYPE; 
     break; 
   } 
   echo $result; 
  }else { 
   echo ""; 
   exit; 
  } 
 } 
 
 //接收事件消息 
 public function receiveEvent($object) 
 { 
  $content = ""; 
  switch ($object->Event) 
  { 
   case "subscribe": 
    $content = "欢迎关注Nicky的公众号 "; 
    $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):""; 
    break; 
   case "unsubscribe": 
    $content = "取消关注"; 
    break; 
  } 
  $result = $this->transmitText($object, $content); 
  return $result; 
 } 
 
 //接收文本消息 
 public function receiveText($object) 
 { 
  $keyword = trim($object->Content); 
 
  //自动回复模式 
 
  if (strstr($keyword, "天气")){ 
   $city = str_replace('天气','',$keyword); 
   include("baiduweather.php"); 
   $content = getWeatherInfo($city); 
  } 
  $result = $this->transmitNews($object, $content); 
  return $result; 
 } 
 
 //回复图文消息 
 public 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']); 
  } 
  $xmlTpl = "<xml> 
<ToUserName><![CDATA[%s]]></ToUserName> 
<FromUserName><![CDATA[%s]]></FromUserName> 
<CreateTime>%s</CreateTime> 
<MsgType><![CDATA[news]]></MsgType> 
<ArticleCount>%s</ArticleCount> 
<Articles> 
$item_str</Articles> 
</xml>"; 
 
  $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray)); 
  return $result; 
 } 
 
 
 //日志记录 
 public function logger($log_content) 
 { 
  if(isset($_SERVER['HTTP_APPNAME'])){ //SAE 
   sae_set_display_errors(false); 
   sae_debug($log_content); 
   sae_set_display_errors(true); 
  }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL 
   $max_size = 10000; 
   $log_filename = "log.xml"; 
   if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);} 
   file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND); 
  } 
 } 
 
} 
?>

php微信开发之百度天气预报

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
使用 eAccelerator加速PHP代码的方法
Sep 30 PHP
火车头discuz6.1 完美采集的php接口文件
Sep 13 PHP
php dirname(__FILE__) 获取当前文件的绝对路径
Jun 28 PHP
PHP中空字符串介绍0、null、empty和false之间的关系
Sep 25 PHP
解析php做推送服务端实现ios消息推送
Jul 01 PHP
解析PHP中$_FILES的使用以及注意事项
Jul 05 PHP
Laravel 5框架学习之Laravel入门和新建项目
Apr 07 PHP
浅谈PHP中JSON数据操作
Jul 01 PHP
Smarty模板变量调节器用法分析
May 23 PHP
PHP读取大文件的几种方法介绍
Oct 27 PHP
Thinkphp5+plupload实现的图片上传功能示例【支持实时预览】
May 08 PHP
laravel实现上传图片的两种方式小结
Oct 12 PHP
PHP-FPM运行状态的实时查看及监控详解
Nov 18 #PHP
PHP+iframe图片上传实现即时刷新效果
Nov 18 #PHP
PHP批量获取网页中所有固定种子链接的方法
Nov 18 #PHP
PHP实现二维数组按某列进行排序的方法
Nov 18 #PHP
PHP二维数组去重实例分析
Nov 18 #PHP
浅谈php fopen下载远程文件的函数
Nov 18 #PHP
PHP实现的自定义数组排序函数与排序类示例
Nov 18 #PHP
You might like
php笔记之:php函数range() round()和list()的使用说明
2013/04/26 PHP
php语法检查的方法总结
2019/01/21 PHP
php把文件设置为插件的技巧方法
2020/02/03 PHP
js类中的公有变量和私有变量
2008/07/24 Javascript
IE浏览器兼容Firefox的JS脚本的代码
2008/10/23 Javascript
网页自动跳转代码收集
2009/09/27 Javascript
用js实现小球的自由移动代码
2013/04/22 Javascript
String.prototype实现的一些javascript函数介绍
2013/11/22 Javascript
AngularJS语法详解
2015/01/23 Javascript
JavaScript关联数组用法分析【概念、定义、遍历】
2017/03/15 Javascript
在Vue组件中获取全局的点击事件方法
2018/09/06 Javascript
vuex的module模块用法示例
2018/11/12 Javascript
vue 导航内容设置选中状态样式的例子
2019/11/01 Javascript
vue中渲染对象中属性时显示未定义的解决
2020/07/31 Javascript
vue 路由缓存 路由嵌套 路由守卫 监听物理返回操作
2020/08/06 Javascript
详解Vue3 Teleport 的实践及原理
2020/12/02 Vue.js
[03:36]2015国际邀请赛第二日现场精彩集锦
2015/08/06 DOTA
[54:10]Spirit vs NB Supermajor小组赛 A组败者组决赛 BO3 第一场 6.2
2018/06/03 DOTA
[57:29]Alliance vs KG 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/17 DOTA
用Python写的图片蜘蛛人代码
2012/08/27 Python
简单的通用表达式求10乘阶示例
2014/03/03 Python
用Python实现QQ游戏大家来找茬辅助工具
2014/09/14 Python
python基于urllib实现按照百度音乐分类下载mp3的方法
2015/05/25 Python
Python多线程实现同步的四种方式
2017/05/02 Python
Python greenlet和gevent使用代码示例解析
2020/04/01 Python
解决Keyerror ''acc'' KeyError: ''val_acc''问题
2020/06/18 Python
tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this T
2020/06/22 Python
基于python判断字符串括号是否闭合{}[]()
2020/09/21 Python
Python 字典一个键对应多个值的方法
2020/09/29 Python
html5使用canvas实现图片下载功能的示例代码
2017/08/26 HTML / CSS
原生 JS+CSS+HTML 实现时序图的方法
2019/07/31 HTML / CSS
Schutz鞋官方网站:Schutz Shoes
2017/12/13 全球购物
三爱活动实施方案
2014/03/19 职场文书
节能减耗标语
2014/06/21 职场文书
党员自我剖析材料
2014/08/31 职场文书
毕业生评语大全
2015/01/04 职场文书