使用腾讯地图的 IP 定位服务。这里是正确的实现方式
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class CheckXinjiangIp
{
protected $key = ' '; // 你的腾讯地图 key
public function handle(Request $request, Closure $next)
{
$ip = $request->ip();
if ($ip === '127.0.0.1') {
return $next($request);
}
// 缓存24小时
$location = Cache::remember('ip_location_' . $ip, 60 * 24, function () use ($ip) {
$response = Http::get('https://apis.map.qq.com/ws/location/v1/ip', [
'key' => $this->key,
'ip' => $ip
]);
return $response->json();
});
// 检查是否是新疆地区
if (isset($location['result']['ad_info']['province'])
&& $location['result']['ad_info']['province'] === '新疆') {
return $next($request);
}
// 非新疆地区返回JSON响应
return response()->json([
'code' => 403,
'msg' => '非新疆地区访问',
'data' => [
'redirect' => true,
'path' => '/pages/banners/index'
]
]);
}
}
腾讯地图 IP 定位服务的特点:
- 需要在请求参数中带上 key
- 返回的地区信息更准确
- 支持 HTTPS
- 有每日免费配额
返回数据示例:
{
"status": 0,
"message": "Success",
"result": {
"ip": "xxx.xxx.xxx.xxx",
"location": {
"lat": 43.92172,
"lng": 87.46991
},
"ad_info": {
"nation": "中国",
"province": "新疆",
"city": "乌鲁木齐市",
"district": "渠道"
}
}
}