1. 서비스 계정 JSON 파일 받기
- Firebase Console에서 설정 > 서비스 계정을 엽니다.
- 새 비공개 키 생성을 클릭한 다음 키 생성을 클릭하여 확인합니다.
- 키가 들어 있는 JSON 파일을 안전하게 저장합니다.
2. 토큰 발급 받기
$url = 'https://fcm.googleapis.com/v1/projects/프로젝트이름/messages:send';
putenv('GOOGLE_APPLICATION_CREDENTIALS=서비스 계정 JSON 파일 경로');
$scope = 'https://www.googleapis.com/auth/firebase.messaging';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes($scope);
$auth_key = $client->fetchAccessTokenWithAssertion();
echo $auth_key['access_token']; //토큰 발급 성공!!
3. 메시지 보내기
$token = $auth_key['access_token']; //위에서 받은 토큰
$headers = array(
'Authorization: Bearer '. $token,
'Content-Type: application/json'
);
$fields = array(
'token' => 메시지 받을 기기의 토큰값,
'notification' => array('title'=> 알림 제목,'body'=> 알림내용)
$message_json = array('message'=>$fields);
self::sendAsync($url, $headers, $message_json);
function sendAsync($url, $headers, $fields){
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
//create the multiple cURL handle
$mh = curl_multi_init();
//add the two handles
curl_multi_add_handle($mh,$ch);
//execute the multi handle
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);
//close the handles
curl_multi_remove_handle($mh, $ch);
curl_multi_close($mh);
}