微信应用开发【PHP】---笔记9---基于微信公众平台实现天气预报查询【调用聚合数据的天气预报接口】

    技术2023-05-16  103

    基于微信公众平台实现天气预报查询

    一、基于微信公众平台实现天气预报查询1.截图2.准备工作3.代码1》实现思路2》代码(1)【index.php】主要代码(2)【weather.php】

    一、基于微信公众平台实现天气预报查询

    1.截图

    2.准备工作

    1》取得天气预报接口【聚合数据的天气预报接口】 地址:https://www.juhe.cn/docs/api/id/73 在这里,创建账号、实名认证、申请key值 在页面下方有数据解释 2》创建weather接口文件和在index.php文件写关键代码呗

    3.代码

    1》实现思路

    1.在https://www.juhe.cn/docs/api/id/73获取天气预报接口 “http://apis.juhe.cn/simpleWeather/query?city=” . $city ."&key=" . $key, 并获取key 【需要注册实名认证才可以获取,免费但每日有限制使用次数】 2.获取用户的关键词,拼接url和解析url 3.通过json数据返回给用户关键信息

    2》代码

    (1)【index.php】主要代码

    前面省略

    //1.接收文本消息 private function receiveText($object) { $keyword = $object->Content; if ($keyword == "3") { $contentStr = "❤"; $resultStr = $this->transmitText($object, $contentStr); return $resultStr; }elseif (substr($keyword, 0, 6) == "天气") { require_once "weather.php"; $Entity = trim(substr($keyword, 6, strlen($keyword))); $key="你的账户,个人中心->我的数据,接口名称上方查看复制粘贴"; $contentStr = getWeatger($Entity,$key); } else { $contentStr = "失败"; } $resultStr = $this->transmitNews($object, $contentStr); return $resultStr; }

    (2)【weather.php】

    <?php require_once "FUN.php"; function getWeatger($city, $key) { if (!empty($city) || !empty($key)) { $url = "http://apis.juhe.cn/simpleWeather/query?city=" . $city . "&key=" . $key; $output = https_request($url); $data = json_decode($output, true); $results = $data['result']; if ($data[' error_code'] == 0||count($results) != 0) { //$weaArray=$results['city'] . "天气预报:温度为" . $results['realtime']['temperature'] . "天气" . // $results['realtime']['info'] . "风向" . $results['realtime']['direct'] . $results['realtime']['power']; $weaArray = array(); $weaArray[] = array( "Title" => $results['city'] . "天气预报:温度为" . $results['realtime']['temperature'] . "摄氏度,天气" . $results['realtime']['info'] . ",风向" . $results['realtime']['direct'] . $results['realtime']['power'], "Description" => "", "Pic" => "", "Url" => ""); // return "获取天气成功!"; return $weaArray; }else { return "获取天气失败!"; } } }
    2020-07-03
    Processed: 0.009, SQL: 9