2016年7月6日 星期三

【PHP】header 中加入Authorization token驗證

今天再串某家商成的API,要使用Authorization token驗證,
這邊記錄一下步驟:
1.依照API手冊先取得連線的token
2.用curl方式將token加入header中
加入方式:
Code 部分:
// 取得token
$token = get_token();

$url = THIS_API_URL.$url;

// 將token加入header中
$API->http_header = array();
$API->http_header[] = 'Content-type: application/json';
$API->http_header[] = 'Authorization: basic '.$token;
 
$API->send_method = $send_method;

// 執行
$return = $API->curl_file_get_contents($url,$array);
$return = json_decode($return,true);
Class 部分:
 
class API
{
        // POST 資料
 public $send_method = 'post', // 傳送方式
        $http_header = array('Content-Type: text/plain')
        ;
 public function curl_file_get_contents($url,$request=array())
 {
  $useragent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36";
  $curl = curl_init(); // 啟動一個CURL會話
  curl_setopt($curl, CURLOPT_URL, $url); // 要訪問的地址
  curl_setopt($curl, CURLOPT_REFERER, $url);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 對認證證書來源的檢查
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 從證書中檢查SSL加密算法是否存在
  curl_setopt($curl, CURLOPT_USERAGENT, $useragent); // 模擬用戶使用的瀏覽器
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉
  curl_setopt($curl, CURLOPT_ENCODING, "UTF-8"); // 編碼
  curl_setopt($curl, CURLOPT_COOKIE, "cookieLangId=zh_tw;"); // 傳送cookie
  curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動設置Referer
  if ($this->send_method == 'post')
  {
   curl_setopt($curl, CURLOPT_POST, count($request)); // 發送一個常規的Post請求
   curl_setopt($curl, CURLOPT_POSTFIELDS, $request); // Post提交的數據包
  }
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); // 連線時間
  curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 設置超時限制防止死循環
  curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示返回的Header區域內容
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 獲取的信息以文件流的形式返回
  curl_setopt($curl, CURLOPT_HTTPHEADER, $this->http_header);
  $r = curl_exec($curl); // 執行操作
  if (curl_errno($curl)) {
     echo 'Errno'.curl_error($curl);//捕抓異常
  }
  curl_close($curl); // 關閉CURL會話
 
  return $r;
 }
}
php 要讀取 Authorization 要在 .htaccess 加上:
RewriteEngine on
RewriteRule .? - [E=Authorization:%{HTTP:Authorization}]
print_r($GLOBALS);

沒有留言:

張貼留言