Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IPInfo.io service #247

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions config/geoip.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@
'locales' => ['en'],
],

'ipinfo' => [
'class' => \Torann\GeoIP\Services\IPInfo::class,
'key' => env('IPINFO_API_KEY'),
'secure' => true,
],

],

/*
Expand Down
73 changes: 73 additions & 0 deletions src/Services/IPInfo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace Torann\GeoIP\Services;

use Exception;
use Illuminate\Support\Arr;
use Torann\GeoIP\Support\HttpClient;

/**
* Class GeoIP
* @package Torann\GeoIP\Services
*/
class IPInfo extends AbstractService
{
/**
* Http client instance.
*
* @var HttpClient
*/
protected $client;

/**
* The "booting" method of the service.
*
* @return void
*/
public function boot()
{
$this->client = new HttpClient([
'base_uri' => 'https://ipinfo.io/',
'query' => [
'token' => $this->config('key'),
],
]);
}

/**
* {@inheritdoc}
* @throws Exception
*/
public function locate($ip)
{
// Get data from client
$data = $this->client->get($ip);

// Verify server response
if ($this->client->getErrors() !== null || empty($data[0])) {
throw new Exception('Request failed (' . $this->client->getErrors() . ')');
}

$json = json_decode($data[0], true);

return $this->hydrate([
'ip' => $ip,
'iso_code' => $json['country'],
'country' => $this->get_country_name($json['country']),
'city' => $json['city'],
'state' => $json['region'],
'state_name' => $json['region'],
'postal_code' => $json['postal'],
'timezone' => $json['timezone'],
'continent' => $json['continent'] ?? explode('/',$json['timezone'])[0] ?? '',
]);
}

public function get_country_name($country_code)
{
$url = 'https://restcountries.com/v3.1/alpha/' . $country_code;
$country_data = @json_decode(@file_get_contents($url));

return $country_data[0]?->name?->common ?? $country_code;
}
}