IpLocation.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Servers\Aliyun;
  3. use Ixudra\Curl\Facades\Curl;
  4. /**
  5. * ip归属地
  6. * @author 唐远望
  7. * @version 1.0
  8. * @date 2025-12-22
  9. */
  10. class IpLocation
  11. {
  12. /**
  13. * 获取IP归属地
  14. * @param string $ip IP地址
  15. * @param string $field 获取字段,可以选字段
  16. *
  17. * @return string|array
  18. *
  19. * */
  20. public function getCityByIp($ip = '', $field = '')
  21. {
  22. // 获取IP
  23. $ip = $ip ? $ip : request()->ip();
  24. // 从缓存读取数据
  25. $result = cache('aliyunMarketGetCityByIp:' . ip2long($ip), []);
  26. // 如果有数据
  27. if ($result) return $field ? (isset($result[$field]) ? $result[$field] : '') : $result;
  28. // 读取AppCode
  29. $appcode = config('aliyun_appcode', '3e494a5f38c44e0c97424fd122e348c3');
  30. // 提示未配置
  31. if (empty($appcode)) ['error' => '请联系管理员设置接口 appcode'];
  32. // 拼接路径
  33. $path = 'https://bf1c.api.huachen.cn/ip'; //'https://hcapi20.market.alicloudapi.com/ip';
  34. // 头部信息
  35. $headers = ['Authorization:APPCODE ' . $appcode];
  36. // 拼接参数
  37. $url = $path . '?ip=' . $ip;
  38. // 接收返回值json格式并转数组
  39. $result = Curl::to($url)->withHeaders($headers)->asJsonResponse(true)->get();
  40. // 如果错误
  41. if (empty($result['data'])) return $field ? '' : [];
  42. if (empty($result['ret'])) return $field ? '' : [];
  43. // 如果错误$result['ret'].='=>'.$result['msg']
  44. if ($result['ret'] != 200) return $field ? '' : [];
  45. // 存储到缓存,有效期6小时
  46. cache(['aliyunMarketGetCityByIp:' . ip2long($ip) => $result['data']], 3600 * 6);
  47. // 如果存在返回国家/地区
  48. if ($field) return isset($result['data'][$field]) ? $result['data'][$field] : '';
  49. // 否则返回整个数组数据
  50. return $result['data'];
  51. }
  52. }