微信公眾平台開發之天氣預報功能_php執行個體

來源:互聯網
上載者:User
最近有項目需求給公眾號上增加了天氣預報功能,使用百度提供的車連網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 = "%s%s%stext%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]]> %s %s %s "; $item_str = ""; foreach ($newsArray as $item){  $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']); } $newsTpl = "%s%s%snews%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

<?phpfunction 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代碼:請申請好後,自行填入

如要不明白的地方,可以關注我的百度空間.留言和我聯絡!

天氣預報開發最新代碼:

  <?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 = " %s %s %s %s %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 %s %s text %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; } } ?>
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.