프로젝트/coin-trading

1. 업비트 API 적용해보기

DJ.Kang 2025. 2. 5. 09:34

□ 업비트 API사용을 위한 key 발급
https://upbit.com/service_center/open_api_guide

 

Open API 안내 | 업비트(UPbit)

업비트에서는 개발자와 사용자를 위해 Open API를 제공하고 있습니다. 업비트 API를 통해 마켓정보, 잔고 조회, 주문, 출금 등 다양한 기능을 활용해보세요.

upbit.com

 

□ 의존성 추가

    // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
    implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.14'

    // https://mvnrepository.com/artifact/com.auth0/java-jwt
    implementation group: 'com.auth0', name: 'java-jwt', version: '4.5.0'

□ JWT토큰 생성기

https://docs.upbit.com/docs/create-authorization-request

 

업비트 개발자 센터

 

docs.upbit.com

package coin.cointrading.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
public class JwtTokenProvider {

    @Value("${upbit.access-key}")
    private String accessKey;
    @Value("${upbit.secret-key}")
    private String secretKey;

    public String createToken(){
        long expirationTime = 1000 * 60 * 60;  // 1 hour
        Date expirationDate = new Date(System.currentTimeMillis() + expirationTime);

        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        String jwtToken = JWT.create()
                .withClaim("access_key", accessKey)
                .withClaim("nonce", UUID.randomUUID().toString())
                .withExpiresAt(expirationDate)
                .sign(algorithm);

        return "Bearer " + jwtToken;
    }
}

 

□ 계좌 조회하기

package coin.cointrading.service;

import coin.cointrading.dto.AccountResponse;
import coin.cointrading.util.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TradingService {

    private final String serverUrl = "https://api.upbit.com";
    private final JwtTokenProvider jwtTokenProvider;
    private final RestTemplate restTemplate;

    public List<AccountResponse> getAccount() {
        String accountUrl = serverUrl + "/v1/accounts";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", jwtTokenProvider.createToken());
        HttpEntity<?> entity = new HttpEntity<>(headers);

        return restTemplate.exchange(
                accountUrl,
                HttpMethod.GET,
                entity,
                new ParameterizedTypeReference<List<AccountResponse>>() {
                }).getBody();
    }

}

 

- 응답화면