페이지 이동경로
  • Docs>
  • Tutorial>
  • Implement Kakao Login

Tutorial

Implement Kakao Login

This document provides a step-by-step guide to implement Kakao Login directly using the languages below.

  • Node.js.
  • PHP.
  • Python.

The code used in this tutorial is available in the GitHub repository. If direct development feels challenging, you can test with the sample code, which is already implemented.

Overview

Category Details
What you will learn - Add Kakao Login button to a webpage.
- Configure consent items.
- Implement login functionality.
- Implement logout functionality.
- Implement unlink functionality.
- Implement functionality to retrieve information of the logged-in user.
Prerequisites Log in with Kakao Developers account.
Create Kakao Developers app.
Prepare development environment.

1. Set up project

In this step, you set up the project required to implement Kakao Login.

1-1. Create project

Enter the commands below in the terminal to create a new project folder and move into it. In this tutorial, configuration files and code files will be created in the kakao-login folder.

Node.js
PHP
Python
mkdir kakao-login
cd kakao-login
mkdir kakao-login
cd kakao-login
mkdir kakao-login
cd kakao-login

1-2. Initialize project

Node.js
PHP
Python
Initialize
npm init -y

When you run the command above in the terminal, a package.json file is created to manage the project's metadata (name, version, license, etc.), dependency list, and run scripts.

{
  "name": "kakao-login",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}
No additional work is required for PHP.
Optional: Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # macOS/Linux

The commands above create and activate a virtual environment; this is optional.

1-3. Install dependencies

Node.js
PHP
Python
npm install express express-session axios qs

When you run the command above in the terminal, the libraries required for the project are installed.

PHP can run without installing additional packages.
pip install Flask requests

When you run the command above in the terminal, the libraries required for the project are installed.

2. Set up app

To use Kakao Login, you must configure settings in Kakao Developers. For setup, see Test with sample code > Set up app.

3. [Server] Handle login request

In this step, you write code to handle login requests on the server.

  1. In your code editor (IDE), open the project created earlier.
  2. Create folders and files by referring to the directory structure below, then copy and paste the code provided in each step. At the top of each language-specific example, check the file path and file name.
Directory structure
Node.js
PHP
Python
.
│
├── index.html # Main HTML file.
├── app.js # Main application file.
├── package.json # Project metadata and dependencies.
└── README.md # Project description file.
.
├── api.php # PHP script that handles Kakao API calls.
├── index.html # Main HTML file.
└── README.md # Project description file.
.
├── api.py              # Main Flask application file.
├── requirements.txt    # Project dependencies file.
├── templates/          # HTML templates directory.
│   └── index.html      # Main page template.
└── README.md           # Project description file.

3-1. Configure basic server

Node.js
PHP
Python
//app.js

const express = require("express");
const session = require("express-session");
const qs = require("qs");
const axios = require("axios");
const app = express();
const port = 4000;

// Add settings for serving static files.
app.use(express.static(__dirname));
app.use(express.json()); // Add for JSON parsing.

// Session settings to maintain login state.
app.use(
  session({
    secret: "your session secret",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false },
  })
);
// api.php

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Start a session to maintain login state.
session_start();
# api.py

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

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

3-2. Define common settings and request function

Declare variables such as app key, domain, and API hosts that are repeatedly used for Kakao API requests, and define a request function. For each variable, see Test with sample code > Apply app information.

You must enter the REST API key of your app in the client_id value from App management page under [App] > [General] > [App key]. If you use an incorrect app key, a KOE101 error occurs.

Node.js
PHP
Python
// app.js
// Code entered in the previous step.
//   :

// Set variables.
const client_id = "6f95e7e3146********";               // Replace with your REST API key.
const client_secret = "this is client secret key";
const domain = "http://localhost:4000";
const redirect_uri = `${domain}/redirect`;
const token_uri = "https://kauth.kakao.com/oauth/token"; // Kakao authorization server URL for access token requests.
const api_host = "https://kapi.kakao.com";               // Kakao API host.

