업비트(UPBIT) API - 나의 자산 호출하기

in #kr6 years ago

업비트에서 드디어 개발 API 가 오픈했습니다.

뭐 API 가 딱히 없어도, 여태껏 시세정보는 몰래 가져오고 있었는데, 매수/매도가 가능한 API가 오픈한 것은 참으로 고마운 일입니다.

업비트 API는 JWT를 이용한 데이터전송을 사용하고 있습니다.

저도 이번 기회에 JWT 처음 알게 되었네요~

개발은 PHP를 이용해서 개발할 계획이기 때문에, 구글링으로 PHP 의 JWT 라이브러리를 검색해서 github 에서 다운받았습니다.

다운로드 주소

https://github.com/firebase/php-jwt

php JWT 사용방법

https://coderwall.com/p/8wrxfw/goodbye-php-sessions-hello-json-web-tokens

아래 소스코드는 제가 만든 업비트 내 계좌정보 가져오기 입니다.

삽질좀 했습니다.

JWT 사용방법과 CURL 의 header 에 토큰을 싫어서 전송하는 건 처음이라서 저도 조금 헤맸습니다~

function get_my_account()
{
//https://github.com/firebase/php-jwt
//https://coderwall.com/p/8wrxfw/goodbye-php-sessions-hello-json-web-tokens
include_once "_JWT.php";
$JWT = new JWT();

$payload = array();
$payload['access_key'] = UPBIT_ACCESS_KEY;
$payload['nonce'] = time() * 1000;
$token = $JWT->encode($payload, UPBIT_SECRET_KEY);

$url = "https://api.upbit.com/v1/accounts";
$string = get_curl(array(
    "url"       => $url,
    "header"    => array(
        "Authorization: Bearer {$token}"
    )
));
$data = json_decode($string, true);

return $data;

}

function get_curl($param){
//print_r($param);exit;

$ch = curl_init();

#접속할 URL 주소
curl_setopt($ch, CURLOPT_URL, $param['url']);

#FALSE 를 설정하면 cURL는 서버 인증서의 유효성을 검사하지 않습니다.#다른 인증를 CURLOPT_CAINFO 옵션 지정하거나 CURLOPT_CAPATH 옵션 증명서 디렉토리를 지정합니다.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

#SSL 버젼 지정. 기본값은 2
#curl_setopt ($ch, CURLOPT_SSLVERSION,1);

#TRUE 를 설정하면 헤더의 내용을 출력합니다.
#curl_setopt($ch, CURLOPT_HEADER, 1);

#HTTP 요청에서 사용되는 "User - Agent :" 헤더의 내용.
curl_setopt($ch, CURLOPT_USERAGENT, CURL_AGENT);

if($param['cookie']){
    #curl_close 호출 될 때 쿠키를 파일 이름으로 저장.
    curl_setopt($ch, CURLOPT_COOKIEJAR, CURL_COOKIE);

    #쿠키의 데이터를 http 헤더를 통해 보낸다.
    curl_setopt($ch, CURLOPT_COOKIEFILE, CURL_COOKIE);
}

#POST 로 데이터 전송.
#TRUE 를 설정하면 HTTP POST를 수행합니다. POST는 application / x - www - form - urlencoded 식으로 이루어집니다. 이것은 일반적인 HTML 양식과 같은 형식입니다.
if($param['post_data']){
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param['post_data']);
}

if($param['header']){
    curl_setopt($ch, CURLOPT_HTTPHEADER, $param['header']);
}

#최대 실행 시간(초)
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

#TRUE 를 설정하면 curl_exec () 의 반환 값을 문자열로 반환합니다. 일반적으로 데이터를 직접 출력합니다.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
curl_close($ch);

return $result;

}

아래는 결과입니다.

원화로 10만원 넣어둔게 나오는군요~ 헤헤

Array
(
[0] => Array
(
[currency] => KRW
[balance] => 100000.19014065
[locked] => 0.0
[avg_krw_buy_price] => 0
[modified] =>
)
)

이건 매수중일때~ locked 값이 생성되어있네요~(비트코인 8만원치 매수걸어둔 상태입니다.)

Array
(
[0] => Array
(
[currency] => KRW
[balance] => 19932.17614065
[locked] => 80068.014
[avg_krw_buy_price] => 0
[modified] =>
)

)

이건 비트코인 매수후의 데이터입니다.

데이터가 2개 리턴되네요.

Array
(
[0] => Array
(
[currency] => KRW
[balance] => 19932.17614065
[locked] => 63854.241165
[avg_krw_buy_price] => 0
[modified] =>
)

[1] => Array
    (
        [currency] => BTC
        [balance] => 0.00243
        [locked] => 0.0
        [avg_krw_buy_price] => 6669000
        [modified] => 
    )

)

Sort:  

Congratulations @siderace501! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

You made your First Vote
You made your First Comment
You got a First Vote

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:
SteemitBoard and the Veterans on Steemit - The First Community Badge.

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.18
TRX 0.13
JST 0.029
BTC 58009.23
ETH 3063.14
USDT 1.00
SBD 2.34