메뉴 건너뛰기

infra

[PHP] Curl HTTPRequest Class 로 google api token 받기

lispro062014.11.17 23:06조회 수 1578댓글 0

    • 글자 크기

pecl로 HTTPREQUEST 모듈인 http.so를 이용해야 하는데, 오류 때문에 되지 않는다.(in php 5.6)


그래서 HTTPREQUEST CLASS를 수정해 token을 받는데 성공했다.


<?php

class HttpRequest {

    private $method, $url, $data = false;

    private $error, $hasError = false, $response, $status;

    private $requestInfo, $curlError, $headers = array();

    // Default arguments

    private $args = array(

        "followRedirect" => true,

    );

    function __construct($method, $url, $data = false, $args = false) {

        $method = strtolower($method);

        if ($method == "post" || $method == "get") {

            $this->method = $method;

        } else {

            $this->setError("Invalid method: $method");

            return;

        }

        $this->url  = $url;

        $this->data = $data;

        if (is_array($args)) {

            // Add arguments to the already available default arguments

            foreach($args as $key => $value) {

                $this->args[$key] = $value;

            }

        }

        $this->doRequest();

    }

    function hasError() {

        return $this->hasError;

    }

    private function setError($msg) {

        $this->error = $msg;

        $this->hasError = true;

    }

    function getError() {

        return $this->error;

    }

    function getStatus() {

        return $this->status;

    }

    function getResponse() {

        return $this->response;

    }

    function getRequestInfo() {

        return $this->requestInfo;

    }

    function toString() {

        var_dump($this);

    }

    private function doRequest() {

        $this->doCurl();

        if ($this->status != "200") {

            $this->setError("Response error: " . $this->status . " (" . $this->curlError . ")");

        }

    }

    private function doCurl() {

        $c = curl_init();

        // Maybe we want to rewrite the url for data arguments in GET requests

        if ($this->method == "get" && $this->data) {

            $this->url .= "?" . http_build_query($this->data);

        }

        // Default values

        curl_setopt($c, CURLOPT_URL, $this->url);

        //curl_setopt($c, CURLOPT_RETURNTRANSFER ,true);

        //curl_setopt($c, CURLOPT_FOLLOWLOCATION, $this->args['followRedirect']);

        //curl_setopt($c, CURLOPT_HTTPHEADER, array('Expect:'));

//register a callback function which will process the headers

//this assumes your code is into a class method, and uses $this->readHeader as the callback //function

//curl_setopt($c, CURLOPT_HEADERFUNCTION, array(&$this,'readHeader'));

        // Authentication

        if (isset($this->args['username']) && isset($this->args['password'])) {

            curl_setopt($c, CURLOPT_USERPWD, $this->args['username'] . ':' . $this->args['password']);

        }

        // POST

        if($this->method == "post") {

            curl_setopt($c, CURLOPT_POST, true);

            // Always escape HTTP data dammit!

            curl_setopt($c, CURLOPT_POSTFIELDS, $this->args);

        }

        $this->response    = curl_exec($c);

        $this->status      = curl_getinfo($c, CURLINFO_HTTP_CODE);

        $this->curlError   = curl_errno($c) . ": ". curl_error($c);

        $this->requestInfo = curl_getinfo($c);

$this->headers     = array_merge($this->requestInfo, $this->headers);

        curl_close($c);

    }

private function readHeader($ch, $header) {

        $key = trim(substr($header, 0, strpos($header, ":")));

        $val = trim(substr($header, strpos($header, ":") + 1));

        if (!empty($key) && !empty($val)) {

            $this->headers[$key] = $val;

        }

        return strlen($header);

}

function getHeaders($key = false) {

        if ($key) {

            return $this->headers[$key];

        } else {

    return $this->headers;

        }

}

}

 

if(isset($_GET['code'])) {

    // try to get an access token

    $code = $_GET['code'];

    $url = 'https://accounts.google.com/o/oauth2/token';

    $params = array(

        "code" => $code,

        "client_id" => "c_id",

        "client_secret" => "secret",

        "redirect_uri" => "http://url/oauth2callback.php",

        "grant_type" => "authorization_code"

    );

    $request = new HttpRequest('post',$url,false,$params);

    $request->doRequest();

    $responseObj = json_decode($request->getResponseBody());

    echo "Access token: " . $responseObj->access_token;

}

?>


curl_setopt($c, CURLOPT_HTTPHEADER, array('Expect:'));

등에서 옵션이 달라지고, $data, $arg 파라미터가 이상하여, 좀 수정하고, 주석처리했다.

lispro06 (비회원)
    • 글자 크기
[GData] python 으로 spreadsheet 에 업데이트 (by suritam9) [PDA] PDA가 웹서비스를 한다. (by 박영식)

댓글 달기

첨부 (0)
위로