微信公眾平臺(tái)開(kāi)發(fā)之天氣預(yù)報(bào)功能
最近有項(xiàng)目需求給微信公眾號(hào)上增加了天氣預(yù)報(bào)功能,使用百度提供的車(chē)聯(lián)網(wǎng)API V3.0中的天氣查詢功能實(shí)現(xiàn).先上一張最終效果圖:

項(xiàng)目需求:有連接好的微信平臺(tái),有百度注冊(cè)帳號(hào),需要在百度LBS開(kāi)放云平臺(tái),添加應(yīng)用,獲取AK代碼,PHP代碼編輯器,如EditPlus等
下面詳細(xì)介紹下開(kāi)發(fā)步驟:
第一步:準(zhǔn)備工作
登錄微信公眾平臺(tái),檢查服務(wù)器配置是否已啟用,URL(服務(wù)器地址) 是否已配置Token(令牌),與自己寫(xiě)的微信入口文件中的Token(令牌一致),如下圖:然后點(diǎn)擊提交,只至網(wǎng)頁(yè)上提示綠色背景的提交成功信息,則完成本步驟的操作

第二步:微信天氣預(yù)報(bào)數(shù)據(jù)源準(zhǔn)備
用已注冊(cè)好的百度帳號(hào),登錄百度LBS云平臺(tái),添加一個(gè)應(yīng)用,獲取訪問(wèn)應(yīng)用AK,及了解車(chē)聯(lián)API V3.0,天氣查詢功能相應(yīng)的接口說(shuō)明文件,以按需調(diào)用需要的天氣信息.

第三步:微信公眾平臺(tái),接口文件編寫(xiě) jiekou.php
<?php
/*
無(wú)憂電腦技巧網(wǎng) 微信公眾號(hào)功能源碼
CopyRight 2015 All Rights Reserved
*/
define("TOKEN", "weixin2015");
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
}else{
$wechatObj->valid();
}
class wechatCallbackapiTest
{
//驗(yàn)證簽名
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ú)憂電腦技巧網(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)容前兩個(gè)字符,如"黃岡天氣" 最終取值"黃岡"
include("weather.php"); //調(diào)用天氣接口文件
$content = getWeatherInfo($city); //執(zhí)行天氣接口文件中的 getWeatherInfo方法.查詢 黃岡天氣.
} else{
$content = date("Y-m-d H:i:s",time())."\n技術(shù)支持 無(wú)憂電腦技巧網(wǎng)\nwww.51pcjq.com"; //發(fā)送其它內(nèi)容默認(rèn)回復(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)
{
}
}

第四步:使用百度車(chē)聯(lián)API V3.0接口,及訪問(wèn)應(yīng)用AK碼,編號(hào)微信天氣接口源碼:
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=自已申請(qǐng)的百度車(chē)聯(lián)API AK代碼";//構(gòu)建通過(guò)百度車(chē)聯(lián)API V3.0查詢天氣url鏈接
$ch = curl_init();//初始化會(huì)話 curl_setopt($ch, CURLOPT_URL, $url);//設(shè)置會(huì)話參數(shù) curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//設(shè)置會(huì)話參數(shù) $output = curl_exec($ch);//執(zhí)行curl會(huì)話
curl_close($ch);//關(guān)閉curl會(huì)話
$result = json_decode($output, true);//函數(shù)json_decode() 的功能時(shí)將json數(shù)據(jù)格式轉(zhuǎn)換為數(shù)組。
if ($result["error"] != 0){
return $result["status"]; }
$curHour = (int)date('H',time());
$weather = $result["results"][0];//按照微信公眾號(hào)開(kāi)發(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;}?>

注意事項(xiàng)
微信公眾平臺(tái) TOKEN 與自己編寫(xiě)的微信接口文件中的 TOKEN 的值必須保持一致
編寫(xiě)php代碼,需使用專(zhuān)業(yè)的php編輯工具,如EditPlus,Dreamweaver等
上述天氣接口文件中,百度車(chē)聯(lián)api AK代碼已換成 "自已申請(qǐng)的百度車(chē)聯(lián)API AK代碼:請(qǐng)申請(qǐng)好后,自行填入
如要不明白的地方,可以關(guān)注我的百度空間.留言和我聯(lián)系!
微信天氣預(yù)報(bào)開(kāi)發(fā)最新代碼:
<meta http-equiv="Content-Type" content="text/html; charset=utf" />
<?php
header("Content-Type:text/html;charset=UTF-");
date_default_timezone_set("PRC");
/**
* 最開(kāi)始用的是微信提供的demo老是不成功,用了這個(gè)網(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;
}
}
//測(cè)試文字回復(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 = "我是頂尖機(jī)器人";
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 = "聽(tīng)不懂您在講什么";
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),在這里您將得到海量免費(fèi)學(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ù)報(bào) 此處漢字需要處理,想了很多辦法才沒(méi)亂碼
private function weather($k){
$n=urlencode($k);
$showapi_appid = ‘‘; //去相關(guān)網(wǎng)站申請(qǐ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)文章
Laravel自定義 封裝便捷返回Json數(shù)據(jù)格式的引用方法
今天小編就為大家分享一篇Laravel自定義 封裝便捷返回Json數(shù)據(jù)格式的引用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-09-09
laravel框架實(shí)現(xiàn)為 Blade 模板引擎添加新文件擴(kuò)展名操作示例
這篇文章主要介紹了laravel框架實(shí)現(xiàn)為 Blade 模板引擎添加新文件擴(kuò)展名操作,結(jié)合實(shí)例形式詳細(xì)分析了laravel框架Blade 模板引擎添加新文件擴(kuò)展名具體操作步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2020-01-01
使用PHP?MySQL實(shí)現(xiàn)數(shù)據(jù)量小的內(nèi)容推薦方法
這篇文章主要為大家介紹了使用PHP?MySQL實(shí)現(xiàn)數(shù)據(jù)量小的內(nèi)容推薦方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
ioncube_loader_win_5.2.dll的錯(cuò)誤解決方法
這篇文章主要介紹了ioncube_loader_win_5.2.dll的錯(cuò)誤解決方法的相關(guān)資料,需要的朋友可以參考下2015-01-01

