A _php example of weather forecast function development of micro-credit public platform

Source: Internet
Author: User
Tags cdata curl sprintf trim urlencode

Recently, there is a project demand for the micro-letter public number to increase the function of the weather forecast, using the vehicle networking API Baidu V3.0 in the weather query function to achieve. First of all, the final effect chart:

Project requirements: There is a good link between the micro-letter platform, Baidu registered account number, the need to open the cloud in Baidu lbs platform, add applications, get AK Code, PHP code editor, such as EditPlus, etc.

The following development steps are described in detail below:

The first step: Prepare for work

Login Micro-trust public platform, check that the server configuration is enabled and that the URL (server address) is configured with token (token), in accordance with the token (token) in its own micro-mail entry file, as shown below: Then click Submit, only to the Web page to prompt for a green background submission success information, Then complete the operation of this step


Step two: Micro-credit weather forecast data source Preparation

With registered Baidu account number, login Baidu lbs cloud Platform, add an application, get access to the application of AK, and understand the vehicle associated API V3.0, weather query function corresponding interface documentation to call the required weather information.

Step three: Micro-trust public platform, interface file writing jiekou.php

<?php * Worry-free computer skills Network Micro-letter public number 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 signature Public Function valid () {$echoStr = $_get["echo
 Str "];
 $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
 The 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 = "Welcome attention to worry-free computer technology
  Clever net ";
 Break
 $result = $this->transmittext ($object, $content);
 return $result; Private Function Receivetext ($object) {$keyword = Trim ($object->content);//Get user input/Judge weather if!empty ($keywor d) {//!empty function to determine whether the value obtained by the $keyword is empty $city = Mb_substr ($keyword, 0, 2, ' utf-8 ');///Take the first two characters of user input, such as "Huanggang Weather" final value "Huanggang" includ E ("weather.php"); Call Weather interface File $content = Getweatherinfo ($city);
 Executes the Getweatherinfo method in the Weather interface file. Check Huanggang weather. else{$content = Date ("Y-m-d h:i:s", Time ()). " \ n Technical support worry-free computer skills network \nwww.51pcjq.com ";
 Send the contents of the default reply for 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 = "<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 '], $it
 em[' 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) {}}

Fourth step: The use of Baidu Vehicle API V3.0 interface, and access to the application AK code, numbered micro-letter weather Interface Source code:

weatger.php

<?php function Getweatherinfo ($cityName) {if ($cityName = = "" | | (Strstr ($cityName, "+")) {return "Send weather + city, such as ' Weather Shenzhen '";} The user inquires the weather, the reply keyword rule $url = "http://api.map.baidu.com/telematics/v3/weather?location=". UrlEncode ($cityName). &output=json&ak= since the application of Baidu car link API AK Code "//Build through Baidu Car Link API V3.0 query weather URL links $ch = Curl_init ()//initialization session curl_setopt ($CH, 
Curlopt_url, $url)//Set session parameter curl_setopt ($ch, Curlopt_returntransfer, 1);/set session parameter $output = curl_exec ($ch);//Execute Curl Session
 Curl_close ($ch);//Close curl Session $result = Json_decode ($output, true);//function Json_decode () converts the JSON data format to an array. 
 if ($result ["error"]!= 0) {return $result [' status] ';} 
 $curHour = (int) date (' H ', Time ()); $weather = $result ["Results"][0];//the development of documents in accordance with the micro-letter public number, the formation of multiple text response information $weatherArray [] = Array ("Title" => $weather [' CurrentCity ']. " Current weather: "." Temperature: ". $weather [' weather_data '][0][' temperature '].", ". $weather [' weather_data '][0][' weather '].", "." Wind: ". $weather [' weather_data '][0][' winds '].". "," 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 <)) $weather ["Weather_data"] [$i] ["Daypictureurl"]: $weather ["Weather_data"] [$i] ["Nightpictureurl"], 
 "Url" => ""); return $weatherArray;}? >

Attention matters

The TOKEN public platform has to be consistent with the value of TOKEN in its own micro-communication interface file

Write PHP code, you need to use professional PHP editing tools, such as editplus,dreamweaver, etc.

The above weather interface file, Baidu Vehicle API AK Code has been replaced by the "Self application of the Baidu Vehicle API AK Code: Please apply, fill in

If you do not understand the place, you can pay attention to my Baidu space. Leave a message and contact me!

Micro-Credit weather forecast development latest code:

 <meta http-equiv= "Content-type" content= "text/html;
 Charset=utf "/> <?php header (" content-type:text/html;charset=utf-");
 Date_default_timezone_set ("PRC");
 /** * Started with the micro-letter provided by the demo is always unsuccessful, using this online download only successful * * *//define your token define ("token", "DJJC");
 $WECHATOBJ = new Wechatcallbackapitest ();
 Micro-letter Access operation, the successful access to the direct annotation on the line $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 is due to the different $POSTSTR = $GLOBALS
 
 ["Http_raw_post_data"]; Extract post Data if (!empty ($POSTSTR)) {$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', LIBXML_NOCDA
 TA);
 
 $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 reply 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 "Hello": $contentStr = "Hello!";
 Break
 Case "What's Your Name": $contentStr = "I am a top robot";
Break
 Judge whether the weather 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 = ' [Tomorrow Day] '. $data->f->day_weather. "
 \ n "; $data = ' [Tomorrow night] '. $data->f->night_weather. "
 \ 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 ...";
 The Public Function handleevent ($object) {$contentStr = ""; Switch ($object->event) {case "subscribe": $CONTENTSTR = "Thank you for your attention to the top tutorial network, where you will receive a huge amount of free learning resources!"
 ";
 Break
 Default: $contentStr = "Unknow Event:". $object->event;
 Break
 $RESULTSTR = $this->responsetext ($object, $CONTENTSTR);
 return $resultStr; The 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;
 }//Weather forecast Here The Chinese characters need to be processed, think a lot of ways to be no garbled private function weather ($k) {$n =urlencode ($k); $showapi _appid = ';
 Go to the relevant website to apply on the line $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; }}?>

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.