IpLocation.php 2.1 KB

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