laravel项目整合ipstack到torann/geoip扩展

torann/geoip支持自定义service,通过以下两个步骤整合ipstack服务。

1、新增类\App\GeoIP\Services\IPStack,继承自Torann\GeoIP\Services\AbstractService,实现boot和locate方法。

2、添加配置到services(文件/config/geoip.php),如:
'ipstack' => [
'class' => \App\GeoIP\Services\IPStack::class,
'secure' => false,
'access_key' => env('IPSTACK_KEY'),
'language' => 'en',
]

并修改默认的service为ipstack

附:\App\GeoIP\Services\IPStack.php源码

namespace App\GeoIP\Services;

use Exception;
use Torann\GeoIP\Support\HttpClient;
use Torann\GeoIP\Services\AbstractService;

class IPStack 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' => ($this->config('secure') ? 'https' : 'http') . '://api.ipstack.com/',
'query' => [
'access_key' => $this->config('access_key'),
'output' => 'json',
'language' => $this->config('language', 'en'),
],
]);
}

/**
* {@inheritdoc}
*/
public function locate($ip)
{
// Get data from client
$data = $this->client->get($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]);

if (isset($json->error)) {
throw new Exception('ERROR '. $json->error->code. ': (' . $json->error->info . ')');
}

return $this->hydrate([
'ip' => $ip,
'iso_code' => $json->country_code,
'country' => $json->country_name,
'city' => $json->city,
'state' => $json->region_code,
'state_name' => $json->region_name,
'postal_code' => $json->zip,
'lat' => $json->latitude,
'lon' => $json->longitude,
'timezone' => isset($json->time_zone) ? $json->time_zone->id : 'NA',
'continent' => $json->continent_name,
'currency' => isset($json->currency) ? $json->currency->code : ''
]);
}
}

点赞