


Weather forecast function developed on WeChat public platform, weather forecast on public platform_PHP tutorial
WeChat public platform development of weather forecast function, public platform weather forecast
Recently there is a project requirement to add a weather forecast function to the WeChat public account, using the Internet of Vehicles API provided by Baidu Implementation of the weather query function in V3.0. First, the final rendering:
Project requirements: Have a well-connected WeChat platform and a Baidu registered account. You need to add applications on the Baidu LBS open cloud platform, obtain AK code, PHP code editor, such as EditPlus, etc.
The development steps are introduced in detail below:
Step 1: Preparation
Log in to the WeChat public platform, check whether the server configuration is enabled, whether the URL (server address) has been configured with a Token (token), and is consistent with the Token (token) in the WeChat entrance file written by you, as shown below: Then click Submit, only when the green background prompts the submission success message on the web page, complete the operation of this step
Step 2: WeChat weather forecast data source preparation
Use a registered Baidu account to log in to the Baidu LBS cloud platform, add an application, get access to the application AK, and understand the interface description files corresponding to the Internet of Vehicles API V3.0 and the weather query function, so as to call the required functions on demand. Weather information.
Step 3: WeChat public platform, write interface file jiekou.php
<?php /* 无忧电脑技巧网 微信公众号功能源码 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 = "欢迎关注无忧电脑技巧网 "; break; } $result = $this->transmitText($object, $content); return $result; } private function receiveText($object) { $keyword = trim($object->Content); //获得用户输入的信息 //判断天气 if(!empty( $keyword )){ //!empty 函数,判断 $keyword获得的值是否为空 $city = mb_substr($keyword, 0, 2, 'utf-8'); //取用户输入内容前两个字符,如"黄冈天气" 最终取值"黄冈" include("weather.php"); //调用天气接口文件 $content = getWeatherInfo($city); //执行天气接口文件中的 getWeatherInfo方法.查询 黄冈天气. } else{ $content = date("Y-m-d H:i:s",time())."\n技术支持 无忧电脑技巧网\nwww.51pcjq.com"; //发送其它内容默认回复的内容. } 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) { } }
Step 4: Use Baidu AutoLink API V3.0 interface, and access the application AK code, number WeChat weather interface source code:
weatger.php
<?php function getWeatherInfo($cityName){ if ($cityName == "" || (strstr($cityName, "+"))){ return "发送天气+城市,例如'天气深圳'"; }//用户查询天气,回复关键词 规则 $url = "http://api.map.baidu.com/telematics/v3/weather?location=".urlencode($cityName)."&output=json&ak=自已申请的百度车联API AK代码";//构建通过百度车联API V3.0查询天气url链接 $ch = curl_init();//初始化会话 curl_setopt($ch, CURLOPT_URL, $url);//设置会话参数 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置会话参数 $output = curl_exec($ch);//执行curl会话 curl_close($ch);//关闭curl会话 $result = json_decode($output, true);//函数json_decode() 的功能时将json数据格式转换为数组。 if ($result["error"] != 0){ return $result["status"]; } $curHour = (int)date('H',time()); $weather = $result["results"][0];//按照微信公众号开发文档,组建设多图文回复信息 $weatherArray[] = array("Title" => $weather['currentCity']."当前天气:"."温度:".$weather['weather_data'][0]['temperature'].",".$weather['weather_data'][0]['weather'].","."风力:".$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;}?>
Notes
The value of WeChat public platform TOKEN must be consistent with the TOKEN value in the WeChat interface file written by yourself
To write PHP code, you need to use professional PHP editing tools, such as EditPlus, Dreamweaver, etc.
In the above weather interface file, the Baidu AutoLink API AK code has been replaced by "Self-applied Baidu AutoLink API AK code: Please fill in it yourself after applying
If you don’t understand something, you can follow my Baidu space. Leave a message and contact me!
The latest code developed for WeChat weather forecast:
<meta http-equiv="Content-Type" content="text/html; charset=utf" /> <?php header("Content-Type:text/html;charset=UTF-"); date_default_timezone_set("PRC"); /** * 最开始用的是微信提供的demo老是不成功,用了这个网上下载的才成功 */ //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; } } //测试文字回复 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 = "感谢您关注顶尖教程网,在这里您将得到海量免费学习资源!"; 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; } } //天气预报 此处汉字需要处理,想了很多办法才没乱码 private function weather($k){ $n=urlencode($k); $showapi_appid = ‘‘; //去相关网站申请就行 $showapi_sign = ‘deafcacefdea‘; $showapi_timestamp = date(‘YmdHis‘); $areaid=‘‘; $paramArr = ‘‘; $needHourData=‘‘; $url = iconv(‘gbk‘,‘utf-‘,‘http://route.showapi.com/-?‘.‘area=‘.$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; } } ?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Thanks to netizens Qing Qiechensi, HH_KK, Satomi Ishihara and Wu Yanzu of South China for submitting clues! According to news on September 2, there are recent rumors that "iPhone 16 may not support WeChat." In response to this, a reporter from Shell Finance called Apple's official hotline. Apple's technical consultant in China responded that whether iOS systems or Apple devices can continue to use WeChat, and WeChat The issue of whether it can continue to be listed and downloaded on the Apple App Store requires communication and discussion between Apple and Tencent to determine the future situation. Software App Store and WeChat Problem Description Software App Store technical consultant pointed out that developers may need to pay fees to put software on the Apple Store. After reaching a certain number of downloads, Apple will need to pay corresponding fees for subsequent downloads. Apple is actively communicating with Tencent,

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

Rumors of WeChat supporting iPhone 16 were debunked. Thanks to netizens Xi Chuang Jiu Shi and HH_KK for submitting clues! According to news on September 2, there are rumors today that WeChat may not support iPhone 16. Once the iPhone is upgraded to the iOS 18.2 system, it will not be able to use WeChat. According to "Daily Economic News", it was learned from people familiar with the matter that this rumor is a rumor. Apple's response: According to Shell Finance, Apple's technical consultant in China responded that the issue of whether WeChat can continue to be used on iOS systems or Apple devices, and whether WeChat can continue to be listed and downloaded in the Apple App Store, needs to be resolved between Apple and Tencent. Only through communication and discussion can we determine the future situation. Currently, Apple is actively communicating with Tencent to confirm whether Tencent will continue to

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

For investors new to the cryptocurrency world, it is crucial to understand how to buy virtual coins. This article is designed to provide a comprehensive guide to beginners covering detailed steps on how to choose the right exchange, register an account, deposit funds, and purchase Ethereum (ETH). By following this guide, beginners can safely and conveniently embark on their virtual currency investment journey and seize potential investment opportunities in 2025 and beyond.
