微信開發-天氣預報功能

高洛峰
發布: 2017-03-11 14:27:16
原創
2592 人瀏覽過

這篇文章主要為大家詳細介紹了php微信開發之百度天氣預報的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了php微信百度天氣預報的開發程式碼,供大家參考,具體內容如下

1.登入百度ak申請:http://www.php.cn/


2.實作天氣資訊功能

#Weather.php 


##

<?php 
/** 
 * 使用百度天气预报接口获取城市天气信息案例实现 
 */ 
 
 //获取城市天气信息 
 function getWeatherInfo($cityName){ 
  if($cityName == "" || (strstr($cityName,"+"))){ 
   return "发送城市加天气,例如北京天气"; 
  } 
  //获取到的ak 
  $ak = your ak; 
  //获取到的sk 
  $sk = your sk; 
  //调用接口 
  $url = &#39;http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sk=%s&#39;; 
  $uri = &#39;/telematics/v3/weather&#39;; 
 
  $location = $cityName; 
  $output = &#39;json&#39;; 
  $querystring_arrays = array( 
   &#39;ak&#39; => $ak, 
   &#39;location&#39; => $location, 
   &#39;output&#39; => $output 
  ); 
 
  $querystring = http_build_query($querystring_arrays); 
  //生成sn 
  $sn = md5(urlencode($uri.&#39;?&#39;.$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(&#39;H&#39;,time()); 
  $weather = $result["results"][0]; 
  $weatherArray[]=array("Title"=>$weather[&#39;currentCity&#39;]."天气预报","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[&#39;echostr&#39;])) { 
 $wechatObj->responseMsg(); 
}else{ 
 $wechatObj->valid(); 
} 
 
class wechatCallbackapiTest 
{ 
 //验证签名 
 public function valid() 
 { 
  $echoStr = $_GET["echostr"]; 
  if($this->checkSignature()){ 
   header(&#39;content-type:text&#39;); 
   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, &#39;SimpleXMLElement&#39;, 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(&#39;天气&#39;,&#39;&#39;,$keyword); 
   include("weather.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[&#39;Title&#39;], $item[&#39;Description&#39;], $item[&#39;PicUrl&#39;], $item[&#39;Url&#39;]); 
  } 
  $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[&#39;HTTP_APPNAME&#39;])){ //SAE 
   sae_set_display_errors(false); 
   sae_debug($log_content); 
   sae_set_display_errors(true); 
  }else if($_SERVER[&#39;REMOTE_ADDR&#39;] != "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(&#39;H:i:s&#39;)." ".$log_content."\r\n", FILE_APPEND); 
  } 
 } 
 
} 
?>
登入後複製

以上就是本文的全部內容,希望對大家的學習有幫助,也希望大家多多支持腳本家。


以上是微信開發-天氣預報功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板