// Define API request function.
async function call(method, uri, param, header) {
  let rtn;
  try {
    // Send an HTTP request to the Kakao API server using the specified method, uri, param, and header values.
    rtn = await axios({
      method: method,   // HTTP method such as "POST" or "GET".
      url: uri,         // API URL to request.
      headers: header,  // Request headers (for example, Content-Type, Authorization).
      data: param,      // Request body data.
    });
  } catch (err) {
    // On error, store the error response from the response object.
    rtn = err.response;
  }
  // Return response data regardless of success or failure.
  return rtn.data;
}
// api.php
// Code entered in the previous step.
//   :

$client_id = '6f95e7e3146********';       // Replace with your REST API key.
$client_secret = ' this is client secret key ';
$domain = 'http://localhost:4000';
$redirect_uri = $domain . '/api.php?action=redirect';
$kauth_host = 'https://kauth.kakao.com';  // Kakao authorization server URL for access token requests.
$kapi_host = 'https://kapi.kakao.com';    // Kakao API host.

// Define API request function.
function call($method, $uri, $params = [], $headers = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $uri);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, !empty($params) ? http_build_query($params) : '');
    }
    
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

$action = $_GET['action'] ?? '';
# api.py
# Code entered in the previous step.
# : 

client_id = "6f95e7e3146********"      # Replace with your REST API key.
client_secret = " this is client secret key "
domain = "http://localhost:4000"
redirect_uri = domain + "/redirect"
kauth_host = "https://kauth.kakao.com" # Kakao authorization server URL for access token requests.
kapi_host = "https://kapi.kakao.com"   # Kakao API host.

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

3-3. Get authorization code

Implement 1. Get authorization code in the Kakao Login process. The code below displays the Kakao Login screen and the consent screen to the user. When the user selects the [Login with Kakao Account] button, the Get authorization code API is called, and the Kakao Login and consent screen is shown.

After the user logs in with Kakao Account and selects [Agree and continue] on the consent screen, the code to request an authorization code from Kakao runs. At this time, pass your app’s REST API key to client_id, and the path set in Test with sample code > Register redirect URI to redirect_uri.

Redirect URI example

When a user logs in and consents via their Kakao Account, Kakao authenticates the user and redirects the browser to the redirect URI. Then, the authorization code is sent to this URI.

https://${CONFIGURED_REDIRECT_URI}/?code=${AUTHORIZATION_CODE_RECEIVED} 

# Example
http://localhost:4000/redirect?code=abc123xyz
Node.js
PHP
Python
// app.js
// Code entered in the previous step.
//   :

// Send a request to the Kakao authorization server.
app.get("/authorize", function (req, res) {
  // Optional: When requesting additional consent from the user, pass consent item IDs via the scope value.
  // You need to request additional features for friends list and message sending.
  // (Example: /authorize?scope=friends,talk_message)
  let { scope } = req.query;
  let scopeParam = "";
  if (scope) {
    scopeParam = "&scope=" + scope;
  }

  // Redirect to the Kakao authorization server.
  // After user consent, the authorization code is delivered to the redirect URI.
  res.status(302).redirect(
      `https://kauth.kakao.com/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code${scopeParam}`
  );
});
// api.php
// Code entered in the previous step 
// :  

// Send a request to the Kakao authorization server.
switch ($action) {
    case 'authorize':
        // Optional: When requesting additional consent from the user, pass consent item IDs via the scope value.
        // You need to request additional features for friends list and message sending.
        // (Example: /api.php?action=authorize&scope=friends,talk_message)
        $scope = $_GET['scope'] ?? '';
        $scopeParam = $scope ? "&scope=" . urlencode($scope) : "";

        // Redirect to the Kakao authorization server.
        // After user consent, the authorization code is delivered to the redirect URI.
        header("Location: {$kauth_host}/oauth/authorize?client_id={$client_id}&redirect_uri={$redirect_uri}&response_type=code{$scopeParam}");
        exit;
}
# api.py
# Code entered in the previous step.
# :

