在我们开发微信公众号等微信应用的时候,我们都是希望功能越多越好,那么我们今天就来讲一下,php实现微信天气查询,其实并不是太复杂,只需要调用一下百度天气接口就可以了,废话不多说了,我们一起来看看吧!
我们要达到的效果如下图所示,当你在微信中输入某地天气如“深圳天气”字样是会出现以下页面:
ps:这里声明一下,我使用的后台服务器是新浪sae服务器,这里不做过多介绍
第一页代码这一页代码主要是用于token的验证、以及通过后台服务器对微信用户请求发出响应。这一页代码比较简单,不做介绍。
<?php
header("content-type:text;charset=utf8;")
define("token", "weixin");
$wechatobj = new wechatcallbackapitest();
if (!isset($_get['echostr'])) {
$wechatobj->responsemsg();
}else{
$wechatobj->valid();
}
class wechatcallbackapitest
{
public function valid()
{
$echostr = $_get["echostr"];
if($this->checksignature()){
echo $echostr;
exit;
}
}
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 = sha1($tmpstr);
if($tmpstr == $signature){
return true;
}else{
return false;
}
}
public function responsemsg()
{
$poststr = $globals["http_raw_post_data"];
if (!empty($poststr)){
$this->logger("r ".$poststr);
$postobj = simplexml_load_string($poststr, 'simplexmlelement', libxml_nocdata);
$rx_type = trim($postobj->msgtype);
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)
{
$content = "";
switch ($object->event)
{
case "subscribe":
$content = "欢迎关注,查询天气,发送天气加城市名,如“深圳天气”";
break;
case "unsubscribe":
$content = "取消关注";
break;
}
$result = $this->transmittext($object, $content);
return $result;
}
//str_replace(str1,str2,str3)用str3包含str1,用str2取代str1.
private function receivetext($object)
{
$keyword = trim($object->content);
if (strstr($keyword, "天气")){
$city = str_replace('天气', '', $keyword);//这里用空格取代$keyword中的天气二字。
include("weather2.php");
$content = getweatherinfo($city);
//判断笑话
}
$result = $this->transmitnews($object, $content);
return $result;
}
private function transmittext($object, $content)
{
$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, $arr_item)
{
if(!is_array($arr_item))
return;
$itemtpl = " <item>
<title><![cdata[%s]]></title>
<description><![cdata[%s]]></description>
<picurl><![cdata[%s]]></picurl>
<url><![cdata[%s]]></url>
</item>
";
$item_str = "";
foreach ($arr_item 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($arr_item));
return $result;
}
private function transmitmusic($object, $musicarray)
{
$itemtpl = "<music>
<title><![cdata[%s]]></title>
<description><![cdata[%s]]></description>
<musicurl><![cdata[%s]]></musicurl>
<hqmusicurl><![cdata[%s]]></hqmusicurl>
</music>";
$item_str = sprintf($itemtpl, $musicarray['title'], $musicarray['description'], $musicarray['musicurl'], $musicarray['hqmusicurl']);
$texttpl = "<xml>
<tousername><![cdata[%s]]></tousername>
<fromusername><![cdata[%s]]></fromusername>
<createtime>%s</createtime>
<msgtype><![cdata[music]]></msgtype>
$item_str
</xml>";
$result = sprintf($texttpl, $object->fromusername, $object->tousername, time());
return $result;
}
//这里主要用于在服务器端生成日志
private function logger($log_content)
{
if(isset($_server['http_bae_env_appid'])){ //bae
require_once "baelog.class.php";
$logger = baelog::getinstance();
$logger ->logdebug($log_content);
}else if(isset($_server['http_appname'])){ //sae
sae_set_display_errors(false);
sae_debug($log_content);
sae_set_display_errors(true);
}else if($_server['remote_addr'] != "127.0.0.1"){ //local
$max_size = 10000;
$log_filename = "log.xml";
if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
file_put_contents($log_filename, date('h:i:s')." ".$log_content."\r\n", file_append);
}
}
}
?>
第二页代码这一页代码主要关于调用百度天气接口的过程以及他们的数据传输方式。
1、我们要调用百度的天气接口,需要在百度地图开放平台进行注册,然后创建一个应用获取该应用ak和sk。
获取ak(即access key)后,点击设置,页面如下:
在请求校验方式哪里选择sn校验方式,会自动出现下方的sk码(即 security key)。
sk的具体作用和sn计算算法可参照下面这篇文章http://lbsyun.baidu.com/index.php?title=lbscloud/api/appendix
<?php
// var_dump(getweatherinfo("桃江"));
getweatherinfo("深圳");
function getweatherinfo($cityname)
{
if ($cityname == "" || (strstr($cityname, "+"))){
return "发送天气加城市,例如'天气深圳'";
}
$ak = 'plev804cmhumwpxvcehccb14ths0zuat';//从百度地图开发平台获取的ak
$sk = 'iv3vspcd2jnilmlcrcgywgskp9paxidc';//从百度地图开发平台获取的sk
//向百度地图开发平台请其数据的url如http://api.map.baidu.com/geocoder/v2/?address=百度大厦&output=json&ak=yourak**&sn=7de5a22212ffaa9e326444c75a58f9a0。包含4个参数,address(查询地址),output(请求数据的恢复格式)、ak(验证密钥)、sn是经过加密后的数据。
$url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sn=%s';
$uri = '/telematics/v3/weather';
$location = $cityname;
$output = 'json';
$querystring_arrays = array(
'ak' => $ak,
'location' => $location,
'output' => $output
);
$querystring = http_build_query($querystring_arrays);//使用关联数组生成一个urlencode请求字符串。格式如下:ak=plev804cmhumwpxvcehccb14ths0zuat&location=深圳&output=json;
// var_dump($querystring);
//urlencode() url中的一些特殊字符和中文字符可能不被服务器所识别,需要经过urlencode()编码才能被识别。
$sn = md5(urlencode($uri.'?'.$querystring.$sk));//md5()对url中的数据进行加密。
$targeturl = sprintf($url, $ak, urlencode($location), $output, $sn);
// var_dump($targeturl);
//curl用于与接口服务器建立会话获取 接口传递过来的数据。
$ch = curl_init();
curl_setopt($ch, curlopt_url, $targeturl);//与接口简历会话
curl_setopt($ch, curlopt_returntransfer, 1);//获取的数据存储在一个变量上,而不是直接输出。如果为o或false则直接输出。
$result = curl_exec($ch);//执行会话,获取数据。
echo $result;//字符串格式加数个json格式的数据类型
curl_close($ch);
$result = json_decode($result, true);//参数带true返回一个数组
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>";
var_dump($result);
if ($result["error"] != 0){
return $result["status"];
}
$curhour = (int)date('h',time());
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>";
echo $curhour;
$weather = $result["results"][0];
$weatherarray[] = array("title" =>$weather['currentcity']."天气预报", "description" =>"", "picurl" =>"", "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;
}
?>
以上就是本篇文章的所有内容,大家好好看看吧,对于刚开始接触微信开发的同学来讲本篇文章可能有点难度哦!
相关推荐:
php微信开发之获取城市天气
以上就是php实现微信实时天气查询的详细内容。