1. 程式人生 > 其它 >PHP 呼叫外部介面

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']; //配置外網介面 $url = 'baidu.com' $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');

$url = 'baidu.com'

https://www.cnblogs.com/luqiangblogs/p/14031152.html