# Send a request to the Kakao authorization server.
@app.route("/authorize")
def authorize():
    # Optional: When requesting additional consent from the user, pass consent item IDs via the scope value.
    # You need to request additional features for friends list and message sending.
    # (Example: /authorize?scope=friends,talk_message)
    scope_param = ""
    if request.args.get("scope"):
        scope_param = "&scope=" + request.args.get("scope")
    
    # Redirect to the Kakao authorization server.
    # After user consent, the authorization code is delivered to the redirect URI.
    return redirect(
        "{0}/oauth/authorize?response_type=code&client_id={1}&redirect_uri={2}{3}".format(
            kauth_host, client_id, redirect_uri, scope_param))

3-4. Request access token and save session

The service server uses the authorization code issued by Kakao to get an access token.

An access token is a credential required when calling Kakao APIs such as retrieving user information or sending messages. Requesting the authorization code in the previous step is ultimately required to obtain this access token. For more details, see Q. What are an authorization code and an access token?.

Store the access token returned by the Kakao API server in the session to maintain the user's login state. For more details, see Q. What is a session?.

Node.js
PHP
Python
// app.js
// Code entered in the previous step.
//   :

// Request an access token using the authorization code received from the Kakao authorization server.
app.get("/redirect", async function (req, res) {
  // Build parameters required for the token request.
  const param = qs.stringify({
    grant_type: "authorization_code",   // Fixed grant type.
    client_id: client_id,               // REST API key of your app.
    redirect_uri: redirect_uri,         // Registered redirect URI.
    code: req.query.code,               // Authorization code received.
    client_secret: client_secret,       // Optional: Add if using Client secret.
  });

  // Set API request header.
  const header = { "content-type": "application/x-www-form-urlencoded" };

  // Request access token from the Kakao authorization server.
  const rtn = await call("POST", token_uri, param, header);

  // Save the issued access token in the session (to maintain login state).
  req.session.key = rtn.access_token;

  // After login is complete, navigate to the main page.
  res.status(302).redirect(`${domain}/index.html?login=success`);
});
// api.php
// :  
// switch ($action) { 
// Code entered in the previous step 

    // Request an access token using the authorization code received from the Kakao authorization server.
    case 'redirect':
        // Build parameters required for the token request.
        $params = [
            'grant_type' => 'authorization_code',  // Fixed grant type.
            'client_id' => $client_id,             // REST API key of your app.
            'redirect_uri' => $redirect_uri,       // Registered redirect URI.
            'client_secret' => $client_secret,     // Optional: Add if using Client secret.
            'code' => $_GET['code']                // Authorization code received.
        ];

        // Set API request header.
        $headers = ['Content-Type: application/x-www-form-urlencoded'];

        // Request access token from the Kakao authorization server.
        $response = call('POST', $kauth_host."/oauth/token", $params, $headers);
        echo json_encode($response);

        // Save the issued access token in the session (to maintain login state).
        if (isset($response['access_token'])) {
            $_SESSION['key'] = $response['access_token'];

            // After login is complete, navigate to the main page.
            header("Location: {$domain}/index.html?login=success");
        }
        exit;
// }
# api.py
# Code entered in the previous step.
# :

# Request an access token using the authorization code received from the Kakao authorization server.
@app.route("/redirect")
def redirect_page():
    # Build parameters required for the token request.
    data = {
        'grant_type': 'authorization_code',  # Fixed grant type.
        'client_id': client_id,              # REST API key of your app.
        'redirect_uri': redirect_uri,        # Registered redirect URI.
        'client_secret': client_secret,      # Optional: Add if using Client secret.
        'code': request.args.get("code")     # Authorization code received.
    }

    # Request access token from the Kakao authorization server.
    resp = requests.post(kauth_host + "/oauth/token", data=data)

    # Save the issued access token in the session (to maintain login state).
    session['access_token'] = resp.json()['access_token']

    # After login is complete, navigate to the main page.
    return redirect("/?login=success")

3-5. Retrieve information of logged-in user

In this step, request information of the logged-in user, such as a service user ID, nickname, profile image. Include the issued access token in the Authorization request header to call the Retrieve user information API.

To complete Kakao Login, you must call the Retrieve user information API after the user logs in. This links the user to the app. (Note: Unlinking users with incomplete signup)

Node.js
PHP
Python
// app.js
// Code entered in the previous step.
//   :

