欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-04 16:23:41
本文实例为大家分享了php微信百度天气预报的开发代码,供大家参考,具体内容如下 1.登录百度ak申请: 2.实现天气信息功能 baiduweather.p...

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

1.登录百度ak申请:

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微信开发之百度天气预报

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