当前位置:Gxlcms > PHP教程 > php实现微信开发之百度天气预报

php实现微信开发之百度天气预报

时间:2021-07-01 10:21:17 帮助过:47人阅读

这篇文章主要为大家详细介绍了php微信开发之百度天气预报的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

1.登录百度ak申请:http://lbsyun.baidu.com/apiconsole/key


2.实现天气信息功能

baiduWeather.php

  1. <?php
  2. /**
  3. * 使用百度天气预报接口获取城市天气信息案例实现
  4. */
  5. //获取城市天气信息
  6. function getWeatherInfo($cityName){
  7. if($cityName == "" || (strstr($cityName,"+"))){
  8. return "发送城市加天气,例如北京天气";
  9. }
  10. //获取到的ak
  11. $ak = your ak;
  12. //获取到的sk
  13. $sk = your sk;
  14. //调用接口
  15. $url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sk=%s';
  16. $uri = '/telematics/v3/weather';
  17. $location = $cityName;
  18. $output = 'json';
  19. $querystring_arrays = array(
  20. 'ak' => $ak,
  21. 'location' => $location,
  22. 'output' => $output
  23. );
  24. $querystring = http_build_query($querystring_arrays);
  25. //生成sn
  26. $sn = md5(urlencode($uri.'?'.$querystring.$sk));
  27. $targetUrl = sprintf($url,$ak,urlencode($location),$output,$sn);
  28. $ch = curl_init();
  29. curl_setopt($ch,CURLOPT_URL,$targetUrl);
  30. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  31. $result = curl_exec($ch);
  32. curl_close($ch);
  33. $result = json_decode($result,true);
  34. if($result["error"]!=0){
  35. return $result["status"];
  36. }
  37. $curHour = (int)date('H',time());
  38. $weather = $result["results"][0];
  39. $weatherArray[]=array("Title"=>$weather['currentCity']."天气预报","Description"=>"","PicUrl"=>"","Url"=>"");
  40. for($i = 0;$i<count($weather["weather_data"]);$i++){
  41. $weatherArray[] = array("Title"=>
  42. $weather["weather_data"][$i]["data"]."\n".
  43. $weather["weather_data"][$i]["weather"].
  44. $weather["weather_data"][$i]["wind"].
  45. $weather["weather_data"][$i]["temperature"],
  46. "Description"=>"",
  47. "PicUrl"=>(($curHour>=6)&&($curHour<
  48. 18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"],"URL"=>""
  49. );
  50. }
  51. return $weatherArray;
  52. }

3.实现天气消息事件

  1. <?php
  2. /*
  3. CopyRight 2016 All Rights Reserved
  4. */
  5. define("TOKEN", "weixin");
  6. /**
  7. * 百度天气预报案例实现
  8. * 实现思路:
  9. * 1.申请百度ak、sk
  10. * 2.使用百度天气预报接口
  11. * 3.实现天气信息功能
  12. * 4.实现事件响应功能
  13. */
  14. $wechatObj = new wechatCallbackapiTest();
  15. if (!isset($_GET['echostr'])) {
  16. $wechatObj->responseMsg();
  17. }else{
  18. $wechatObj->valid();
  19. }
  20. class wechatCallbackapiTest
  21. {
  22. //验证签名
  23. public function valid()
  24. {
  25. $echoStr = $_GET["echostr"];
  26. if($this->checkSignature()){
  27. header('content-type:text');
  28. echo $echoStr;
  29. exit;
  30. }
  31. }
  32. public function checkSignature(){
  33. $signature = $_GET["signature"];
  34. $timestamp = $_GET["timestamp"];
  35. $nonce = $_GET["nonce"];
  36. $token = TOKEN;
  37. $tmpArr = array($token, $timestamp, $nonce);
  38. sort($tmpArr);
  39. $tmpStr = implode($tmpArr);
  40. $tmpStr = sha1($tmpStr);
  41. if($tmpStr == $signature) {
  42. return true;
  43. }else{
  44. return false;
  45. }
  46. }
  47. //响应消息
  48. public function responseMsg()
  49. {
  50. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  51. if (!empty($postStr)){
  52. $this->logger("R ".$postStr);
  53. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  54. $RX_TYPE = trim($postObj->MsgType);
  55. //消息类型分离
  56. switch ($RX_TYPE)
  57. {
  58. case "event":
  59. $result = $this->receiveEvent($postObj);
  60. break;
  61. case "text":
  62. $result = $this->receiveText($postObj);
  63. break;
  64. default:
  65. $result = "unknown msg type: ".$RX_TYPE;
  66. break;
  67. }
  68. echo $result;
  69. }else {
  70. echo "";
  71. exit;
  72. }
  73. }
  74. //接收事件消息
  75. public function receiveEvent($object)
  76. {
  77. $content = "";
  78. switch ($object->Event)
  79. {
  80. case "subscribe":
  81. $content = "欢迎关注Nicky的公众号 ";
  82. $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
  83. break;
  84. case "unsubscribe":
  85. $content = "取消关注";
  86. break;
  87. }
  88. $result = $this->transmitText($object, $content);
  89. return $result;
  90. }
  91. //接收文本消息
  92. public function receiveText($object)
  93. {
  94. $keyword = trim($object->Content);
  95. //自动回复模式
  96. if (strstr($keyword, "天气")){
  97. $city = str_replace('天气','',$keyword);
  98. include("baiduweather.php");
  99. $content = getWeatherInfo($city);
  100. }
  101. $result = $this->transmitNews($object, $content);
  102. return $result;
  103. }
  104. //回复图文消息
  105. public function transmitNews($object, $newsArray)
  106. {
  107. if(!is_array($newsArray)){
  108. return;
  109. }
  110. $itemTpl = " <item>
  111. <Title><![CDATA[%s]]></Title>
  112. <Description><![CDATA[%s]]></Description>
  113. <PicUrl><![CDATA[%s]]></PicUrl>
  114. <Url><![CDATA[%s]]></Url>
  115. </item>
  116. ";
  117. $item_str = "";
  118. foreach ($newsArray as $item){
  119. $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
  120. }
  121. $xmlTpl = "<xml>
  122. <ToUserName><![CDATA[%s]]></ToUserName>
  123. <FromUserName><![CDATA[%s]]></FromUserName>
  124. <CreateTime>%s</CreateTime>
  125. <MsgType><![CDATA[news]]></MsgType>
  126. <ArticleCount>%s</ArticleCount>
  127. <Articles>
  128. $item_str</Articles>
  129. </xml>";
  130. $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
  131. return $result;
  132. }
  133. //日志记录
  134. public function logger($log_content)
  135. {
  136. if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
  137. sae_set_display_errors(false);
  138. sae_debug($log_content);
  139. sae_set_display_errors(true);
  140. }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
  141. $max_size = 10000;
  142. $log_filename = "log.xml";
  143. if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
  144. file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
  145. }
  146. }
  147. }
  148. ?>

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

PHP实现图片的等比缩放和Logo水印功能的方法

PHP实现调用Mailgun发送邮件的方法

PHP+jQuery实现滚屏无刷新动态加载数据功能的方法

以上就是php实现微信开发之百度天气预报的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行