티스토리 뷰

[Android] C2DM 푸시 알림 구현하기 - PHP 서버 편 튜토리얼



PHP서버에서 C2DM을 이용해서 푸시를 하려면 curl을 이용하는 방법과 Zend 프레임워크를 이용하는 방법이 있다. 더 간단한 방법인 curl 을 이용해서 ClientLogin을 하고 메세지를 방법을 살펴보도록 하자.


C2DM 푸시를 보내는 순서는


  1. 구글 계정 인증 (이전에 C2DM에서 푸시를 보내는 계정으로 설정했던 계정)
  2. curl을 이용해서 메세지 전송


이렇게 이루어진다. 두 단계만 거치면 간단하게 전송이 가능하다.






0. C2DM 세팅 (클라이언트)

[안드로이드] C2DM(push notification) 구현하기 - 안드로이드(클라이언트) 편



1. google 계정 등록하는 함수 작성

function googleAuthenticate($username, $password, $source="Company-AppName-Version", $service="ac2dm") {



session_start();

if( isset($_SESSION['google_auth_id']) && $_SESSION['google_auth_id'] != null)

{

return $_SESSION['google_auth_id'];

}


// get an authorization token

$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");

$post_fields = "accountType=" . urlencode('HOSTED_OR_GOOGLE')

. "&Email=" . urlencode($username)

. "&Passwd=" . urlencode($password)

. "&source=" . urlencode($source)

. "&service=" . urlencode($service);

curl_setopt($ch, CURLOPT_HEADER, true);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


// for debugging the request

//curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging the request


$response = curl_exec($ch);


//var_dump(curl_getinfo($ch)); //for debugging the request

//var_dump($response);


curl_close($ch);


if (strpos($response, '200 OK') === false) {

return false;

}


// find the auth code

preg_match("/(Auth=)([\w|-]+)/", $response, $matches);


if (!$matches[2]) {

return false;

}


$_SESSION['google_auth_id'] = $matches[2];

return $matches[2];

}





2. curl을 이용해서 메세지를 보내는 함수 작성

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {


$headers = array('Authorization: GoogleLogin auth=' . $authCode);

$data = array(

            'registration_id' => $deviceRegistrationId, 

            'collapse_key' => $msgType, 

            'data.message' => $messageText //TODO Add more params with just simple data instead            

);


$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");

if ($headers)

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);



$response = curl_exec($ch);


curl_close($ch);


return $response;

}




3. 인증+메세지 보내는 함수 호출하기

: 이제 서버에서 필요한 작업을 하고나서 클라이언트한테 메세지를 보내면 된다.

: 아래는 직접 데이터베이스에서 사용자의 registration id를 가져와서 사용하는 예이다.

$authCode = googleAuthenticate($GOOGLE_ACCOUNT , $GOOGLE_ACCOUNT_PASSWORD);

$sql = "SELECT registration_id FROM Users WHERE UserID=$user_id";

$sqlstr = mysql_query($sql);

$deviceRegistrationId = "";

if ($row = mysql_fetch_array($sqlstr)) {

$deviceRegistrationId = $row['registration_id'];

}

$msgType = "Got it!";

$messageText = "Package has arrived!";

sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText);






4. 클라이언트에서 해당 메세지 처리하기

[안드로이드] C2DM(push notification) 구현하기 - 안드로이드(클라이언트) 편


: 위의 링크에 handleMessage 안에서 처리하면 된다.

: 위의 함수를 쓰는 경우 data.message 에서 data.<key> 의 형식으로 추가 데이터를 추가하면 되고, 클라이언트에서는 intent.getExtras.getString(<key>) 와 같은 식으로 가져올 수 있다.



끝.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함