欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信公眾平臺開發(fā)之天氣預(yù)報功能

 更新時間:2015年08月31日 09:37:33   投稿:mrr  
這一篇文章將對大家每天都會關(guān)心的天氣查詢進行開發(fā),例如,用戶發(fā)送消息 “黃岡天氣”,則會返回黃岡實時天氣狀況,以及未來兩天甚至未來五天的天氣狀況。

最近有項目需求給微信公眾號上增加了天氣預(yù)報功能,使用百度提供的車聯(lián)網(wǎng)API V3.0中的天氣查詢功能實現(xiàn).先上一張最終效果圖:

項目需求:有連接好的微信平臺,有百度注冊帳號,需要在百度LBS開放云平臺,添加應(yīng)用,獲取AK代碼,PHP代碼編輯器,如EditPlus等

下面詳細介紹下開發(fā)步驟:

第一步:準(zhǔn)備工作

      登錄微信公眾平臺,檢查服務(wù)器配置是否已啟用,URL(服務(wù)器地址) 是否已配置Token(令牌),與自己寫的微信入口文件中的Token(令牌一致),如下圖:然后點擊提交,只至網(wǎng)頁上提示綠色背景的提交成功信息,則完成本步驟的操作


第二步:微信天氣預(yù)報數(shù)據(jù)源準(zhǔn)備

      用已注冊好的百度帳號,登錄百度LBS云平臺,添加一個應(yīng)用,獲取訪問應(yīng)用AK,及了解車聯(lián)API V3.0,天氣查詢功能相應(yīng)的接口說明文件,以按需調(diào)用需要的天氣信息.

第三步:微信公眾平臺,接口文件編寫 jiekou.php

<?php
/*
 無憂電腦技巧網(wǎng) 微信公眾號功能源碼
 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 = "歡迎關(guān)注無憂電腦技巧網(wǎng) ";
  break;
 }
 $result = $this->transmitText($object, $content);
 return $result;
 }
 private function receiveText($object)
 {
 $keyword = trim($object->Content); //獲得用戶輸入的信息
 //判斷天氣
 if(!empty( $keyword )){ //!empty 函數(shù),判斷 $keyword獲得的值是否為空
 $city = mb_substr($keyword, 0, 2, 'utf-8'); //取用戶輸入內(nèi)容前兩個字符,如"黃岡天氣" 最終取值"黃岡"
 include("weather.php"); //調(diào)用天氣接口文件
 $content = getWeatherInfo($city); //執(zhí)行天氣接口文件中的 getWeatherInfo方法.查詢 黃岡天氣.
 } else{
 $content = date("Y-m-d H:i:s",time())."\n技術(shù)支持 無憂電腦技巧網(wǎng)\nwww.51pcjq.com"; //發(fā)送其它內(nèi)容默認回復(fù)的內(nèi)容.
 }
 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 = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
 $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
 return $result;
 }
 private 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']);
 }
 $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";
 $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
 return $result;
 }
 private function logger($log_content)
 {
 }
}

第四步:使用百度車聯(lián)API V3.0接口,及訪問應(yīng)用AK碼,編號微信天氣接口源碼:

weatger.php

<?php
function getWeatherInfo($cityName){ 
if ($cityName == "" || (strstr($cityName, "+"))){ 
return "發(fā)送天氣+城市,例如'天氣深圳'"; }//用戶查詢天氣,回復(fù)關(guān)鍵詞 規(guī)則 
$url = "http://api.map.baidu.com/telematics/v3/weather?location=".urlencode($cityName)."&output=json&ak=自已申請的百度車聯(lián)API AK代碼";//構(gòu)建通過百度車聯(lián)API V3.0查詢天氣url鏈接 
$ch = curl_init();//初始化會話 curl_setopt($ch, CURLOPT_URL, $url);//設(shè)置會話參數(shù) curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//設(shè)置會話參數(shù) $output = curl_exec($ch);//執(zhí)行curl會話 
curl_close($ch);//關(guān)閉curl會話 
$result = json_decode($output, true);//函數(shù)json_decode() 的功能時將json數(shù)據(jù)格式轉(zhuǎn)換為數(shù)組。
 if ($result["error"] != 0){ 
 return $result["status"]; } 
 $curHour = (int)date('H',time()); 
 $weather = $result["results"][0];//按照微信公眾號開發(fā)文檔,組建設(shè)多圖文回復(fù)信息 
 $weatherArray[] = array("Title" => $weather['currentCity']."當(dāng)前天氣:"."溫度:".$weather['weather_data'][0]['temperature'].",".$weather['weather_data'][0]['weather'].","."風(fēng)力:".$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代碼,需使用專業(yè)的php編輯工具,如EditPlus,Dreamweaver等

上述天氣接口文件中,百度車聯(lián)api AK代碼已換成 "自已申請的百度車聯(lián)API AK代碼:請申請好后,自行填入

如要不明白的地方,可以關(guān)注我的百度空間.留言和我聯(lián)系!

微信天氣預(yù)報開發(fā)最新代碼:

 <meta http-equiv="Content-Type" content="text/html; charset=utf" />
 <?php
 header("Content-Type:text/html;charset=UTF-");
 date_default_timezone_set("PRC");
 /**
 * 最開始用的是微信提供的demo老是不成功,用了這個網(wǎng)上下載的才成功
 */
 
 //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;
 }
 }
 //測試文字回復(fù)
 public function handleText($postObj)
 {
 $fromUsername = $postObj->FromUserName;
 $toUsername = $postObj->ToUserName;
 $keyword = trim($postObj->Content);
 $time = time();
 $textTpl = "<xml>
 <ToUserName><![CDATA[%s]]></ToUserName>
 <FromUserName><![CDATA[%s]]></FromUserName>
 <CreateTime>%s</CreateTime>
 <MsgType><![CDATA[%s]]></MsgType>
 <Content><![CDATA[%s]]></Content>
 <FuncFlag></FuncFlag>
 </xml>"; 
 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 = "感謝您關(guān)注頂尖教程網(wǎng),在這里您將得到海量免費學(xué)習(xí)資源!";
 break;
 default :
 $contentStr = "Unknow Event: ".$object->Event;
 break;
 }
 $resultStr = $this->responseText($object, $contentStr);
 return $resultStr;
 }
 
 public function responseText($object, $content)
 {
 $textTpl = "<xml>
 <ToUserName><![CDATA[%s]]></ToUserName>
 <FromUserName><![CDATA[%s]]></FromUserName>
 <CreateTime>%s</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[%s]]></Content>
 <FuncFlag></FuncFlag>
 </xml>";
 $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;
 }
 }
 //天氣預(yù)報 此處漢字需要處理,想了很多辦法才沒亂碼
 private function weather($k){
 $n=urlencode($k);
 $showapi_appid = ‘‘; //去相關(guān)網(wǎng)站申請就行
 $showapi_sign = ‘deafcacefdea‘;
 $showapi_timestamp = date(‘YmdHis‘);
 $areaid=‘‘;
 $paramArr = ‘‘;
 $needHourData=‘‘;
 $url = iconv(‘gbk‘,‘utf-‘,‘http://route.showapi.com/-?‘.‘a(chǎn)rea=‘.$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;
 }
 }
 ?>

相關(guān)文章

最新評論