diff --git a/config/geoip.php b/config/geoip.php index 8ebb9d7..83f6c01 100644 --- a/config/geoip.php +++ b/config/geoip.php @@ -84,6 +84,11 @@ 'locales' => ['en'], ], + 'ip2location' => [ + 'class' => \Torann\GeoIP\Services\IP2Location::class, + 'key' => env('IP2LOCATION_API_KEY'), + ], + ], /* diff --git a/src/Services/IP2Location.php b/src/Services/IP2Location.php new file mode 100644 index 0000000..bc1ffd8 --- /dev/null +++ b/src/Services/IP2Location.php @@ -0,0 +1,76 @@ +client = new HttpClient([ + 'base_uri' => 'http://api.ip2location.io/', + 'query' => [ + 'key' => $this->config('key'), + ], + ]); + } + + /** + * {@inheritdoc} + * @throws Exception + */ + public function locate($ip): array|Location + { + // Get data from client + $data = $this->client->get('find', [ + 'ip' => $ip, + ]); + + // Verify server response + if ($this->client->getErrors() !== null) { + throw new Exception('Request failed (' . $this->client->getErrors() . ')'); + } + + // Parse body content + $json = json_decode($data[0]); + + return $this->hydrate([ + 'ip' => $ip, + 'iso_code' => $json->country_code, + 'country' => $json->country_name, + 'city' => $json->city_name, + 'state' => null, + 'state_name' => $json->region_name, + 'postal_code' => $json->zip_code, + 'lat' => $json->latitude, + 'lon' => $json->longitude, + 'timezone' => $json->time_zone, + 'continent' => null, + ]); + } + + /** + * Update function for service. + * + * @return string + */ + public function update() + { + // Optional artisan command line update method + } +}