WeChat public platform development-weather forecast function, public platform weather forecast-PHP Tutorial

Source: Internet
Author: User
Weather forecast function developed on the public platform, and weather forecast on the public platform. The weather forecast function developed on the public platform. the weather forecast function of the public platform has recently been added to the public account for project requirements. the weather forecast function is developed using the IoV APIV3. the weather forecast function of the public platform

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:

Project requirements: there is a connected platform and a registered Baidu account. you need to open the cloud platform on Baidu LBS, add applications, get AK code, PHP code editor, such as EditPlus.

The following describes the development procedure in detail:

Step 1: Prepare

Log on to the public platform and check whether the server configuration is enabled and whether the Token (Token) has been configured for the URL (server address) is consistent with the Token (Token) in the self-written entry file, for example: click "submit". only the successful submission of the green background is displayed on the webpage. This step is complete.


Step 2: Prepare the weather forecast data source

Use a registered Baidu account, log on to the Baidu LBS cloud platform, add an application, obtain the accesskey of the application, and learn about the API V3.0 of iov cc. the interface description file corresponding to the weather query function is provided, call the required weather information as needed.

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

<? Php/* carefree Computer Skills Network public code function Source Code CopyRight 2015 All Rights Reserved */define ("TOKEN", "weixin2015"); $ wechatObj = new wechatCallbackapiTest (); if (! Isset ($ _ GET ['echostr']) {$ wechatObj-> responseMsg ();} else {$ wechatObj-> valid ();} class wechatCallbackapiTest {// verify the 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 ($ tmpSt R ==$ 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 ){}}

Step 4: Use the V3.0 API of Baidu automobile network and access the AK code of the application. the source code of the weather interface is:

Weatger. php

<? Phpfunction getWeatherInfo ($ cityName) {if ($ cityName = "" | (strstr ($ cityName, "+") {return "send weather + city, for example, 'weather Shenzhen '";} // The user queries the weather and replies to the keyword rule $ url =" http://api.map.baidu.com/telematics/v3/weather?location= ". Urlencode ($ cityName ). "& output = json & ak = self-applied Baidu iov api ak code"; // Construct a url to query the weather using Baidu IOV 3. 0. $ ch = curl_init (); // initialize the session curl_setopt ($ ch, CURLOPT_URL, $ url); // Set the session parameter curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); // Set the session parameter $ output = curl_exec ($ ch); // execute the curl session curl_close ($ ch); // Close the curl session $ result = json_decode ($ output, true); // converts the json data format to an array when the json_decode () function is used. If ($ result ["error"]! = 0) {return $ result ["status"] ;}$ curHour = (int) date ('H', time ()); $ weather = $ result ["results"] [0]; // develop the document according to the public account, group construction multi-text reply information $ weatherArray [] = array ("Title" => $ 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:

 
 <? Php header ("Content-Type: text/html; charset = UTF-"); date_default_timezone_set ("PRC "); /*** at the beginning, the provided demo was always unsuccessful. it was successful only after being downloaded from the internet * // define your token define ("TOKEN ", "djjc"); $ wechatObj = new wechatCallbackapiTest (); // access operation. after successful access, you can directly annotate $ 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 ;}// 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 -',' 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 ;}}?>

Vivo has recently added the weather forecast function to public accounts in a project demand. it uses the IoV API V3 ....

Related Article

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.