node.js로 “카카오 로그인, 카카오 카카오 친구목록 조회, 나에게 메시지 발송” 테스트 해볼 수 있는 간단한 예제입니다.
demo.zip (2.4 KB)
[실행방법]
- localhost 웹서버에 demo.html을 복사합니다.
- 내 애플리케이션 > 앱 설정 > 요약 정보 > "REST API 키"를 복사해서 demo.js 파일 client_id 변수에 설정합니다.
- 내 애플리케이션>제품 설정>카카오 로그인 > Redirect URI에 http://localhost:4000/redirect 주소를 설정합니다.
- node로 demo.js 를 localhost:4000으로 실행합니다.
[실행결과]
demo.js
const express = require('express');
const session = require('express-session');
const cors = require("cors");
const qs = require("qs");
const axios = require('axios');
const app = express();
const port = 4000;
app.use(session({
secret: 'your session secret',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
let corsOptions = {
origin: 'http://localhost',
credentials: true
}
app.use(cors(corsOptions));
const client_id = '여기에 REST_API_KEY를 입력하세요';
const redirect_uri = 'http://localhost:4000/redirect';
const token_uri = 'https://kauth.kakao.com/oauth/token';
const api_host = "https://kapi.kakao.com";
const client_secret = '';
app.get('/authorize', function (req, res) {
let { scope } = req.query;
var scopeParam = "";
if (scope) {
scopeParam = "&scope=" + scope;
}
res.status(302).redirect(`https://kauth.kakao.com/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code${scopeParam}`);
})
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', token_uri, param, header);
req.session.key = rtn.access_token;
res.status(302).redirect(`http://localhost/demo.html`);
})
app.get('/profile', async function (req, res) {
const uri = api_host + "/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);
})
app.get('/friends', async function (req, res) {
const uri = api_host + "/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);
})
app.get('/message', async function (req, res) {
const uri = api_host + "/v2/api/talk/memo/default/send";
const param = qs.stringify({
"template_object": '{'+
'"object_type": "text",'+
'"text": "텍스트 영역입니다. 최대 200자 표시 가능합니다.",'+
'"link": {'+
' "web_url": "https://developers.kakao.com",'+
' "mobile_web_url": "https://developers.kakao.com"'+
'},'+
'"button_title": "바로 확인"'+
'}'
});
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);
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
로그인에 관한 가이드 : 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