PHP 调用请求外网接口

1.类中定义静态方法
class FtpService{
/**
* 请求外网
* @param $url 外网接口url
* @param bool $params 参数,拼接字符串 post请求可以为数组
* @param int $ispost 是否是post请求
* @return array|bool
*/
public static function reqUrl($url, $params = false, $ispost = 0)
{
$httpInfo = array();
$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Data');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}

$response = curl_exec($ch);
//echo $response; //打印查看数据
if ($response === FALSE) {
return false;
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
$response = json_decode($response,true);

$result = [];
$result['httpCode'] = $httpCode;
$result['info'] = $response;
return $result;
}
}
2.调用eg: (例子为post请求,参数为数组或者拼接字符串)
//post调用 参数为数组
public function ApiTestPost()
{
$url = config('http_host')['interface']; //配置外网接口
$data = [
'code'=>0,
'sign'=>'1223435', //校验签名,自己设置签名规则 外网校验
'ordser_sn'=>'1234567'
];
//$data = 'code=0&sign=12345&order_sn=1234567'; //也可以是这种格式
$res = FtpService::reqUrl($url, $data,1);
return $res['info']['data'];
}

//get调用 参数为拼接字符串
public function ApiTest()
{
$url = config('http_host')['interface']; //配置外网接口
$order_sn = "987654321";
$sign = '1234566';
$params = "&appoint_sn=".$appoint_sn.'&sign='.$sign;
$res = FtpService::reqUrl($url, $params);
return $res['info']['data'];
}

3.外网接口部分获取参数:
post请求中:$data = input(''); //得到的就是上面$data数据 校验签名后写逻辑部分就ok了
 get请求中: $order_sn = input('order_sn');


posted @ 2020-11-24 16:49  北往星辰  阅读(822)  评论(0编辑  收藏  举报