用tp5写的接口
我用的是这个:https://market.aliyun.com/products/57002002/cmapi00035184.html?spm=5176.10695662.1996646101.searchclickresult.549c173dYGx2YO#sku=yuncode2918400001
public function chat()
{
//tp获取请求的ip
$ip = $_SERVER['REMOTE_ADDR'];
//传入ip调用getAddress方法
$address = $this->getAddress($ip);
//将换算出来的地址返回给前端
return json($address);
}
//根据ip换算地址
public function getAddress($ip)
{
$host = "https://ips.market.alicloudapi.com";
$path = "/iplocaltion";
$method = "GET";
$appcode = "8d906c63c537482fb9e8f7e00f3c211a";//填写appcode
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "ip=" . $ip;
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
//curl_setopt($curl, CURLOPT_HEADER, true); 如不输出json, 请打开这行代码,打印调试头部状态码。
//状态码: 200 正常;400 URL无效;401 appCode错误; 403 次数用完; 500 API网管错误
if (1 == strpos("$" . $host, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
$out_put = curl_exec($curl);
$out_put = json_decode($out_put, true);
//判断返回的code是否是100
if ($out_put['code'] == '100') {
//返回的code是100就表示换算成功
$out_put = $out_put['result'];
//将换算出来的地址return出去
return $out_put = $out_put['nation'] . $out_put['province'] . $out_put['city'] . $out_put['district'];
} else {
//如果code不等于100说明没有换算成功
return $out_put = '暂无定位';
}
}