// Request to retrieve information of the logged-in user using the access token.
app.get("/profile", async function (req, res) {
  const uri = api_host + "/v2/user/me";  // API URL to retrieve user information.
  const param = {};  // No parameters are required when requesting user information.
  const header = {
    "content-type": "application/x-www-form-urlencoded",  // Specify Content-Type header.
    Authorization: "Bearer " + req.session.key,  // Pass the access token stored in the session.
  };

  const rtn = await call("POST", uri, param, header);  // Send request to Kakao API.

  res.send(rtn);  // Return the retrieved user information to the client.
});
// api.php
// switch ($action) { 
// Code entered in the previous step 
// :
    // Request to retrieve information of the logged-in user using the access token.
    case 'profile':
        $uri = $kapi_host . "/v2/user/me";  // API URL to retrieve user information.
        $headers = [
            'Content-Type: application/x-www-form-urlencoded',  // Specify Content-Type header.
            'Authorization: Bearer ' . $_SESSION['key']  // Pass the access token stored in the session.
        ];

        $response = call('POST', $uri, [], $headers);  // Send request to Kakao API.
        header('Content-Type: application/json');

        echo json_encode($response);  // Return the retrieved user information to the client.
        exit;
// }
# api.py
# Code entered in the previous step.
# :

# Request to retrieve information of the logged-in user using the access token.
@app.route("/profile")
def profile():
    headers = {
        'Authorization': 'Bearer ' + session.get('access_token', '')  # Pass the access token stored in the session.
    }

    resp = requests.get(kapi_host + "/v2/user/me", headers=headers)  # Send API request to retrieve user information.

    return resp.text  # Return the retrieved user information to the client.

3-6. Implement logout and unlink

In this step, implement logout and unlink features for logged-in users.

Add the code that calls the Logout API to end the user's session, and the Unlink API to unlink the user from app.

Node.js
PHP
Python
// app.js
// Code entered in the previous step.
//   :

// Logout request: End the session and log out the user.
app.get("/logout", async function (req, res) {
  const uri = api_host + "/v1/user/logout";  // Logout API URL.
  const header = {
    Authorization: "Bearer " + req.session.key  // Pass the access token stored in the session.
  };

  const rtn = await call("POST", uri, null, header);  // Send logout request to Kakao API.
  req.session.destroy();  // Delete session (logout).
  res.send(rtn);  // Return the response to the client.
});

// Unlink request: Unlink the user and the app, then end the session.
app.get("/unlink", async function (req, res) {
  const uri = api_host + "/v1/user/unlink";  // Unlink API URL.
  const header = {
    Authorization: "Bearer " + req.session.key  // Pass the access token stored in the session.
  };

  const rtn = await call("POST", uri, null, header);  // Send unlink request to Kakao API.
  req.session.destroy();  // Delete session (unlink).
  res.send(rtn);  // Return the response to the client.
});
// api.php
// :  
// switch ($action) { 
// Code entered in the previous step
// :

    // Logout request: End the session and log out the user.
    case 'logout':
        $uri = $kapi_host . "/v1/user/logout";  // Logout API URL.
        $headers = [
            'Authorization: Bearer ' . $_SESSION['key']  // Pass the access token stored in the session.
        ];

        $response = call('POST', $uri, [], $headers);  // Send logout request to Kakao API.
        session_destroy();  // Delete session (logout).
        header('Content-Type: application/json');
        echo json_encode($response);  // Return the response to the client.
        exit;

    // Unlink request: Unlink the user and the app, then end the session.
    case 'unlink':
        $uri = $kapi_host . "/v1/user/unlink";  // Unlink API URL.
        $headers = [
            'Authorization: Bearer ' . $_SESSION['key']  // Pass the access token stored in the session.
        ];

        $response = call('POST', $uri, [], $headers);  // Send unlink request to Kakao API.
        session_destroy();  // Delete session (unlink).
        header('Content-Type: application/json');
        echo json_encode($response);  // Return the response to the client.
        exit;
// }
# api.py
# Code entered in the previous step.
# :

