Skip to content

KakaoDevelopers

Kakao API 사용 방법

Categories

RESTful API

Message API

다음과 같이 진행한다.

  • 카카오 개발자 홈페이지 ( https://developers.kakao.com/ ) 에 접속하고 로그인한다. (파이어폭스 안되고 크롬 되더라)
  • 상단 메뉴 > 내 애플리케이션 > 애플리케이션 추가하기
    • 앱 이름: [직접 입력]
    • 사업자명: [직접 입력]
  • 추가된 애플리케이션 선택
  • 앱 설정 > 요약 정보 > REST API 키 <- 키 복사 !!
  • 카카오 로그인 > 활성화 설정 활성화
  • 카카오 로그인 > Redirect URI 추가 및 <- 주소 복사 !! 정확히 일치해야 한다.
    • OAuth Redirect URI을 추가한다 (복사)
  • 동의항목 > 카카오톡 메시지 전송 설정 후 <- ID(talk_message) 복사 !!
    • 이용 중 동의 선택
    • 동의 목적 입력
      • e.g. "테스트 알람"
  • 앱 설정 > 플랫폼 > Web 추가
    • 웹사이트 도메인 추가 (주소 마지막에 '/' 추가 금지)

OAuth등록을 위해 다음 주소에 내용 추가:

https://kauth.kakao.com/oauth/authorize?client_id={REST API 키}&redirect_uri={OAuth Recirect URL}&response_type=code&scope={동의항목 ID}

예를 들면:

  • REST API 키: e19ed0d304ec37d2be3ed041fd60e323
  • OAuth Redirect URI: https://localhost:20000/
  • 동의항목 ID: talk_message

일 경우:

https://kauth.kakao.com/oauth/authorize?client_id=e19ed0d304ec37d2be3ed041fd60e323&redirect_uri=https://localhost:20000/&response_type=code&scope=talk_message

WARNING

여기부터 코드 값이 지속적으로 바뀌므로 재접속 해야 한다

브라우저의 시크릿 모드로 접속한 후 Accept 한다. 그럼 다음과 같은 주소로 Redirect 된다.

https://localhost:20000/?code={코드}

위의 "{코드}"에 해당되는 내용을 복사한다.

예를 들면:

이후, 개인용 서버에서 카카오톡 메시지 API를 사용해 코드를 등록해야 한다.

샘플은 다음과 같다 (위의 {REST API 키}, {OAuth Redirect URI}, {코드}를 각각 복사하여 아래의 샘플에 추가한다)

import requests
import json
import sys

# 카카오톡 메시지 API
url = "https://kauth.kakao.com/oauth/token"

rest_api_key = "e19ed0d304ec37d2be3ed041fd60e323"
oauth_redirect_uri = "https://localhost:20000/"
# code = "BurXfeurZ2RJ4kM6r-6Y2z_-h3geKLmphRaysdso6VBIAkP-vkce7ZeomcJEElyNw3JIpAo3dRoAAAGC986kBw"
code = sys.argv[1]

data = {
    "grant_type" : "authorization_code",
    "client_id" : rest_api_key,
    "redirect_url" : oauth_redirect_uri,
    "code" : code
}
response = requests.post(url, data=data)
tokens = response.json()
print(tokens)  # 이 결과

with open("kakao_code.json", "w") as fp:
    json.dump(tokens, fp)

결과 Response는 다음과 같이 출력된다.

{
    'access_token': 'v247CUaLKUv6HMXsdnWWkuqJhmRI2jOT2fP1xn9eCj1y6gAAAYLn0ibe',
    'token_type': 'bearer',
    'refresh_token': 'f2k3GNKZPnt1bYZvVUmuz-HnELde1Kzjd9Z1iDNbCj9y6gAAAYLn0iwc',
    'expires_in': 21599,
    'scope': 'talk_message',
    'refresh_token_expires_in': 5183999
}

위의 access_token 값을 복사하여 아래, Authorization 헤더에 추가한다.

import json
import requests

url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"
access_token = "v247CUaLKUv6HMXsdnWWkuqJhmRI2jOT2fP1xn9eCj1y6gAAAYLn0ibe"

headers = {"Authorization": "Bearer " + access_token}

data = {
        "template_object" : json.dumps({ "object_type" : "text",
            "text" : "Google 뉴스: drone",
            "link" : {
                "web_url" : "https://www.google.co.kr/search?q=drone&source=lnms&tbm=nws",
                "mobile_web_url" : "https://www.google.co.kr/search?q=drone&source=lnms&tbm=nws"
                }
            })
        }

response = requests.post(url, headers=headers, data=data)
if response.json().get('result_code') == 0:
    print('메시지를 성공적으로 보냈습니다.')
else:
    print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(response.json()))

카카오톡을 확인해 보면 자신의 아이디로 채팅이 온 걸 확인할 수 있다.

목록 메시지 예제

import json
import requests

url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"

headers = {"Authorization": "Bearer " + "qixkf7oJe3e9hWuLmKpUql9GKcMbZqEWupnrOidzCilv1QABAYDe2-fh"}

template = {
    "object_type" : "list",
    "header_title" : "Google",
    "header_link" : {
        "web_url" : "www.google.com",
        "mobile_web_url" : "www.google.com"
    },
    "contents" : [
        {
            "title" : "1. 국립공원 뉴스",
            "description" : "검색어: national park",
            "image_url" : "https://cdn.kado.net/news/photo/201901/948844_399953_0825.jpg",
            "image_width" : 50, "image_height" : 50,
            "link" : {
                "web_url" : "https://www.google.co.kr/search?q=national+park&source=lnms&tbm=nws",
                "mobile_web_url" : "https://www.google.co.kr/search?q=national+park&source=lnms&tbm=nws"
            }
        },
        {
            "title" : "2. 딥러닝 뉴스",
            "description" : "검색어: deep learning",
            "image_url" : "https://cdn-images-1.medium.com/max/1200/1*iDQvKoz7gGHc6YXqvqWWZQ.png",
            "image_width" : 50, "image_height" : 50,
            "link" : {
                "web_url" : "https://www.google.co.kr/search?q=deep+learning&source=lnms&tbm=nws",
                "mobile_web_url" : "https://www.google.co.kr/search?q=deep+learning&source=lnms&tbm=nws"
            }
        }

    ],
    "buttons" : [
        {
            "title" : "Google로 이동",
            "link" : {
                "web_url" : "www.google.com",
                "mobile_web_url" : "www.google.com"
            }
        }
    ]

}

data = {
    "template_object" : json.dumps(template)
}

response = requests.post(url, data=data, headers=headers)
# print(response.status_code)
if response.json().get('result_code') == 0:
    print('메시지를 성공적으로 보냈습니다.')
else:
    print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(response.json()))

See also

  • PyKakao - 카카오 API 파이썬 패키지

Favorite site