微信查询天气公众账号小记

步骤1.

申请微信公众号,个人申请订阅号。(笔者早早就申请过了)

步骤2.

去这里创建应用 http://developer.baidu.com

步骤3.

根据bae的创建的服务,发布你的应该引擎。当然,你的svn需要自己维护,我使用的php服务。其实只要在你的svn中增加微信要求的接口即可。wx_sample.php 即可

《微信查询天气公众账号小记》

步骤4.

配置微信的回调地址

《微信查询天气公众账号小记》

步骤5.

对 wx_sample.php进行修改,可参考 http://jingyan.baidu.com/article/af9f5a2d21ea3243150a4542.html

注意:这里需要先认证一次,在注释掉 $wechatObj->valid(),然后 调用 $wechatObj->responseMsg();

如下代码片段:

$wechatObj = new wechatCallbackapiTest();

//$wechatObj->valid();  //微信修改配置后提交认证的时候使用这个,认证成功后必须禁用
$wechatObj->responseMsg();

class wechatCallbackapiTest{
.....

步骤6.

实现天气查询接口

    public function getWeatherByCity($cityName)
    {
        $weatherApiFmt = "http://www.weather.com.cn/data/cityinfo/%s.html";
        $cityName2Code = array("北京"=>"101010100", 
                               "上海"=>"101020100",
                               "广州"=>"101280101", 
                               "深圳"=>"101280601",
                               "西安"=>"101110101",
                               "乌鲁木齐"=>"101130101");
        if (! array_key_exists($cityName, $cityName2Code))
        {
            return "目前只支持北上广深,西安和乌鲁木齐";
        }
        $weatherApi = sprintf($weatherApiFmt, $cityName2Code[$cityName]);
        $ret = file_get_contents($weatherApi);
        $aryRet = json_decode($ret);
        $retStr = "天气:".$aryRet->weatherinfo->weather;
        $retStr .= " 气温:".$aryRet->weatherinfo->temp1." ~ ".$aryRet->weatherinfo->temp2;
        return $retStr;
    }

再responseMsg方法中做修改:

     if(!empty( $keyword ))
    {
        $msgType = "text";
        $contentStr = $this->getWeatherByCity($keyword);
        $retStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $retStr;
    }

步骤7.

效果如下:

《微信查询天气公众账号小记》

    原文作者:移动开发
    原文地址: https://my.oschina.net/sanpeterguo/blog/366338
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