카카오톡 메시지 - REST API 를 통한 나에게 메시지 보내기 (텍스트 방식으로 보내기) for PHP
카카오톡 메시지 - REST API 를 통한 나에게 메시지 보내기 (텍스트 방식으로 보내기) for PHP
REDINFO
몇달 전 2023-07-29 21:50:17

카카오톡 메시지 API는 실제 카카오톡으로 메시지를 보낼 수 있는 API이며 나에게 메시지 보내기와 등록된 친구에게 최대(5명)까지 메시지를 보낼 수 있다. 이번편에서는 간단하게나마 PHP에서 REST API 를 이용한 나에게 메시지 보내기에 대해 알아보도록 하자. 

 

우선 이번 예제에서 사용된 샘플 파일은 아래와 같이 총 5개의 파일로 구성되어 있다. 

config.php 카카오 API를 이용하기 위한 기본 설정을 정의 
index.php 카카오 메시지 UI
oauth.php 카카오 메시지에 필요한 로그인 인증 토큰 발행 
send.php 카카오 메시지를 전송
callback.php 카카오 메시지를 받고 바로가기 클릭 시 보여지는 화면 

 

예제는 최대한 간단하게 구성하였으며 나에게 메시지 보내기 절차는 아래와 같이 이루어진다. 

  1. 로그인을 통해 인증 토큰 발급 
  2. 인증토큰을 세션에 저장 
  3. 메시지 보내기 
  4. 콜백 URL을 통해  환영 메시지 확인 

 

config.php
<?php 

session_start();

// 카카오 앱 키
define('KAKAO_JAVASCRIPT', ''); // 자바스크립트 키
define('KAKAO_REST_API', ''); // REST API 키 
define('KAKAO_CLIENT_SECRIET', ''); // 토큰 발급 시, 보안을 강화하기 위해 추가 확인하는 코드 > [내 애플리케이션] > [보안]에서 설정 가능

// 카카오 부가설정: 카카오 로그인 > Redirect URI에 설정 필요
define('KAKAO_REDIRECT_URI', ''); // 카카오 로그인 인증 후 이동될 URI

// 카카오 메시지클릭 후 이동될 URL
define('KAKAO_CALLBACK_URL', '');

$requestOauthUrl = 'https://kauth.kakao.com/oauth/authorize?response_type=code&client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}';
$requestOauthUrl = str_replace(array('{REST_API_KEY}','{REDIRECT_URI}'), array(KAKAO_JAVASCRIPT,KAKAO_REDIRECT_URI), $requestOauthUrl);

// 디버깅 함수 
function debug($arr = array()){
	echo '<pre>';
	print_r($arr);
	echo '</pre>';
}

 

index.php
<?php
include __DIR__."/config.php"; // 카카오 설정 변수

$kakaoData = array();
if( !empty($_SESSION['kakaoData'])){
	$kakaoData = $_SESSION['kakaoData'];
}

if( !empty($kakaoData['rst']) && $kakaoData['rst'] == 'fail' ){
	echo '<h3>응답에러: '.$kakaoData['msg'].'</h3>';
}

// 엑세스토큰 만료시간 체크 
if( $kakaoData['tokenData']['expires_time'] < time()){
	$kakaoData = array();
}

// 액세스 토큰 체크 하여 처리
if(empty($kakaoData['tokenData']['access_token'])){
	echo '<a href="'.$requestOauthUrl.'">엑세스토큰 요청</a>';
	exit;
}

?>
<script src="//code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<form id="form" action="send.php" onsubmit="return send()">
<h1>나에게 카카오 메시지 보내기(텍스트)</h1>
<p><textarea id="msg" name="msg" placeholder="메시지를 입력해주세요" style="width:400px; height:100px; resize:none;"></textarea></p>
<p><input type="submit" value="전송"></p>
<script>
	var authSend = true;
	function send(){
		if( authSend !== true){ return false; }
		var $form = $('#form');
		var msg = $form.find('#msg').val();
		if( !msg){ alert('메시지를 입력해주세요.'); return false;}

		authSend = false;
		$.ajax({url:$form.attr('action'), data: {msg: msg}, dataType:'json', type:'post'})
		.done(function(e){
			console.log(e);
			alert(e.msg);
			if(e.rst == 'success'){
				$form.find('#msg').val('');
			}
		})
		.fail(function(e){console.log(e.responseText); alert('시스템 오류'); })
		.always(function(e){ authSend = true;})
		return false;
	}
</script>

 

oauth.php
<?php 
include __DIR__."/config.php"; // 카카오 설정 변수

$response = array();

if( !empty($_SESSION['kakaoData'])) unset($_SESSION['kakaoData']);

