Home  >  Article  >  Backend Development  >  WeChat public platform weather query, train ticket query, express query, little yellow chicken, translation, bus query implementation

WeChat public platform weather query, train ticket query, express query, little yellow chicken, translation, bus query implementation

WBOY
WBOYOriginal
2016-07-25 08:50:351282browse
You can try it by scanning the QR code at the source.
  1. /**
  2. * wechat php test
  3. */
  4. include("ABClient.php"); //Apply and download the sdk from Aibang.com
  5. define("FNAPK", "API key"); //This Baidu application duapp.com creates an API key obtained by the application
  6. define("WAPK","key"); //This key address is http://lbsyun.baidu.com/apiconsole/key?application=key Get
  7. //define your token
  8. define("TOKEN", "Write your own token here");
  9. $wechatObj = new wechatCallbackapiTest();
  10. $wechatObj->responseMsg();
  11. class wechatCallbackapiTest
  12. {
  13. private $model;
  14. private $name;
  15. public function __construct(){
  16. $this->model = new ABClient();
  17. $a = $this->model->test_transfer();
  18. $this- >name = include("name.php");
  19. }
  20. public function valid()
  21. {
  22. $echoStr = $_GET["echostr"];
  23. //valid signature , option
  24. if($this-> ;checkSignature()){
  25. echo $echoStr;
  26. exit;
  27. }
  28. }
  29. public function responseMsg()
  30. {
  31. //get post data, May be due to the different environments
  32. $postStr = $GLOBALS[" HTTP_RAW_POST_DATA"];
  33. //extract post data
  34. if (!empty($postStr)){
  35. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  36. $fromUsername = $postObj->FromUserName;
  37. $toUsername = $postObj->ToUserName;
  38. $type = $postObj->MsgType;
  39. $event = $postObj->Event;
  40. $c = $postObj->Location_X;
  41. $d = $postObj ->Location_Y;
  42. $keyword = trim($postObj->Content);
  43. $time = time();
  44. $msgid = $postObj->MsgId;
  45. $textTpl = "
  46. < ToUserName>
  47. %s
  48. ";
  49. if($type == "event" && $event == "subscribe")
  50. {
  51. $msgType = "text";
  52. $contentStr.= "Welcome Follow Weidu Network. This public platform has the following functions: nn";
  53. $contentStr.= "1. Directly input Chinese characters or Chinese characters for Chinese and English translation, such as "Hello"n";
  54. $contentStr.= "2 .Enter "weather + region" for weather query, such as "Weather + Shijiazhuang"n";
  55. $contentStr.= "3. Enter "city + starting point + destination" for public transportation query, such as "Shijiazhuang + Railway Station + Gongjiazhuang "n";
  56. $contentStr.= "4. Enter "@anycontent" to chat with the little bitch, such as "@little bitch"n";
  57. $contentStr.= "5. Send your geographical location to WeChat for weather information Query, you can try n";
  58. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  59. echo $resultStr;
  60. }else if($type == "text"){
  61. $keywords = explode("+",$keyword);
  62. $b = explode("@",$keyword);
  63. if(isset($b[1])){
  64. $contentStr = $this->simsim($b[1]);
  65. $msgType = "text";
  66. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  67. echo $ resultStr;
  68. exit();
  69. }
  70. if($keywords[0]=="train"){
  71. $city = $keywords[1];
  72. $end = $keywords[2];
  73. $time = $keywords[3];
  74. $result = $ this->doget($city,$end,$time);
  75. if(!empty($result)){
  76. $result = strip_tags($result['datas']);
  77. $return_str = str_replace("  ;","",$result);
  78. $return_str = str_replace("\n","",$return_str);
  79. $a = explode(",",$return_str);
  80. $name =array();
  81. $c = array_chunk($a,16);
  82. array_pop($c);
  83. foreach($c as $k =>$v){
  84. $str="remaining tickets: n business seat:".$v [5].", Special class seat: ".$v[6].", First class seat: ".$v[7].", Second class seat: ".$v[8].", Premium soft sleeper: ".$v[9].", soft sleeper: ".$v[10].", hard sleeper: ".$v[11].", soft seat: ".$v[12].", hard seat:" .$v[13].", No seat: ".$v[14].", Others: ".$v[15];
  85. $str = preg_replace("/Hard seat:--,/","" ,$str);
  86. $str = preg_replace("/Business Seat:--,/","",$str);
  87. $str = preg_replace("/Premium Class Seat:--,/","",$ str);
  88. $str = preg_replace("/First class seat:--,/","",$str);
  89. $str = preg_replace("/Second class seat:--,/","",$ str);
  90. $str = preg_replace("/Advanced Soft Sleeper:--,/","",$str);
  91. $str = preg_replace("/Soft Sleeper:--,/","",$str);
  92. $str = preg_replace("/Hard sleeper:--,/","",$str);
  93. $str = preg_replace("/Soft seat:--,/","",$str);
  94. $str = preg_replace("/Hard seat:--,/","",$str);
  95. $str = preg_replace("/Others:--/","",$str);
  96. $contentStr.="Train number: {$v[1]}, departure station: {$v[2]}, arrival station: {$v[3]}, duration: {$v[4]}. n{$str}nn";
  97. if($k == 12){
  98. break;
  99. }
  100. }
  101. }else{
  102. $contentStr.="Sorry not found";
  103. }
  104. $msgType = "text ";
  105. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  106. echo $resultStr;
  107. exit();
  108. }
  109. if(isset($keywords[1]) &&!isset($keywords[2])){
  110. if($this->pexpress(trim($keywords[0]))){
  111. $a = $this->express(trim($keywords[0 ]),trim($keywords[1]));
  112. if($a["message"]=="ok"){
  113. if($a['ischeck']==1){
  114. $contentStr.= "Your package has not been signed for nn";
  115. }else{
  116. $contentStr.="Your package has not been signed for nn";
  117. }
  118. $data = $a['data'];
  119. foreach($data as $k =>$v){
  120. $contentStr.="Update time: {$v["time"]}nLogistics status: {$v["context"]}nn";
  121. }
  122. }else{
  123. $contentStr = "Query failed, please enter correct query";
  124. }
  125. $msgType = "text";
  126. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  127. echo $ resultStr;
  128. }else{
  129. $weather = $this->weather($keywords[1]);
  130. if(!empty($weather))
  131. {
  132. $data = $this->json2array($weather) ;
  133. foreach($data as $k =>$v)
  134. {
  135. $str.=$v['date'].'. Weather: '.$v['weather'].'. Wind speed: '.$v['wind'].'. Temperature: '.$v['temperature']."nn";
  136. }
  137. }else{
  138. $str="Please enter the correct address, such as weather + Beijing";
  139. }
  140. $msgType = " text";
  141. $contentStr = $str;
  142. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  143. echo $resultStr;
  144. }
  145. }else if(isset( $keywords[2])&&($keywords[0]!=="train")){
  146. $city = $keywords[0];
  147. $start = $keywords[1];
  148. $end =$keywords[2 ];
  149. $a = $this->model->test_transfer($city,$start,$end);
  150. if(!empty($a)){
  151. foreach($a as $k=>$ v){
  152. $contentStr.= "Route{$c}:".$v['dist']." meters. Estimated time: {$v['time']} minutes. nBus route: {$ v['segments']["segment"][0]["line_name"]}. n boarding location: {$v['segments']["segment"][0]["start_stat"]}. Drop off location: {$v['segments']["segment"][0]["end_stat"]}.n经过路线:{$v['segments']["segment"][0]["stats"]}nn";
  153. if($k == 4){
  154. break;
  155. }
  156. }
  157. }else{
  158. $contentStr="抱歉没有查询到";
  159. }
  160. $msgType = "text";
  161. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  162. echo $resultStr;
  163. }else{
  164. $fanyi = $this->fanyi($keyword);
  165. $msgType = "text";
  166. $contentStr = $fanyi;
  167. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  168. echo $resultStr;
  169. }
  170. }else if($type == 'location'){
  171. $result = $this->address($c,$d);
  172. if(isset($result['district'])){
  173. $weather = $this->weather($result['district']);
  174. if(!$weather){
  175. $weather = $this->weather($result['city']);
  176. }
  177. }else{
  178. $weather = $this->weather($result['city']);
  179. }
  180. $data = $this->json2array($weather);
  181. foreach($data as $k =>$v){
  182. $str.=$v['date'].'。天气:'.$v['weather'].'。风速:'.$v['wind'].'。温度:'.$v['temperature']."nn";
  183. }
  184. $msgType = "text";
  185. $contentStr = $str;
  186. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  187. echo $resultStr;
  188. }else{
  189. echo "您可以输入点什么";
  190. }
  191. }else {
  192. echo "";
  193. exit;
  194. }
  195. }
  196. //获取地理位置的
  197. private function address($addx,$addy)
  198. {
  199. $arr = array();
  200. $result = $this->map_text("http://api.map.baidu.com/geocoder/v2/?ak=".WAPK."&callback=renderReverse&location={$addx},{$addy}&output=xml&pois=0");
  201. $data = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
  202. $result = $this->json2array($data);
  203. $arr = $result["result"]["addressComponent"];
  204. $address = $result['result']['formatted_address'];
  205. array_push($arr,$address);
  206. return $arr;
  207. }
  208. //解析json为数组
  209. private function json2array($json) {
  210. if ($json) {
  211. foreach ((array)$json as $k=>$v) {
  212. $data[$k] = !is_string($v) ? $this->json2array($v) : $v;
  213. }
  214. return $data;
  215. }
  216. }
  217. //获取天气信息
  218. private function weather($data)
  219. {
  220. //根据API调用输出数据
  221. $url="http://api.map.baidu.com/telematics/v2/weather?location={$data}&output=json&ak=".WAPK;
  222. $weather=$this->map_text($url);
  223. $data = json_decode($weather);
  224. return $data->results;
  225. }
  226. //调用翻译的api
  227. private function fanyi($data)
  228. {
  229. //根据API调用输出数据
  230. $url="http://openapi.baidu.com/public/2.0/bmt/translate?client_id=".FANAPK."&q={$data}&from=auto&to=auto";
  231. $fanyi=$this->map_text($url);
  232. $shuju=json_decode($fanyi);
  233. $result=$shuju->trans_result;
  234. return $result[0]->dst;
  235. }
  236. //解析地址的api
  237. private function map_text($url)
  238. {
  239. if(!function_exists('file_get_contents')) {
  240. $file_contents = file_get_contents($url);
  241. } else {
  242. $ch = curl_init();
  243. $timeout = 5;
  244. curl_setopt ($ch, CURLOPT_URL, $url);
  245. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  246. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  247. $file_contents = curl_exec($ch);
  248. curl_close($ch);
  249. }
  250. return $file_contents;
  251. }
  252. private function checkSignature()
  253. {
  254. $signature = $_GET["signature"];
  255. $timestamp = $_GET["timestamp"];
  256. $nonce = $_GET["nonce"];
  257. $token = TOKEN;
  258. $tmpArr = array($token, $timestamp, $nonce);
  259. sort($tmpArr);
  260. $tmpStr = implode( $tmpArr );
  261. $tmpStr = sha1( $tmpStr );
  262. if( $tmpStr == $signature ){
  263. return true;
  264. }else{
  265. return false;
  266. }
  267. }
  268. private function simsim($keywords){
  269. $curlPost=array("txt"=>$keywords);
  270. $ch = curl_init();//初始化curl
  271. curl_setopt($ch,CURLOPT_URL,'http://xiaohuangji.com/ajax.aspx');//抓取指定网页
  272. curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
  273. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
  274. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  275. curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  276. $data = curl_exec($ch);//运行curl
  277. curl_close($ch);
  278. return $data;
  279. }
  280. private function pexpress($exname){
  281. $a = $this->map_text("http://www.kuaidi100.com/");
  282. preg_match_all("/data-code="(?Pw+)">(?P.*)</span>/iU",$a,$b);</li> <li> $name = array();</li> <li> foreach($b['title'] as $k=>$v){</li> <li> $name[$v] = $b['name'][$k];</li> <li> }</li> <li> if(!empty($name[$exname])){</li> <li> return true;</li> <li> }else{</li> <li> return false;</li> <li> }</li> <li> }</li> <li> private function express($keywords,$number){</li> <li> $a = $this->map_text("http://www.kuaidi100.com/");</li> <li> preg_match_all("/data-code="(?P<name>w+)"><span>(?P<title>.*)</span>/iU",$a,$b);</li> <li> $name = array();</li> <li> foreach($b['title'] as $k=>$v){</li> <li> $name[$v] = $b['name'][$k];</li> <li> }</li> <li> $this->name = $name;</li> <li> $keywords = $name[$keywords];</li> <li> $url = "http://www.kuaidi100.com/query?type={$keywords}&postid={$number}";</li> <li> $result = $this->map_text($url);</li> <li> $result = $this->json2array(json_decode($result));</li> <li> return $result;</li> <li> }</li> <li> </li> <li> private function doget ($start,$end,$time) // get获取数据使用</li> <li> {</li> <li> if(empty($time)){</li> <li> $time = date('Y-m-d',time());</li> <li> }else{</li> <li> if(substr($time,0,1)!=0){</li> <li> $time = date('Y-0',time()).$time;</li> <li> }else{</li> <li> $time = date('Y-',time()).$time;</li> <li> }</li> <li> }</li> <li> $star = $this->name[$start];</li> <li> $end = $this->name[$end];</li> <li> $url = "http://dynamic.12306.cn/otsquery/query/queryRemanentTicketAction.do?method=queryLeftTicket&orderRequest.train_date={$time}&orderRequest.from_station_telecode={$star}&orderRequest.to_station_telecode={$end}&orderRequest.train_no=&trainPassType=QB&trainClass=QB%23D%23Z%23T%23K%23QT%23&includeStudent=00&seatTypeAndNum=&orderRequest.start_time_str=00%3A00--24%3A00";</li> <li> $optionget = array('http' => array('method' => "GET", 'header' => "User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.0.04506; CIBA)rnAccept:*/*rnReferer:http://dynamic.12306.cn/otsquery/query/queryRemanentTicketAction.do?method=init")); </li> <li> $file = file_get_contents($url, false , stream_context_create($optionget));</li> <li> return $this->json2array(json_decode($file));</li> <li> }</li> <li> </li> <li>}</li> <li> <li>?></li> </ol></div> <em onclick="copycode($('code_j53'));">复制代码</em> </div> </td></tr></table> <div id="comment_50307" class="cm"> </div> <div id="post_rate_div_50307"></div> <br><br></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="Android Push - Aurora Push" href="https://m.php.cn/faq/314741.html">Android Push - Aurora Push</a></span><span>Next article:<a class="dBlack" title="Android Push - Aurora Push" href="https://m.php.cn/faq/314747.html">Android Push - Aurora Push</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>