맛집 여행 캠핑 일상 생활

서버에서 PHP로 푸쉬(GCM,APNS) 메시지 보내기 본문

안드로이드

서버에서 PHP로 푸쉬(GCM,APNS) 메시지 보내기

영은파더♥ 2016. 3. 10. 12:04

서버사이드에서 안드로이드(GCM) 및 아이폰(APNS) PHP PUSH 메시지 보내기


▶ 안드로이드 GCM (C2DM에서 변경됨)

<?php

// $regId 는 1건 및 배열(1000건 이하)도 허용된다. 천건이 넘으면 분할해서 호출하자.

// $regId 는 푸쉬를 받을 단말기의 GCMRegistrar.getRegistrationId(this); 로 받은 등록Id이다.

function gcm_send($regId, $sendMsg) {

$sendMsg = urldecode($sendMsg);

$headers = array(

'Content-Type:application/json',

'Authorization:key=사용자인증정보API키'

);


$arr = array();

$arr['data'] = array();

$arr['data']['msg'] = $sendMsg;

$arr['registration_ids'] = array();

if(is_array($regId)) {

$to_cnt = count($regId);

for($i=0; $i<$to_cnt; $i++) {

$arr['registration_ids'][$i] = $regId[$i];

}

}

else {

$arr['registration_ids'][0] = $regId;

}


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arr));

$result = curl_exec($ch);

curl_close($ch);

return $result;

}

?>


▶ 아이폰 APNS

<?php

// $regId 1건만 된다.

function apns_send($regId, $sendMsg) {

$sendMsg = urldecode($sendMsg);

if(strlen($sendMsg) > 108) { // 안드로이드와 달리 자릿수 제한이 짧다. $payload 바이트가 128Byte가 안되게 해주자.

$sendMsg = substr($sendMsg, 0, 105);

$sendMsg .= "...";

}

// 아래의 배열은 적절히 맞게 수정하면 된다.

$payload = array();

$payload['aps'] = array('alert' => 'Notification');

$payload['e'] = array('m' => $sendMsg);

$push = json_encode($payload);

//$apnsCert = 'Cert 파일이 있는 디렉토리/developCert.pem'; // 개발용 cert 파일

$apnsCert = 'Cert 파일이 있는 디렉토리/productCert.pem'; // 실제 사용 cert 파일

$streamContext = stream_context_create();

stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

//$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext); // 개발용 코드

$apns = stream_socket_client('ssl://gateway.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext); // 실제 사용 코드

if (!$apns) {

return "Failed to connect $error $errorString";

}

$apnsMessage = chr(0).chr(0).chr(32).@pack('H*', str_replace(' ', '', "$regId")).chr(0).chr(strlen($push)).$push;

$writeResult = fwrite($apns, $apnsMessage);

@socket_close($apns);

fclose($apns);


return $writeResult;

}

?>

멀티로 보내기는 적절히 구현해 주어야 한다.


Trackback : | Comments :