PHP implements Baidu weather forecast for WeChat development

墨辰丷
Release: 2023-03-28 14:28:01
Original
1696 people have browsed it

This article mainly introduces the relevant information of Baidu weather forecast developed by PHP WeChat in detail. It has certain reference value. Interested friends can refer to it

1. Log in Baidu ak application:http://lbsyun.baidu.com/apiconsole/key


2. Implement weather information function

baiduWeather.php

 $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']."天气预报","Description"=>"","PicUrl"=>"","Url"=>""); for($i = 0;$i $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; }
Copy after login

3. Implement weather message events

responseMsg(); }else{ $wechatObj->valid(); } class wechatCallbackapiTest { //验证签名 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; } } //响应消息 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 = "欢迎关注Nicky的公众号 "; $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):""; break; case "unsubscribe": $content = "取消关注"; break; } $result = $this->transmitText($object, $content); return $result; } //接收文本消息 public function receiveText($object) { $keyword = trim($object->Content); //自动回复模式 if (strstr($keyword, "天气")){ $city = str_replace('天气','',$keyword); include("baiduweather.php"); $content = getWeatherInfo($city); } $result = $this->transmitNews($object, $content); return $result; } //回复图文消息 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); } } } ?>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

How to implement proportional scaling and logo watermark functions of images in PHP

PHP implements the method of calling Mailgun to send emails

PHP jQuery implements the scrolling method of dynamically loading data without refreshing

The above is the detailed content of PHP implements Baidu weather forecast for WeChat development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!