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

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

demo.zip (3.2 KB)

[실행방법]

  1. demo.zip 파일을 받아 압축을 푼 후, python 구동가능한 폴더에 복사합니다.
  2. 내 애플리케이션 > 앱 설정 > 요약 정보 > "REST API 키"를 복사해서 kakao_rest_api_example.py 파일 client_id 변수에 설정합니다.
  3. 내 애플리케이션>제품 설정>카카오 로그인 > Redirect URI에 http://localhost/redirect 주소를 설정합니다.
  4. kakao_rest_api_example.py 파일을 실행하고 localhost 으로 접속합니다.

[실행결과]
image

kakao_rest_api_example.py

import os
import requests
from flask import Flask, render_template, redirect, request, session

app = Flask(__name__)
app.secret_key = os.urandom(24)

client_id = ""
redirect_uri = "http://localhost/redirect"
kauth_host = "https://kauth.kakao.com"
kapi_host = "https://kapi.kakao.com"
client_secret = ""


@app.route("/")
def home():
    return render_template('demo.html')


@app.route("/authorize")
def authorize():
    scope_param = ""
    if request.args.get("scope"):
        scope_param = "&scope=" + request.args.get("scope")
    return redirect(
        "{0}/oauth/authorize?response_type=code&client_id={1}&redirect_uri={2}{3}".format(kauth_host, client_id,
                                                                                          redirect_uri, scope_param))


@app.route("/redirect")
def redirect_page():
    data = {'grant_type': 'authorization_code',
            'client_id': client_id,
            'redirect_uri': redirect_uri,
            'client_secret': client_secret,
            'code': request.args.get("code")}
    resp = requests.post(kauth_host + "/oauth/token", data=data)
    session['access_token'] = resp.json()['access_token']
    return redirect("/")


@app.route("/profile")
def profile():
    headers = {'Authorization': 'Bearer ' + session['access_token']}
    resp = requests.get(kapi_host + "/v2/user/me", headers=headers)
    return resp.text


@app.route("/friends")
def friends():
    headers = {'Authorization': 'Bearer ' + session['access_token']}
    resp = requests.get(kapi_host + "/v1/api/talk/friends", headers=headers)
    return resp.text


@app.route("/message")
def message():
    headers = {'Authorization': 'Bearer ' + session['access_token']}
    data = {
        'template_object': '{"object_type":"text","text":"Hello, world!","link":{"web_url":"https://developers.kakao.com","mobile_web_url":"https://developers.kakao.com"}}'}
    resp = requests.post(kapi_host + "/v2/api/talk/memo/default/send", headers=headers, data=data)
    return resp.text


@app.route("/friends_message")
def friends_message():
    headers = {'Authorization': 'Bearer ' + session['access_token']}
    data = {
        'receiver_uuids': '[{0}]'.format(request.args.get("uuids")),
        'template_object': '{"object_type":"text","text":"Hello, world!","link":{"web_url":"https://developers.kakao.com","mobile_web_url":"https://developers.kakao.com"}}'}
    resp = requests.post(kapi_host + "/v1/api/talk/friends/message/default/send", headers=headers, data=data)
    return resp.text


@app.route("/logout")
def logout():
    headers = {'Authorization': 'Bearer ' + session['access_token']}
    resp = requests.post(kapi_host + "/v1/user/logout", headers=headers)
    return resp.text


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, port=80)

demo.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/redirect
</pre
    >
    <div class="text-center">
      <script>
        function REST_Call(path) {
          axios
            .get("http://localhost" + 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="http://localhost/authorize">
        <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="http://localhost/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