微信公眾平臺(tái)百度天氣預(yù)報(bào)開(kāi)發(fā)

1.登錄百度ak申請(qǐng):

http://lbsyun.baidu.com/apiconsole/key

2.實(shí)現(xiàn)天氣信息功能

baiduWeather.php


/**

*? 使用百度天氣預(yù)報(bào)接口獲取城市天氣信息案例實(shí)現(xiàn)

*/

//獲取城市天氣信息

function getWeatherInfo($cityName){

if($cityName == "" || (strstr($cityName,"+"))){

return "發(fā)送城市加天氣,例如北京天氣";

}

//獲取到的ak

$ak = your ak;

//獲取到的sk

$sk = your sk;

//調(diào)用接口

$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']."天氣預(yù)報(bào)","Description"=>"","PicUrl"=>"","Url"=>"");

for($i = 0;$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.實(shí)現(xiàn)天氣消息事件


/*

CopyRight 2016 All Rights Reserved

*/

define("TOKEN", "weixin");

/**

* 百度天氣預(yù)報(bào)案例實(shí)現(xiàn)

* 實(shí)現(xiàn)思路:

* 1.申請(qǐng)百度ak、sk

* 2.使用百度天氣預(yù)報(bào)接口

* 3.實(shí)現(xiàn)天氣信息功能

* 4.實(shí)現(xiàn)事件響應(yīng)功能

*/

$wechatObj = new wechatCallbackapiTest();

if (!isset($_GET['echostr'])) {

$wechatObj->responseMsg();

}else{

$wechatObj->valid();

}

class wechatCallbackapiTest

{

//驗(yàn)證簽名

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;

}

}

//響應(yīng)消息

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 = "歡迎關(guān)注Nicky的公眾號(hào) ";

$content .= (!empty($object->EventKey))?("\n來(lái)自二維碼場(chǎng)景 ".str_replace("qrscene_","",$object->EventKey)):"";

break;

case "unsubscribe":

$content = "取消關(guān)注";

break;

}

$result = $this->transmitText($object, $content);

return $result;

}

//接收文本消息

public function receiveText($object)

{

$keyword = trim($object->Content);

//自動(dòng)回復(fù)模式

if (strstr($keyword, "天氣")){

$city = str_replace('天氣','',$keyword);

include("baiduweather.php");

$content = getWeatherInfo($city);

}

$result = $this->transmitNews($object, $content);

return $result;

}

//回復(fù)圖文消息

public function transmitNews($object, $newsArray)

{

if(!is_array($newsArray)){

return;

}

$itemTpl = "? ?

<![CDATA[%s]]>

";

$item_str = "";

foreach ($newsArray as $item){

$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

}

$xmlTpl = "

%s

%s

$item_str

";

$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);

}

}

}

?>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,544評(píng)論 19 139
  • 我一直是這樣,每次開(kāi)始寫(xiě)東西,似乎標(biāo)題才是最難的,所以就將它略過(guò)。 現(xiàn)在,漸漸說(shuō)的話少了,一天聊的話,滑動(dòng)一次屏,...
    呦呦鹿鳴666閱讀 287評(píng)論 0 0
  • 昨夜的文字,收到好多網(wǎng)友的私信,非常感謝你們的關(guān)注。你們的鼓勵(lì) 支持 拍磚,都是我堅(jiān)持寫(xiě)下去的理由,有時(shí),真不知胡...
    蘭子說(shuō)閱讀 402評(píng)論 7 5
  • 美國(guó)的兩位作家寫(xiě)了一本關(guān)于“端粒(DNA頂端)”的書(shū)。其中提到鍛煉可以降壓(力)。延長(zhǎng)端粒長(zhǎng)度(也就是增加生命長(zhǎng)度...
    水平生閱讀 928評(píng)論 0 0

友情鏈接更多精彩內(nèi)容