From 5f669d156bfabfdf049bcfbd0cbb2ff64471d946 Mon Sep 17 00:00:00 2001 From: gzydong <837215079@qq.com> Date: Sun, 12 Sep 2021 16:26:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=99=BB=E5=BD=95=E9=80=9A?= =?UTF-8?q?=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Cache/IpAddressCache.php | 29 +++++++++++++++++++++++ app/Support/IpAddress.php | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 app/Cache/IpAddressCache.php create mode 100644 app/Support/IpAddress.php diff --git a/app/Cache/IpAddressCache.php b/app/Cache/IpAddressCache.php new file mode 100644 index 0000000..8e11cd0 --- /dev/null +++ b/app/Cache/IpAddressCache.php @@ -0,0 +1,29 @@ +get($ip); + + if (!empty($result)) { + return JsonHelper::decode($result); + } + + $result = di()->get(IpAddress::class)->read($ip); + if (!empty($result)) { + $this->add($ip, JsonHelper::encode($result)); + } + + return $result; + } +} diff --git a/app/Support/IpAddress.php b/app/Support/IpAddress.php new file mode 100644 index 0000000..7ad97c0 --- /dev/null +++ b/app/Support/IpAddress.php @@ -0,0 +1,46 @@ +request($ip); + } + + private function request(string $ip) + { + $api = config('juhe_api.ip'); + + $client = di()->get(ClientFactory::class)->create([]); + $params = [ + 'ip' => $ip, + 'key' => $api['key'], + ]; + + $response = $client->get($api['api'] . '?' . http_build_query($params)); + if ($response->getStatusCode() == 200) { + $result = json_decode($response->getBody()->getContents(), true); + + if ($result['resultcode'] != '200') { + return []; + } + + $result = $result['result']; + + return [ + 'country' => $result['Country'] ?? '', + 'province' => $result['Province'] ?? '', + 'city' => $result['City'] ?? '', + 'isp' => $result['Isp'] ?? '', + 'ip' => $ip, + ]; + } + + return []; + } +}