# Logout request: End the session and log out the user.
@app.route("/logout")
def logout():
    headers = {
        'Authorization': 'Bearer ' + session.get('access_token', '')  # Pass the access token stored in the session.
    }
    resp = requests.post(kapi_host + "/v1/user/logout", headers=headers)  # Send logout request to Kakao API.
    session.pop('access_token', None)  # Delete session (logout).
    return resp.text  # Return the response to the client.

# Unlink request: Unlink the user and the app, then end the session.
@app.route("/unlink")
def unlink():
    headers = {
        'Authorization': 'Bearer ' + session.get('access_token', '')  # Pass the access token stored in the session.
    }
    resp = requests.post(kapi_host + "/v1/user/unlink", headers=headers)  # Send unlink request to Kakao API.
    session.pop('access_token', None)  # Delete session (unlink).
    return resp.text  # Return the response to the client.

3-7. Configure server run settings

Add the code below at the end of the file to run the server.

Node.js
PHP
Python
// app.js
// Code entered in the previous step.
//   :

app.listen(port, () => {
  console.log(`Server is running at ${domain}`);
});
For PHP, no code is required to run the server.
# Code entered in the previous step.
#   :

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

4. [UI] Build login screen

In this step, you create the UI (User interface) shown to users.

Under the created project, create an index.html file by referring to the directory structure, then add the code below. The index.html file is used to construct the UI.

In this tutorial, the style.css file hosted on GitHub is directly imported in index.html. The style.css file sets UI styles and is not directly related to the functionality.

Node.js
PHP
Python
<!-- index.html -->
<!DOCTYPE html>
<html lang="kr">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Kakao REST-API Node.js example</title>
  <!-- Script to load Kakao JavaScript SDK. -->
  <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
  <!-- Import CSS file to set UI styles. -->
  <link rel="stylesheet" href="https://kakao-tam.github.io/developers-static/style.css" />
  <link rel="icon" type="image/png"
    href="https://devtalk.kakao.com/uploads/default/optimized/2X/9/9b7b5d9cbbe2e8d6a5410c2d28926804cd8b0bb1_2_32x32.png" />
</head>

<body>
  <div class="header">
    <h1>Kakao Login and API example</h1>
  </div>
  <div class="main-container">
    <div class="container">
      <div class="vertical-layout">
        <script>
          const domain = window.location.origin;
          Kakao.init(" JavaScript key "); // To test [Login with JavaScript SDK], enter the JavaScript key found in [App keys].

          function kakaoLogin() {
            Kakao.Auth.authorize({
              redirectUri: `${domain}/redirect`,
            });
          }

          function REST_Call(path) {
            fetch(domain + path)
              .then(response => response.text()) // Convert response to text.
              .then(data => {
                try {
                  // Try JSON parsing.
                  const jsonData = JSON.parse(data);
                  setContents(JSON.stringify(jsonData, null, 2));
                } catch (e) {
                  // If JSON parsing fails, output as text.
                  setContents(data);
                }
              })
              .catch(error => {
                console.error("Fetch error:", error);
              });
          }

          function setContents(data) {
            document.getElementById("contents").value = data;
          }
          // Show login success message.
          window.onload = function() {
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('login') === 'success') {
              const successLabel = document.createElement('span');
              successLabel.textContent = 'Login successful';
              successLabel.style.color = 'green';
              successLabel.style.marginLeft = '10px';
              document.querySelector('.login-buttons').appendChild(successLabel);
            }
          }
        </script>
        <!-- Login button area. -->
        <div class="login-container">
          <div class="login-buttons">
            <!-- Button to log in with REST API. -->
            <a href="/authorize">
              <img src="//k.kakaocdn.net/14/dn/btqCn0WEmI3/nijroPfbpCa4at5EIsjyf0/o.jpg" alt="Kakao Login" />
            </a>
            <!-- Button to log in with JavaScript SDK; initialize JS SDK to test. -->
            <button onclick="kakaoLogin()" style="
                  background-color: white;
                  border: 1px solid var(--kakao-yellow);
                ">
              Login with JavaScript SDK
            </button>            
          </div>
        </div>        
        <!-- Button area to test login features. -->
        <div class="api-container">
          <div class="section-title">Basic features</div>
          <div class="button-group">
            <button onclick="REST_Call('/profile')">Retrieve user information</button>
            <button onclick="REST_Call('/logout')" style="background-color: white; border: 1px solid #e5e5e5">
              Logout
            </button>
            <button onclick="REST_Call('/unlink')" style="
                  background-color: white;
                  color: #ff5c5c;
                  border: 1px solid #ff5c5c;
                ">
              Unlink
            </button>
          </div>
        </div>
        <!-- Response area. -->
        <textarea id="contents" placeholder="The API response will be displayed here."></textarea>
      </div>
    </div>
  </div>
