WeChat public platform development-weather forecast function-php instance-PHP source code

Source: Internet
Author: User
This article will develop weather queries that everyone cares about every day. for example, if a user sends a message "Huanggang weather", the user will return the real-time weather conditions of Huanggang, and the weather conditions in the next two or even five days. This article will develop weather queries that everyone cares about every day. for example, if a user sends a message "Huanggang weather", the user will return the real-time weather conditions of Huanggang, and the weather conditions in the next two or even five days.

Recently, a project needs to add the weather forecast function to the public account, and use the weather query function in IoV API V3.0 provided by Baidu to achieve the following:

Step 3: compile jiekou. php in the public platform interface file

 ResponseMsg ();} else {$ wechatObj-> valid ();} class wechatCallbackapiTest {// verify the signature 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-> deleetext ($ postObj); break;} $ this-> logger ("T ". $ result); echo $ result;} else {echo ""; exit ;}} private f Unction receiveEvent ($ object) {switch ($ object-> Event) {case "subscribe": $ content = "Welcome to www.51u.com"; break ;} $ result = $ this-> transmitText ($ object, $ content); return $ result;} private function deleetext ($ object) {$ keyword = trim ($ object-> Content); // obtain user input information // Determine the weather if (! Empty ($ keyword )){//! Empty function, judge whether the value obtained by $ keyword is null $ city = mb_substr ($ keyword, 0, 2, 'utf-8 '); // take the first two characters entered by the user. for example, the final value of "Huanggang weather" is "Huanggang" include ("weather. php "); // call the weather interface file $ content = getWeatherInfo ($ city); // execute the getWeatherInfo method in the weather interface file. query Huanggang weather .} else {$ content = date ("Y-m-d H: I: s", time ()). "\ n technical support worry-free computer skills network \ nwww.51pcjq.com"; // default reply content for sending other content .} 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 ="
 
  %s
  
  %s
  
  
   
% S
  
  text
  
  %s
  
 "; $ Result = sprintf ($ textTpl, $ object-> FromUserName, $ object-> ToUserName, time (), $ content); return $ result ;} private function transmitNews ($ object, $ newsArray) {if (! Is_array ($ newsArray) {return "" ;}$ itemTpl ="
  
  <! [CDATA [% s]> 
  %s
   
  %s
   
  %s
   
 "; $ Item_str =" "; foreach ($ newsArray as $ item) {$ item_str. = sprintf ($ itemTpl, $ item ['title'], $ item ['description'], $ item ['picurl'], $ item ['URL']);} $ newsTpl ="
 
  %s
  
  %s
  
  
   
% S
  
  news
  
  
  % S$ Item_str
 "; $ Result = sprintf ($ newsTpl, $ object-> FromUserName, $ object-> ToUserName, time (), count ($ newsArray); return $ result ;} private function logger ($ log_content ){}}

 $ Weather ['currentcity']. "Current weather :". "Temperature :". $ weather ['weather _ data'] [0] ['temperature ']. ",". $ weather ['weather _ data'] [0] ['weather ']. ",". "Wind power :". $ 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 the TOKEN in the public platform must be consistent with that in the self-compiled interface file.

To compile php code, you must use professional php editing tools, such as EditPlus and Dreamweaver.

In the preceding weather interface file, the Baidu IOV api AK code has been changed to "self-applied Baidu iov api ak code: Please fill in the code after applying.

If you do not understand anything, you can follow my Baidu Space. leave a message and contact me!

The latest code for weather forecast development:

 
  
 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 ;}// test text to reply to public function handleText ($ postObj) {$ fromUsername = $ postObj-> FromUserName; $ toUsername = $ postObj-> ToUserName; $ keyword = trim ($ postObj-> Content); $ time = time (); $ textTpl ="
  
  %s
   
  %s
   
  
   
% S
   
  %s
   
  %s
   
   
 "; If (! Empty ($ keyword) {$ msgType = "text"; switch ($ keyword) {case "Hello": $ contentStr = "Hello! "; Break; case" What is your name ": $ contentStr =" I am a top Robot "; break; // determines whether the weather is case $ keywords +" weather "; $ str = mb_substr ($ keyword,-, "UTF-"); $ str_key = mb_substr ($ keyword,-, "UTF -"); if ($ str = "weather") {$ data = $ this-> weather ($ str_key)-> showapi_res_body; $ data = '[today's day]'. $ data-> f-> day_weather. "\ n"; $ data = '[today Night]'. $ data-> f-> night_weather. "\ n"; $ data = '[daytime tomorrow]'. $ data-> f-> day_weather. "\ n"; $ data = '[tomorrow night]'. $ data-> f-> night_weat Her. "\ n"; $ contentStr = $ data. $ data. $ data. $ data;} break; default: $ contentStr = "do not understand what you are talking about"; 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 = "thank you for your attention to the top tutorial network. here you will receive a large number of free learning resources! "; Break; default: $ contentStr =" Unknow Event :". $ object-> Event; break;} $ resultStr = $ this-> responseText ($ object, $ contentStr); return $ resultStr;} public function responseText ($ object, $ content) {$ textTpl ="
  
  %s
   
  %s
   
  
   
% S
   
  text
   
  %s
   
   
 "; $ 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 ;}} // The Chinese characters in the weather forecast need to be processed. if you have thought of many methods, you can skip the garbled private function weather ($ k) {$ n = urlencode ($ k); $ showapi_appid = ''; // apply to the relevant website. $ showapi_sign = 'destcacefdea '; $ showapi_timestamp = date ('ymdhis'); $ areaid = ''; $ paramArr = ''; $ needHourData = ''; $ url = iconv ('gbk', 'utf -',' https://www.php1.cn/ '. '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 ;}}?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.