[rest api 예제] java (spring boot) - 카카오 로그인, 카카오 친구목록 조회, 메시지 발송

JAVA (Spring Boot)로 “카카오 로그인, 카카오 카카오 친구목록 조회, 메시지 발송” 테스트 해볼 수 있는 간단한 예제입니다.

java-demo.zip (135.0 KB)

[실행방법]

  1. STS4를 받아 설치합니다. https://spring.io/tools
  2. java-demo.zip 파일을 받아 압축을 푼 후, STS에서 import 합니다. "File > Import > Gradle(Existing Gradle Project) " 예제 폴더 설정
  3. 내 애플리케이션 > 앱 설정 > 요약 정보 > "REST API 키"를 복사해서 application.properties 파일 rest-api-key 항목에 설정합니다.
  4. 내 애플리케이션>제품 설정>카카오 로그인 > Redirect URI에 http://localhost:8080/login-callback 주소를 설정합니다.
  5. gradle refresh 후, Run As > Spring Boot App 실행
  6. http://localhost:8080/index.html 에 접속합니다.

[실행결과]
image

HttpCallService

@Service
public class HttpCallService {

	public String Call(String method, String reqURL, String header, String param) {
		String result = "";
		try {
			String response = "";
			URL url = new URL(reqURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
            conn.setRequestProperty("Authorization", header);
            if(param != null) {
            	System.out.println("param : " + param);
            	conn.setDoOutput(true);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
                bw.write(param);
                bw.flush();            	
                
            }
            int responseCode = conn.getResponseCode();
            System.out.println("responseCode : " + responseCode);
            
            System.out.println("reqURL : " + reqURL);
            System.out.println("method : " + method);
            System.out.println("Authorization : " + header);            
			InputStream stream = conn.getErrorStream();
		    if (stream != null) {
			    try (Scanner scanner = new Scanner(stream)) {
			        scanner.useDelimiter("\\Z");
			        response = scanner.next();
			    }			
			    System.out.println("error response : " + response);
		    }
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			while ((line = br.readLine()) != null) {
				result += line;
			}
			System.out.println("response body : " + result);
			
			br.close();
		} catch (IOException e) {
			return e.getMessage();
		}
		return result;
	}	
	
	public String CallwithToken(String method, String reqURL, String access_Token) {
		return CallwithToken(method, reqURL, access_Token, null);
	}	
	
	public String CallwithToken(String method, String reqURL, String access_Token, String param) {
		String header = "Bearer " + access_Token;
		return Call(method, reqURL, header, param);
	}		
}

KakaoService

package com.example.demo.service;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.RedirectView;

import com.example.demo.common.Const;
import com.example.demo.transformer.Trans;
import com.google.gson.JsonParser;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
public class KakaoService {
	
	private final HttpSession httpSession;	
	
	@Autowired
	public HttpCallService httpCallService;
	

	@Value("${rest-api-key}")
	private String REST_API_KEY;
	
	@Value("${redirect-uri}")
	private String REDIRECT_URI;	
	
	@Value("${authorize-uri}")
	private String AUTHORIZE_URI;		
	
	@Value("${token-uri}")
	public String TOKEN_URI;			
	
	@Value("${client-secret}")
	private String CLIENT_SECRET;	
	
	@Value("${kakao-api-host}")
	private String KAKAO_API_HOST;	
	
	
	public RedirectView goKakaoOAuth() {
       return goKakaoOAuth("");
	}
	
	public RedirectView goKakaoOAuth(String scope) {
	   
	   String uri = AUTHORIZE_URI+"?redirect_uri="+REDIRECT_URI+"&response_type=code&client_id="+REST_API_KEY;
	   if(!scope.isEmpty()) uri += "&scope="+scope;
			   
       return new RedirectView(uri);
	}	
	
	public RedirectView loginCallback(String code) {	
		String param = "grant_type=authorization_code&client_id="+REST_API_KEY+"&redirect_uri="+REDIRECT_URI+"&client_secret="+CLIENT_SECRET+"&code="+code;
		String rtn = httpCallService.Call(Const.POST, TOKEN_URI, Const.EMPTY, param);
        httpSession.setAttribute("token", Trans.token(rtn, new JsonParser()));     		
		return new RedirectView("/index.html");
	}
			