</body>

</html>
<!-- index.html -->
<!DOCTYPE html>
<html lang="kr">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Kakao REST-API PHP example</title>
  <!-- Script to load Kakao JavaScript SDK. -->
  <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
  <!-- Import CSS file to set UI styles. -->
  <link rel="stylesheet" href="https://kakao-tam.github.io/developers-static/style.css" />
  <link rel="icon" type="image/png"
      href="https://devtalk.kakao.com/uploads/default/optimized/2X/9/9b7b5d9cbbe2e8d6a5410c2d28926804cd8b0bb1_2_32x32.png" />
</head>

<body>
    <div class="header">
        <h1>Kakao Login and API example</h1>
    </div>
    <div class="main-container">
        <div class="container">
            <div class="vertical-layout">
                <script>
                    const domain = window.location.origin;
                    Kakao.init(" JavaScript key "); // To test [Login with JavaScript SDK], enter the JavaScript key found in [App keys].

                    function kakaoLogin() {
                        Kakao.Auth.authorize({
                            redirectUri: `${domain}/api.php?action=redirect`,
                        });
                    }

                    function REST_Call(path) {
                        fetch(domain + path)
                            .then(response => response.text()) // Convert response to text.
                            .then(data => {
                                try {
                                    // Try JSON parsing.
                                    const jsonData = JSON.parse(data);
                                    setContents(JSON.stringify(jsonData, null, 2));
                                } catch (e) {
                                    // If JSON parsing fails, output as text.
                                    setContents(data);
                                }
                            })
                            .catch(error => {
                                console.error("Fetch error:", error);
                            });
                    }

                    function setContents(data) {
                        document.getElementById("contents").value = data;
                    }

                    // Show login success message.
                    window.onload = function() {
                        const urlParams = new URLSearchParams(window.location.search);
                        if (urlParams.get('login') === 'success') {
                        const successLabel = document.createElement('span');
                        successLabel.textContent = 'Login successful';
                        successLabel.style.color = 'green';
                        successLabel.style.marginLeft = '10px';
                        document.querySelector('.login-buttons').appendChild(successLabel);
                        }
                    }                    
                </script>
                <!-- Login button area. -->
                <div class="login-container">
                    <div class="login-buttons">
                        <!-- Button to log in with REST API. -->
                        <a href="/api.php?action=authorize">
                            <img src="//k.kakaocdn.net/14/dn/btqCn0WEmI3/nijroPfbpCa4at5EIsjyf0/o.jpg" alt="Kakao Login" />
                        </a>
                        <!-- Button to log in with JavaScript SDK; initialize JS SDK to test. -->
                        <button onclick="kakaoLogin()"
                            style="background-color: white; border: 1px solid var(--kakao-yellow);">
                            Login with JavaScript SDK
                        </button>
                    </div>
                </div>
                <!-- Button area to test login features. -->
                <div class="api-container">
                    <div class="section-title">Basic features</div>
                    <div class="button-group">
                        <button onclick="REST_Call('/api.php?action=profile')">Retrieve user information</button>
                        <button onclick="REST_Call('/api.php?action=logout')"
                            style="background-color: white; border: 1px solid #E5E5E5;">Logout</button>
                        <button onclick="REST_Call('/api.php?action=unlink')"
                            style="background-color: white; color: #FF5C5C; border: 1px solid #FF5C5C;">Unlink</button>
                    </div>
                </div>
                <!-- Response area. -->
                <textarea id="contents" placeholder="The API response will be displayed here."></textarea>

            </div>
        </div>
    </div>
