PHP

39. PHP FCM 메세지 PHP로 보내기

drizzle0925 2021. 9. 14. 18:01
728x90

Device token을 이용해서 개별적으로 알람(notification)을 보낼때 필요할 것 같아서 찾아서 정리했습니다.

 

server_key

firebase > 프로젝트 선택 > 프로젝트 개요 > 톱니바퀴 > 프로젝트 설정 > 클라우드 메시징

 

빨간색으로 체크한 부분을 복사하시면 됩니다.

 

device_token

아래 게시글을 참고 부탁드립니다.

https://like-a-drizzle.tistory.com/235

 

10. [안드로이드/java] 안드로이드 디바이스 토큰값 확인하기

FCM으로 push 알람 테스트를 하려는데 디바이스 토큰값이 필요해서 한참을 찾다가 좌절할 찰나에 한 코드를 발견했습니다. (지옥과 같은 시간이였다...) 디바이스 토큰 가져오기 프로젝트를 열어

like-a-drizzle.tistory.com

 

 

sample code 1

server_key와 device_token을 알았다면 아래 스크립트에 넣어주기만 하면됩니다.

<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "device_token";
$serverKey = 'server_key';
$title = "Notification title"; // 알람 타이틀
$body = "Notification content"; // 알람 내용
$notification = array('title' => $title, 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=' . $serverKey;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Send the request 
$response = curl_exec($ch); 
curl_close($ch); 

//Close request 
if (false) {
    die('FCM Send Error: ' . curl_error($ch));
}
?>

 

 

sample code 2

<?php

$tokens = array(); // device_token 값을 넣을 배열
$tokens[0] = 'token1';
$tokens[1] = 'token2';

// 헤더 부분
$headers = array(
	'Content-Type:application/json',
	'Authorization:key=[server_key]'
);


// 발송 내용
$arr   = array();
$arr['notification'] = array();
$arr['notification']['title'] = '제목'; // 알람 제목
$arr['notification']['body'] = '내용'; // 알람 내용
$arr['notification']['sound'] = 'default';
$arr['notification']['badge'] = '1';
$arr['notification']['tag'] = '1';  // 개별로 보낼때 이름을 다르게
$arr['notification']['priority'] = 'high';  // 안드로이드 8 이상 추가
$arr['notification']['content_available'] = true;  // 안드로이드 8 이상 추가

$arr['data'] = array();
$arr['data']['message'] = '내용'; // 내부에서 받을 시

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

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($arr));
$response = curl_exec($ch);
curl_close($ch);

// 푸쉬 전송에 대한 결과를 수신
$obj = json_decode($response);

// 전송 성공 및 실패한 갯수
$suc_cnt = $obj->success;
$fail_cnt = $obj->failure;	

echo $suc_cnt.' --- '.$fail_cnt;

?>
728x90