	public String getProfile() {	
		String uri = KAKAO_API_HOST + "/v2/user/me";
		return httpCallService.CallwithToken(Const.GET, uri, httpSession.getAttribute("token").toString());
	}
	
	public String getFriends() {	
		String uri = KAKAO_API_HOST + "/v1/api/talk/friends";
		return httpCallService.CallwithToken(Const.GET, uri, httpSession.getAttribute("token").toString());
	}	
	
	public String message() {	
		String uri = KAKAO_API_HOST + "/v2/api/talk/memo/default/send";
		return httpCallService.CallwithToken(Const.POST, uri, httpSession.getAttribute("token").toString(), Trans.default_msg_param);
	}		
	
	public String friendMessage(String uuids) {	
		String uri = KAKAO_API_HOST + "/v1/api/talk/friends/message/default/send";
		return httpCallService.CallwithToken(Const.POST, uri, httpSession.getAttribute("token").toString(), Trans.default_msg_param+"&receiver_uuids=["+uuids+"]");
	}	
	
	public String logout() {	
		String uri = KAKAO_API_HOST + "/v1/user/logout";
		return httpCallService.CallwithToken(Const.POST, uri, httpSession.getAttribute("token").toString(), Trans.default_msg_param);
	}	
}

index.html

<!DOCTYPE html>
<html lang="kr">
  <head>
    <meta charset="utf-8" />
    <title>Kakao REST-API python Flask example</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

  <body>
    <h1>1. 카카오 로그인 및 프로필 조회 예제</h1>
    <pre>
- [KOE101, KOE004] 내 애플리케이션>제품 설정>카카오 로그인 > 활성화 설정 : ON
- [KOE006] 내 애플리케이션>제품 설정>카카오 로그인 > Redirect URI : http://localhost:8080/login-callback
</pre
    >
    <div class="text-center">
      <script>
        function REST_Call(path) {
          axios
            .get("http://localhost:8080" + path, {
              params: {},
              withCredentials: true,
            })
            .then(({ data }) => {
              console.log(data);
              $("#contents").html(JSON.stringify(data));
            })
            .catch((err) => {
              console.log(err);
              $("#contents").html(JSON.stringify(err));
            });
        }
      </script>

      <a href="/login">
        <img
          src="//k.kakaocdn.net/14/dn/btqCn0WEmI3/nijroPfbpCa4at5EIsjyf0/o.jpg"
          width="222"
        /> </a
      ><br />

      <button onclick="REST_Call('/profile')">프로필 조회</button><br />

      <textarea id="contents" rows="20" cols="100"></textarea><br />

      <a href="/authorize?scope=friends,talk_message">
        <h2>친구목록 조회와 메세지 발송 권한 획득</h2> </a
      ><br />
      <button onclick="REST_Call('/friends')">친구목 조회</button>
      <button onclick="REST_Call('/message')">나에게 메시지 발송</button><br />
      <input type="text" id="uuids"/> <button onclick="REST_Call('/friends-message?uuids='+$('#uuids').val())">친구에게 메시지 발송</button> ex) "AAA","BBB"<br />
      <button onclick="REST_Call('/logout')">로그아웃</button><br />
    </div>
  </body>
</html>

로그인에 관한 가이드 : https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api
친구목록 관한 가이드 : https://developers.kakao.com/docs/latest/ko/kakaotalk-social/rest-api#get-friends
메시지에 관한 가이드 : https://developers.kakao.com/docs/latest/ko/message/rest-api

KOE006 에러 : https://devtalk.kakao.com/t/koe006/114778
친구 api, 메시지 api 사용을 위한 체크 리스트 : https://devtalk.kakao.com/t/api-api/116052
친구목록, 메시지 API 자주 겪는 에러 : https://devtalk.kakao.com/t/faq-api-api/82152?source_topic_id=109558
메시지 API 권한 신청 방법 : https://devtalk.kakao.com/t/api-how-to-request-permission-for-messaging-api/80421?source_topic_id=115052

2개의 좋아요