| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?php
- namespace App\Servers\Aliyun;
- use Ixudra\Curl\Facades\Curl;
- /**
- * ip归属地
- * @author 唐远望
- * @version 1.0
- * @date 2025-12-22
- */
- class IpLocation
- {
- /**
- * 获取IP归属地
- * @param string $ip IP地址
- * @param string $field 获取字段,可以选字段
- *
- * @return string|array
- *
- * */
- public function getCityByIp($ip = '', $field = '')
- {
- // 获取IP
- $ip = $ip ? $ip : request()->ip();
- // 从缓存读取数据
- $result = cache('aliyunMarketGetCityByIp:' . ip2long($ip), []);
- // 如果有数据
- if ($result) return $field ? (isset($result[$field]) ? $result[$field] : '') : $result;
- // 读取AppCode
- $appcode = config('aliyun_appcode', '3e494a5f38c44e0c97424fd122e348c3');
- // 提示未配置
- if (empty($appcode)) ['error' => '请联系管理员设置接口 appcode'];
- // 拼接路径
- $path = 'https://bf1c.api.huachen.cn/ip'; //'https://hcapi20.market.alicloudapi.com/ip';
- // 头部信息
- $headers = ['Authorization:APPCODE ' . $appcode];
- // 拼接参数
- $url = $path . '?ip=' . $ip;
- // 接收返回值json格式并转数组
- $result = Curl::to($url)->withHeaders($headers)->asJsonResponse(true)->get();
- // 如果错误
- if (empty($result['data'])) return $field ? '' : [];
- if (empty($result['ret'])) return $field ? '' : [];
- // 如果错误$result['ret'].='=>'.$result['msg']
- if ($result['ret'] != 200) return $field ? '' : [];
- // 存储到缓存,有效期6小时
- cache(['aliyunMarketGetCityByIp:' . ip2long($ip) => $result['data']], 3600 * 6);
- // 如果存在返回国家/地区
- if ($field) return isset($result['data'][$field]) ? $result['data'][$field] : '';
- // 否则返回整个数组数据
- return $result['data'];
- }
- }
|