try{
	if(empty($_GET['code'])){ throw new Exception("`code` 누락");}


	$url = 'https://kauth.kakao.com/oauth/token';
	$headers = array('Content-Type: application/x-www-form-urlencoded');
	$body = array(
		'grant_type'=>'authorization_code', // 고정
		'client_id'=>KAKAO_REST_API, // REST API 키
		'redirect_uri'=>KAKAO_REDIRECT_URI, // 리다렉트 URI
		'code'=>$_GET['code'], // 인가코드
		'client_secret'=>KAKAO_CLIENT_SECRIET, // 스크릿키 (카카오 앱에서  사용경우에만 전송)
	);

	// CURL 을통한 통신
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($body)); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	$res = curl_exec($ch); 
	curl_close($ch); 	

	// 최종결과를 로드
	$tokenData = json_decode($res,true);
	if( empty($tokenData['access_token'])){  throw new Exception("엑세스 토큰 요청 실패", 1);}

	// 응답용 토큰데이터를 처리
	$response['tokenData'] = array(
		'access_token'=>$tokenData['access_token'],
		'expires_time'=>$tokenData['expires_in']+time(),
		'refresh_token'=>$tokenData['refresh_token'],
		'refresh_token_expires_time'=>$tokenData['refresh_token_expires_in']+time(),
	);
	$response['rst'] = 'success';

}
catch(Exception $e){
	$response['rst'] = 'fail';
	$response['msg'] = $e->getMessage().' (Line: '.$e->getLine().')';
}
$_SESSION['kakaoData'] = $response;
die(header('Location: index.php'));

 

send.php
<?php 
include __DIR__."/config.php"; // 카카오 설정 변수

$response = array();

$kakaoData = array();
if( !empty($_SESSION['kakaoData'])){
	$kakaoData = $_SESSION['kakaoData'];
}

// 엑세스토큰 만료시간 체크 
if( $kakaoData['tokenData']['expires_time'] < time()){
	$kakaoData = array();
}

try{
	if(empty($kakaoData['tokenData'])){ throw new Exception("`tokenData` 누락");}
	if( empty($_POST['msg'])){ throw new Exception("메시지를 입력해주세요."); }

	$msg = $_POST['msg'];

	$url = 'https://kapi.kakao.com/v2/api/talk/memo/default/send';
	$headers = array(
		'Content-Type: application/x-www-form-urlencoded',
		'Authorization: Bearer '.$kakaoData['tokenData']['access_token']
	);

	$template_object = array(
			'object_type'=>'text',
			'text'=>$msg,
			'link'=>array(
				'web_url'=>KAKAO_CALLBACK_URL.'?tokenData='.bin2hex(serialize($kakaoData['tokenData'])),
				'mobile_web_url'=>KAKAO_CALLBACK_URL.'?tokenData='.bin2hex(serialize($kakaoData['tokenData'])),
			),
			'button_title'=>'바로가기',
	);

	$body = array(
		'template_object'=>json_encode($template_object)
	);

	// CURL 을통한 통신
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL, $url); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_POST, 1); 	
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body)); 
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	$res = curl_exec($ch); 
	curl_close($ch); 	

	// 최종결과를 로드
	$tokenData = json_decode($res,true);

	if( !isset($tokenData['result_code']) || $tokenData['result_code'] !== 0){
		throw new Exception("메시지 전송에 실패하였습니다."); 
	}

	$response['rst'] = 'success';
	$response['template_object'] = $template_object;
	$response['msg'] = '나에게 메시지 전송이 성공하였습니다.(카카오톡에서 확인해주세요.)';
}
catch(Exception $e){
	$response['rst'] = 'fail';
	$response['msg'] = $e->getMessage().' (Line: '.$e->getLine().')';
}

die(json_encode($response));

 

callback.php
<?php 
	include __DIR__."/config.php"; // 카카오 설정 변수

	$tokenData = array();
	if(!empty($_GET['tokenData'])){
		$tokenData = unserialize(hex2bin($_GET['tokenData']));
	}

	if( empty($tokenData['access_token'])){ die('엑세스 토큰이 없습니다.'); }
	if( empty($tokenData['expires_time']) || time() > $tokenData['expires_time'] ){ die('엑세스 토큰이 만료되었습니다.'); }

	echo '<h1>환영합니다!</h1>';
	echo '<h2>엑세스 토큰 만료일['.date('Y-m-d H:i:s',$tokenData['expires_time']).']</h2>';

 

최종적으로 인증 성공 후 메시지를 받아서 카카오톡에서 확인이 가능하며 메시지의 바로가기 클릭시에는 아래와 같은 화면을 볼 수 있다. 

 

이 포스트글이 도움이 되었나요?
2
카테고리 연관글

Comment

댓글작성

0(500) | 1(30)