微信公众平台开发之天气预报功能

时间:2022-10-21 18:47:38

最近有项目需求给微信公众号上增加了天气预报功能,使用百度提供的车联网api v3.0中的天气查询功能实现.先上一张最终效果图:

微信公众平台开发之天气预报功能

项目需求:有连接好的微信平台,有百度注册帐号,需要在百度lbs开放云平台,添加应用,获取ak代码,php代码编辑器,如editplus等

下面详细介绍下开发步骤:

第一步:准备工作

      登录微信公众平台,检查服务器配置是否已启用,url(服务器地址) 是否已配置token(令牌),与自己写的微信入口文件中的token(令牌一致),如下图:然后点击提交,只至网页上提示绿色背景的提交成功信息,则完成本步骤的操作

微信公众平台开发之天气预报功能

第二步:微信天气预报数据源准备

      用已注册好的百度帐号,登录百度lbs云平台,添加一个应用,获取访问应用ak,及了解车联api v3.0,天气查询功能相应的接口说明文件,以按需调用需要的天气信息.

微信公众平台开发之天气预报功能

第三步:微信公众平台,接口文件编写 jiekou.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
/*
 无忧电脑技巧网 微信公众号功能源码
 copyright 2015 all rights reserved
*/
define("token", "weixin2015");
$wechatobj = new wechatcallbackapitest();
if (!isset($_get['echostr'])) {
 $wechatobj->responsemsg();
}else{
 $wechatobj->valid();
}
class wechatcallbackapitest
{
 //验证签名
 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->receivetext($postobj);
   break;
  }
  $this->logger("t ".$result);
  echo $result;
 }else {
  echo "";
  exit;
 }
 }
 private function receiveevent($object)
 {
 switch ($object->event)
 {
  case "subscribe":
  $content = "欢迎关注无忧电脑技巧网 ";
  break;
 }
 $result = $this->transmittext($object, $content);
 return $result;
 }
 private function receivetext($object)
 {
 $keyword = trim($object->content); //获得用户输入的信息
 //判断天气
 if(!empty( $keyword )){ //!empty 函数,判断 $keyword获得的值是否为空
 $city = mb_substr($keyword, 0, 2, 'utf-8'); //取用户输入内容前两个字符,如"黄冈天气" 最终取值"黄冈"
 include("weather.php"); //调用天气接口文件
 $content = getweatherinfo($city); //执行天气接口文件中的 getweatherinfo方法.查询 黄冈天气.
 } else{
 $content = date("y-m-d h:i:s",time())."\n技术支持 无忧电脑技巧网\nwww.51pcjq.com"; //发送其它内容默认回复的内容.
 }
 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'], $item['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)
 {
 }
}

微信公众平台开发之天气预报功能

第四步:使用百度车联api v3.0接口,及访问应用ak码,编号微信天气接口源码:

weatger.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
function getweatherinfo($cityname){
if ($cityname == "" || (strstr($cityname, "+"))){
return "发送天气+城市,例如'天气深圳'"; }//用户查询天气,回复关键词 规则
$url = "http://api.map.baidu.com/telematics/v3/weather?location=".urlencode($cityname)."&output=json&ak=自已申请的百度车联api ak代码";//构建通过百度车联api v3.0查询天气url链接
$ch = curl_init();//初始化会话 curl_setopt($ch, curlopt_url, $url);//设置会话参数 curl_setopt($ch, curlopt_returntransfer, 1);//设置会话参数 $output = curl_exec($ch);//执行curl会话
curl_close($ch);//关闭curl会话
$result = json_decode($output, true);//函数json_decode() 的功能时将json数据格式转换为数组。
 if ($result["error"] != 0){
 return $result["status"]; }
 $curhour = (int)date('h',time());
 $weather = $result["results"][0];//按照微信公众号开发文档,组建设多图文回复信息
 $weatherarray[] = array("title" => $weather['currentcity']."当前天气:"."温度:".$weather['weather_data'][0]['temperature'].",".$weather['weather_data'][0]['weather'].","."风力:".$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;}?>

微信公众平台开发之天气预报功能

注意事项

微信公众平台 token 与自己编写的微信接口文件中的 token 的值必须保持一致

编写php代码,需使用专业的php编辑工具,如editplus,dreamweaver等

上述天气接口文件中,百度车联api ak代码已换成 "自已申请的百度车联api ak代码:请申请好后,自行填入

如要不明白的地方,可以关注我的百度空间.留言和我联系!

微信天气预报开发最新代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<meta http-equiv="content-type" content="text/html; charset=utf" />
 <?php
 header("content-type:text/html;charset=utf-");
 date_default_timezone_set("prc");
 /**
 * 最开始用的是微信提供的demo老是不成功,用了这个网上下载的才成功
 */
 
 //define your token
 define("token", "djjc");
 $wechatobj = new wechatcallbackapitest();
 //微信接入操作,成功接入了直接注释了就行了
 $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;
 }
 }
 //测试文字回复
 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 "你好":
 $contentstr = "你好!";
 break;
 case "你叫什么名字":
 $contentstr = "我是顶尖机器人";
 break;
//判断是否为天气
 case $keywords+"天气";
 $str = mb_substr($keyword,-,,"utf-");
 $str_key = mb_substr($keyword,,-,"utf-");
 if($str=="天气"){
 $data = $this->weather($str_key)->showapi_res_body;
 $data=‘[今天白天]‘.$data->f->day_weather."\n";
 $data=‘[今天夜间]‘.$data->f->night_weather."\n";
 $data=‘[明天白天]‘.$data->f->day_weather."\n";
 $data=‘[明天夜间]‘.$data->f->night_weather."\n";
 $contentstr = $data.$data.$data.$data;
 }
 break;
 default:
 $contentstr = "听不懂您在讲什么";
 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 = "感谢您关注顶尖教程网,在这里您将得到海量免费学习资源!";
 break;
 default :
 $contentstr = "unknow event: ".$object->event;
 break;
 }
 $resultstr = $this->responsetext($object, $contentstr);
 return $resultstr;
 }
 
 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;
 }
 }
 //天气预报 此处汉字需要处理,想了很多办法才没乱码
 private function weather($k){
 $n=urlencode($k);
 $showapi_appid = ‘‘; //去相关网站申请就行
 $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;
 }
 }
 ?>