当前位置: 代码迷 >> 综合 >> 微信公众号最佳实践 ( 7.1)天气预报
  详细解决方案

微信公众号最佳实践 ( 7.1)天气预报

热度:63   发布时间:2023-12-02 05:37:18.0

天气预报

中国天气网的api申请很困难,可以使用百度天气的api,weather2.php为百度天气接口代码

这里写图片描述

index.php

<?php
/*CopyRight 2018 All Rights Reserved */define("TOKEN", "weixin");$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {$wechatObj->responseMsg();
}else{$wechatObj->valid();
}class wechatCallbackapiTest {
    public function valid(){
    $echoStr = $_GET["echostr"];if($this->checkSignature()){echo $echoStr;exit;}}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 = 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, '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;}$this->logger("T ".$result);echo $result;}else {echo "";exit;}}private function receiveEvent($object){
    $content = "";switch ($object->Event){case "subscribe":$content = "欢迎关注 德强1012,查询天气,发送天气加城市名,如“深圳天气”";break;case "unsubscribe":$content = "取消关注";break;}$result = $this->transmitText($object, $content);return $result;}private function receiveText($object){
    $keyword = trim($object->Content);if (strstr($keyword, "天气")){$city = str_replace('天气', '', $keyword);include("weather2.php");$content = getWeatherInfo($city);//判断笑话}$result = $this->transmitNews($object, $content);return $result;}private function transmitText($object, $content){
    $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, $arr_item){
    if(!is_array($arr_item))return;$itemTpl = " <item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item>";$item_str = "";foreach ($arr_item 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($arr_item));return $result;}private function transmitMusic($object, $musicArray){
    $itemTpl = "<Music><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><MusicUrl><![CDATA[%s]]></MusicUrl><HQMusicUrl><![CDATA[%s]]></HQMusicUrl></Music>";$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[music]]></MsgType>$item_str</xml>";$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());return $result;}private function logger($log_content){
    if(isset($_SERVER['HTTP_BAE_ENV_APPID'])){   //BAErequire_once "BaeLog.class.php";$logger = BaeLog::getInstance();$logger ->logDebug($log_content);}else if(isset($_SERVER['HTTP_APPNAME'])){   //SAEsae_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);}}
}?>

weather2.php

<?php//var_dump(getWeatherInfo("桃江"));function getWeatherInfo($cityName) {
    if ($cityName == "" || (strstr($cityName, "+"))){return "发送天气加城市,例如'天气深圳'";}//1a3cde429f38434f1811a75e1a90310c$ak = '1a3cde429f38434f1811a75e1a90310c';$sk = '';$url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sn=%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 = md5(urlencode($uri.'?'.$querystring.$sk));$targetUrl = sprintf($url, $ak, urlencode($location), $output, $sn);// var_dump($targetUrl);$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']."天气预报", "Description" =>"", "PicUrl" =>"", "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;
}?>