</body>

</html>
<!-- /templates/index.html -->

<!DOCTYPE html>
<html lang="kr">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Kakao REST-API Python.flask example</title>
  <!-- Script to load Kakao JavaScript SDK. -->
  <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
  <!-- Import CSS file to set UI styles. -->
  <link rel="stylesheet" href="https://kakao-tam.github.io/developers-static/style.css" />
  <link rel="icon" type="image/png"
    href="https://devtalk.kakao.com/uploads/default/optimized/2X/9/9b7b5d9cbbe2e8d6a5410c2d28926804cd8b0bb1_2_32x32.png" />
</head>

<body>
  <div class="header">
    <h1>Kakao Login and API example</h1>
  </div>
  <div class="main-container">
    <div class="container">
      <div class="vertical-layout">
        <script>
          const domain = window.location.origin;
          Kakao.init(" JavaScript key "); // To test [Login with JavaScript SDK], enter the JavaScript key found in [App keys].

          function kakaoLogin() {
            Kakao.Auth.authorize({
              redirectUri: `${domain}/redirect`,
            });
          }

          function REST_Call(path) {
            fetch(domain + path)
              .then(response => response.text()) // Convert response to text.
              .then(data => {
                try {
                  // Try JSON parsing.
                  const jsonData = JSON.parse(data);
                  setContents(JSON.stringify(jsonData, null, 2));
                } catch (e) {
                  // If JSON parsing fails, output as text.
                  setContents(data);
                }
              })
              .catch(error => {
                console.error("Fetch error:", error);
              });
          }

          function setContents(data) {
            document.getElementById("contents").value = data;
          }

          // Show login success message.
          window.onload = function() {
              const urlParams = new URLSearchParams(window.location.search);
              if (urlParams.get('login') === 'success') {
              const successLabel = document.createElement('span');
              successLabel.textContent = 'Login successful';
              successLabel.style.color = 'green';
              successLabel.style.marginLeft = '10px';
              document.querySelector('.login-buttons').appendChild(successLabel);
              }
          }          
        </script>
        <!-- Login button area. -->
        <div class="login-container">
          <div class="login-buttons">
            <!-- Button to log in with REST API. -->           
            <a href="/authorize">
              <img src="//k.kakaocdn.net/14/dn/btqCn0WEmI3/nijroPfbpCa4at5EIsjyf0/o.jpg" alt="Kakao Login" />
            </a>
            <!-- Button to log in with JavaScript SDK; initialize JS SDK to test. -->
            <button onclick="kakaoLogin()" style="background-color: white; border: 1px solid var(--kakao-yellow);">
              Login with JavaScript SDK
            </button>
          </div>
        </div>
        <!-- Button area to test login features. -->
        <div class="api-container">
          <div class="section-title">Basic features</div>
          <div class="button-group">
            <button onclick="REST_Call('/profile')">Retrieve user information</button>
            <button onclick="REST_Call('/logout')"
              style="background-color: white; border: 1px solid #E5E5E5;">Logout</button>
            <button onclick="REST_Call('/unlink')"
              style="background-color: white; color: #FF5C5C; border: 1px solid #FF5C5C;">Unlink</button>
          </div>
        </div>
        <!-- Response area. -->
        <textarea id="contents" placeholder="The API response will be displayed here."></textarea>
      </div>
    </div>
  </div>
</body>

</html>

5. Run

In this step, run the server so you can call APIs and test from the configured screen.

5-1. Run server

Node.js
PHP
Python
node app.js
php -S localhost:4000
python api.py

5-2. Access browser and test

After starting the server, access the address printed in the terminal, and then you can see the test webpage as shown below. For details, see Test with sample code > Test.

Login-only test webpage

See more

  • Test with sample code: This guide walks you through how to quickly test Kakao Login using pre-implemented sample code.
  • Getting started with Kakao API: This guide walks you through the essential steps for getting started with the Kakao API, from creating your app to making your first API call.
  • Design guide: This guide walks you through the instructions for using the official Kakao Login buttons and design assets.