### Node.js Server Configuration for Kakao API
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Sets up a Node.js server using Express for Kakao API integration. It includes session management, static file serving, and necessary middleware. API credentials and endpoint URLs are defined, and the server starts listening on a specified port.
```javascript
// Complete server setup
const express = require('express');
const session = require('express-session');
const qs = require('qs');
const axios = require('axios');
const app = express();
const port = 4000;
// Static files and middleware
app.use(express.static(__dirname));
app.use(express.json());
// Session configuration
app.use(session({
secret: 'your session secret',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
// API credentials and endpoints
const client_id = 'your_rest_api_key';
const client_secret = 'your_client_secret';
const domain = 'http://localhost:4000';
const redirect_uri = `${domain}/redirect`;
const kauth_host = 'https://kauth.kakao.com';
const kapi_host = 'https://kapi.kakao.com';
// Start server
app.listen(port, () => {
console.log(`Server is running at ${domain}`);
});
// Installation and setup:
// npm install express express-session qs axios
// node app.js
// Navigate to http://localhost:4000
// Environment variables approach (recommended):
// const client_id = process.env.KAKAO_REST_API_KEY;
// const client_secret = process.env.KAKAO_CLIENT_SECRET;
```
--------------------------------
### Initiate Kakao OAuth 2.0 Authorization (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Starts the Kakao OAuth 2.0 authorization flow by redirecting users to Kakao's server. It supports optional scope parameters to request specific permissions like friend list access or message sending. This endpoint requires the client ID and redirect URI to be configured.
```javascript
const express = require('express');
const app = express();
const client_id = 'your_rest_api_key';
const redirect_uri = 'http://localhost:4000/redirect';
const kauth_host = 'https://kauth.kakao.com';
app.get('/authorize', function (req, res) {
let { scope } = req.query;
var scopeParam = '';
if (scope) {
scopeParam = '&scope=' + scope;
}
res.status(302).redirect(
`${kauth_host}/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code${scopeParam}`
);
});
// Usage:
// Navigate to http://localhost:4000/authorize for basic login
// Navigate to http://localhost:4000/authorize?scope=friends,talk_message for additional permissions
```
--------------------------------
### Handle Kakao OAuth Redirect and Get Access Token (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Processes the callback from Kakao's authorization server, exchanges the authorization code for an access token, and stores it in the user's session. It uses Axios for HTTP requests and qs for query string parsing. Session management is handled by express-session.
```javascript
const qs = require('qs');
const axios = require('axios');
const session = require('express-session');
app.use(session({
secret: 'your session secret',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
const client_secret = 'your_client_secret';
async function call(method, uri, param, header) {
try {
rtn = await axios({
method: method,
url: uri,
headers: header,
data: param
});
} catch (err) {
rtn = err.response;
}
return rtn.data;
}
app.get('/redirect', async function (req, res) {
const param = qs.stringify({
grant_type: 'authorization_code',
client_id: client_id,
redirect_uri: redirect_uri,
client_secret: client_secret,
code: req.query.code
});
const header = { 'content-type': 'application/x-www-form-urlencoded' };
var rtn = await call('POST', kauth_host + '/oauth/token', param, header);
if (rtn.access_token) {
req.session.key = rtn.access_token;
res.status(302).redirect('/index.html?login=success');
}
});
// Expected response from Kakao:
// {
// "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
// "token_type": "bearer",
// "refresh_token": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
// "expires_in": 21599,
// "scope": "profile_nickname profile_image"
// }
```
--------------------------------
### Send Message to Friends
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Sends a message to specified friends using their UUIDs. Requires both 'friends' and 'talk_message' scope permissions.
```APIDOC
## POST /friend-message
### Description
Sends a message to specified friends using their UUIDs. Requires both 'friends' and 'talk_message' scope permissions.
### Method
POST
### Endpoint
/friend-message
### Parameters
#### Query Parameters
- **uuid** (string) - The UUID of the friend to send the message to. Can be a comma-separated string for multiple friends. (Required)
#### Request Body
- **receiver_uuids** (string) - A JSON string representing an array of friend UUIDs. (Required)
- **template_object** (string) - JSON string representing the message template object. (Required)
### Request Example
```javascript
// GET /friend-message?uuid="abcd-efgh-ijkl-mnop"
app.get('/friend-message', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/api/talk/friends/message/default/send';
const { uuid } = req.query;
const param = qs.stringify({
receiver_uuids: `[${uuid}]`,
template_object: JSON.stringify(message_template) // message_template defined elsewhere
});
const header = {
'content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, param, header);
res.send(rtn);
});
```
### Response
#### Success Response (200)
- **successful_receiver_uuids** (array) - An array of UUIDs for which the message was successfully sent.
#### Response Example
```json
{
"successful_receiver_uuids": ["abcd-efgh-ijkl-mnop"]
}
```
```
--------------------------------
### OAuth Redirect Handler
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Handles the OAuth callback from Kakao's authorization server, exchanges the authorization code for an access token, and stores the token in the user's session.
```APIDOC
## GET /redirect
### Description
Handles the OAuth callback from Kakao's authorization server, exchanges the authorization code for an access token, and stores the token in the user's session for subsequent API calls.
### Method
GET
### Endpoint
/redirect
### Query Parameters
- **code** (string) - Required - The authorization code received from Kakao.
### Request Example
(This endpoint is called by Kakao after user authorization)
### Response
#### Success Response (200)
Redirects to `/index.html?login=success` upon successful token retrieval.
#### Response Example (Token Exchange)
```json
{
"access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"token_type": "bearer",
"refresh_token": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"expires_in": 21599,
"scope": "profile_nickname profile_image"
}
```
### Error Handling
- If `access_token` is not received, the redirect to `/index.html` may fail or indicate a login error.
- Ensure `client_id`, `client_secret`, and `redirect_uri` are correctly configured.
```
--------------------------------
### Friends List Retrieval
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Fetches the authenticated user's Kakao Talk friends list. Requires the 'friends' scope permission to be granted during the authorization process.
```APIDOC
## GET /friends
### Description
Fetches the authenticated user's Kakao Talk friends list. Requires the 'friends' scope permission to be granted during the authorization process.
### Method
GET
### Endpoint
/friends
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// GET /friends
app.get('/friends', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/api/talk/friends';
const param = null;
const header = {
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('GET', uri, param, header);
res.send(rtn);
});
```
### Response
#### Success Response (200)
- **elements** (array) - List of friend objects.
- **total_count** (integer) - Total number of friends.
- **favorite_count** (integer) - Number of favorite friends.
#### Response Example
```json
{
"elements": [
{
"uuid": "abcd-efgh-ijkl-mnop",
"id": 987654321,
"profile_nickname": "친구1",
"profile_thumbnail_image": "http://k.kakaocdn.net/...jpg",
"favorite": false
},
{
"uuid": "qrst-uvwx-yzab-cdef",
"id": 123456789,
"profile_nickname": "친구2",
"profile_thumbnail_image": "http://k.kakaocdn.net/...jpg",
"favorite": true
}
],
"total_count": 2,
"favorite_count": 1
}
```
```
--------------------------------
### Kakao Frontend JavaScript SDK Integration
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Integrates Kakao's JavaScript SDK for client-side authentication. It allows for a smoother user experience using popup-based login. The SDK needs to be initialized with a JavaScript key, and provides functions for login and calling backend API endpoints.
```javascript
// Initialize Kakao JavaScript SDK
Kakao.init('your_javascript_key');
// Login with JavaScript SDK
function kakaoLogin() {
Kakao.Auth.authorize({
redirectUri: `${window.location.origin}/redirect`
});
}
// Call backend API endpoints
function REST_Call(path) {
fetch(window.location.origin + path)
.then(response => response.text())
.then(data => {
try {
const jsonData = JSON.parse(data);
console.log('API Response:', JSON.stringify(jsonData, null, 2));
// Display in textarea or handle response
document.getElementById('contents').value = JSON.stringify(jsonData, null, 2);
} catch (e) {
console.log('Text Response:', data);
document.getElementById('contents').value = data;
}
})
.catch(error => {
console.error('Fetch error:', error);
});
}
// Complete HTML implementation:
//
//
//
//
//
//
```
--------------------------------
### User Profile Retrieval API
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Retrieves the authenticated user's profile information from Kakao, including user ID, nickname, profile image, and other account details.
```APIDOC
## GET /profile
### Description
Retrieves the authenticated user's profile information from Kakao, including user ID, nickname, profile image, and other account details.
### Method
GET
### Endpoint
/profile
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
fetch('http://localhost:4000/profile')
.then(response => response.json())
.then(data => console.log(data.kakao_account.profile.nickname))
.catch(error => console.error('Error:', error));
```
### Response
#### Success Response (200)
Returns the user's profile information.
#### Response Example
```json
{
"id": 123456789,
"connected_at": "2022-04-11T01:45:28Z",
"kakao_account": {
"profile_nickname_needs_agreement": false,
"profile_image_needs_agreement": false,
"profile": {
"nickname": "홍길동",
"thumbnail_image_url": "http://k.kakaocdn.net/...jpg",
"profile_image_url": "http://k.kakaocdn.net/...jpg",
"is_default_image": false
}
}
}
```
### Error Handling
- Requires a valid `access_token` in the session (`req.session.key`).
- If the token is invalid or expired, an error response from Kakao will be returned.
```
--------------------------------
### Send Message to Self
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Sends a message to the authenticated user's own Kakao Talk account using a customizable message template with text content and web links.
```APIDOC
## POST /message
### Description
Sends a message to the authenticated user's own Kakao Talk account using a customizable message template with text content and web links.
### Method
POST
### Endpoint
/message
### Parameters
#### Query Parameters
None
#### Request Body
- **template_object** (string) - JSON string representing the message template object. (Required)
### Request Example
```javascript
// GET /message
const message_template = {
object_type: 'text',
text: 'Hello, world!',
link: {
web_url: 'https://developers.kakao.com',
mobile_web_url: 'https://developers.kakao.com'
}
};
app.get('/message', async function (req, res) {
const uri = 'https://kapi.kakao.com/v2/api/talk/memo/default/send';
const param = qs.stringify({
template_object: JSON.stringify(message_template)
});
const header = {
'content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, param, header);
res.send(rtn);
});
```
### Response
#### Success Response (200)
- **result_code** (integer) - Indicates the result of the operation. 0 for success.
#### Response Example
```json
{
"result_code": 0
}
```
```
--------------------------------
### OAuth Authorization Endpoint
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Initiates the Kakao OAuth 2.0 authorization flow by redirecting users to Kakao's authorization server. Supports optional scope parameters to request additional permissions.
```APIDOC
## GET /authorize
### Description
Initiates the Kakao OAuth 2.0 authorization flow by redirecting users to Kakao's authorization server. Supports optional scope parameters to request additional permissions such as friend list access and message sending capabilities.
### Method
GET
### Endpoint
/authorize
### Query Parameters
- **scope** (string) - Optional - Comma-separated list of scopes to request (e.g., `friends,talk_message`).
### Request Example
Navigate to `http://localhost:4000/authorize?scope=friends,talk_message`
### Response
Redirects the user to the Kakao authorization page.
### Response Example
(None - this is a redirect endpoint)
### Error Handling
- If `scope` is not provided, a basic login flow is initiated.
- Ensure `client_id` and `redirect_uri` are correctly configured.
```
--------------------------------
### Logout
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Logs out the user from Kakao by invalidating the access token while maintaining the app connection. The user remains connected to the app but must re-authenticate to use API features.
```APIDOC
## POST /logout
### Description
Logs out the user from Kakao by invalidating the access token while maintaining the app connection. The user remains connected to the app but must re-authenticate to use API features.
### Method
POST
### Endpoint
/logout
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// GET /logout
app.get('/logout', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/user/logout';
const header = {
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, null, header);
req.session.destroy();
res.send(rtn);
});
```
### Response
#### Success Response (200)
- **id** (integer) - The ID of the logged-out user.
#### Response Example
```json
{
"id": 123456789
}
```
```
--------------------------------
### Retrieve Kakao User Profile (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Fetches the authenticated user's profile information from Kakao's API, including ID, nickname, and profile image. It requires a valid access token stored in the session. The response contains details about the user's Kakao account.
```javascript
// GET /profile
app.get('/profile', async function (req, res) {
const uri = 'https://kapi.kakao.com/v2/user/me';
const param = {};
const header = {
'content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, param, header);
res.send(rtn);
});
// Expected response:
// {
// "id": 123456789,
// "connected_at": "2022-04-11T01:45:28Z",
// "kakao_account": {
// "profile_nickname_needs_agreement": false,
// "profile_image_needs_agreement": false,
// "profile": {
// "nickname": "홍길동",
// "thumbnail_image_url": "http://k.kakaocdn.net/...jpg",
// "profile_image_url": "http://k.kakaocdn.net/...jpg",
// "is_default_image": false
// }
// }
// }
// Usage with fetch from frontend:
// fetch('http://localhost:4000/profile')
// .then(response => response.json())
// .then(data => console.log(data.kakao_account.profile.nickname))
// .catch(error => console.error('Error:', error));
```
--------------------------------
### Fetch Kakao Talk Friends List (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Retrieves the authenticated user's Kakao Talk friends list. This requires the 'friends' scope to be granted during authorization. The API endpoint is 'https://kapi.kakao.com/v1/api/talk/friends'.
```javascript
// GET /friends
app.get('/friends', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/api/talk/friends';
const param = null;
const header = {
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('GET', uri, param, header);
res.send(rtn);
});
// Expected response:
// {
// "elements": [
// {
// "uuid": "abcd-efgh-ijkl-mnop",
// "id": 987654321,
// "profile_nickname": "친구1",
// "profile_thumbnail_image": "http://k.kakaocdn.net/...jpg",
// "favorite": false
// },
// {
// "uuid": "qrst-uvwx-yzab-cdef",
// "id": 123456789,
// "profile_nickname": "친구2",
// "profile_thumbnail_image": "http://k.kakaocdn.net/...jpg",
// "favorite": true
// }
// ],
// "total_count": 2,
// "favorite_count": 1
// }
// Usage:
fetch('http://localhost:4000/friends')
.then(response => response.json())
.then(data => {
data.elements.forEach(friend => {
console.log(`${friend.profile_nickname} (${friend.uuid})`);
});
});
```
--------------------------------
### Send Kakao Talk Message to Friends (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Sends a message to specified friends using their UUIDs. This function requires both 'friends' and 'talk_message' scope permissions. The API endpoint is 'https://kapi.kakao.com/v1/api/talk/friends/message/default/send'.
```javascript
// GET /friend-message?uuid="abcd-efgh-ijkl-mnop"
app.get('/friend-message', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/api/talk/friends/message/default/send';
const { uuid } = req.query;
const param = qs.stringify({
receiver_uuids: `[${uuid}]`,
template_object: JSON.stringify(message_template)
});
const header = {
'content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, param, header);
res.send(rtn);
});
// Expected response:
// {
// "successful_receiver_uuids": ["abcd-efgh-ijkl-mnop"]
// }
// Send to multiple friends:
const multipleUUIDs = '"uuid1","uuid2","uuid3"';
fetch(`http://localhost:4000/friend-message?uuid=${encodeURIComponent(multipleUUIDs)}`)
.then(response => response.json())
.then(data => {
console.log('Successfully sent to:', data.successful_receiver_uuids);
});
// Usage with curl:
// curl -X GET "http://localhost:4000/friend-message?uuid=%22abcd-efgh-ijkl-mnop%22" \
// -H "Cookie: connect.sid=your_session_id"
```
--------------------------------
### Logout from Kakao (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Logs out the user from Kakao by invalidating the access token. This action maintains the app connection but requires re-authentication for API usage. The API endpoint is 'https://kapi.kakao.com/v1/user/logout'.
```javascript
// GET /logout
app.get('/logout', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/user/logout';
const header = {
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, null, header);
req.session.destroy();
res.send(rtn);
});
// Expected response:
// {
// "id": 123456789
// }
// Usage:
fetch('http://localhost:4000/logout')
.then(response => response.json())
.then(data => {
console.log('Logged out user ID:', data.id);
// Redirect to login page or show login button
window.location.href = '/';
})
.catch(error => console.error('Logout failed:', error));
```
--------------------------------
### Send Kakao Talk Message to Self (Node.js)
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Sends a message to the authenticated user's own Kakao Talk account. It uses a customizable message template with text and optional web links. The API endpoint is 'https://kapi.kakao.com/v2/api/talk/memo/default/send'.
```javascript
// GET /message
const message_template = {
object_type: 'text',
text: 'Hello, world!',
link: {
web_url: 'https://developers.kakao.com',
mobile_web_url: 'https://developers.kakao.com'
}
};
app.get('/message', async function (req, res) {
const uri = 'https://kapi.kakao.com/v2/api/talk/memo/default/send';
const param = qs.stringify({
template_object: JSON.stringify(message_template)
});
const header = {
'content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, param, header);
res.send(rtn);
});
// Expected response:
// {
// "result_code": 0
// }
// Custom message template example:
const custom_template = {
object_type: 'text',
text: '안녕하세요! 카카오 메시지 테스트입니다.\n멀티라인 메시지도 가능합니다.',
link: {
web_url: 'https://example.com',
mobile_web_url: 'https://example.com'
},
button_title: '자세히 보기'
};
// Usage with curl:
// curl -X GET "http://localhost:4000/message" \
// -H "Cookie: connect.sid=your_session_id"
```
--------------------------------
### Unlink Kakao Account
Source: https://context7.com/kakao-tam/developers-node.js/llms.txt
Completely disconnects a user's Kakao account from the application. This action revokes permissions and cannot be undone. It requires user re-authorization to reconnect. The API call uses POST to '/v1/user/unlink' and expects a session key for authentication.
```javascript
// GET /unlink
app.get('/unlink', async function (req, res) {
const uri = 'https://kapi.kakao.com/v1/user/unlink';
const header = {
Authorization: 'Bearer ' + req.session.key
};
var rtn = await call('POST', uri, null, header);
req.session.destroy();
res.send(rtn);
});
// Expected response:
// {
// "id": 123456789
// }
// Usage with confirmation:
function unlinkAccount() {
if (confirm('정말로 연결을 끊으시겠습니까? 이 작업은 되돌릴 수 없습니다.')) {
fetch('http://localhost:4000/unlink')
.then(response => response.json())
.then(data => {
console.log('Unlinked user ID:', data.id);
alert('연결이 해제되었습니다.');
window.location.href = '/';
})
.catch(error => console.error('Unlink failed:', error));
}
}
// Usage with curl:
// curl -X GET "http://localhost:4000/unlink" \
// -H "Cookie: connect.sid=your_session_id"
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.