개발 공부 기록/04. Android

[PHP] php에서 fcm 으로 push 메시지 보내기

박세류 2020. 11. 27. 13:34

1. 파이어베이스 서버 키값 받아오기

 

파이어베이스 로그인 -> 좌측상단 설정버튼 -> 클라우드메시지 -> 서버 키 복사해두기

 

 

2. 핸드폰 토근값 받아오기

class MyFirebaseMessageingService : FirebaseMessagingService() {

    private val TAG = "testFireBase"

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, "token : $token")

    }

 

하고 실행 시 LogCat에 토큰값이 찍힐텐데, 복사해두자

 

3. php 파일 작성

<?php 
    function send_notification($tokens, $message) {
        $url = 'https://fcm.googleapis.com/fcm/send';
        if ($message) {
            $fields = array (
                'notification' => array ('body' => $message['body'], 'title' => $message['title'])
            );
        }
        if(is_array($tokens)) {
            $fields['registration_ids'] = $tokens;
        } else {
            $fields['to'] = $tokens;
        }
        $fields['priority'] = "high";
        $FCM_SERVER_KEY = "1번의 서버 키 입력"; 
        $headers = array(
            'Authorization:key =' . $FCM_SERVER_KEY,
            'Content-Type: application/json'
        );
     
        $ch = curl_init();
        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_SSL_VERIFYHOST, 0);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);           
        if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);

        return $result;
    }
    
    $tokens = "2번의 토근값 입력";
    $message = array(
        "title"   => "메시지제목", 
        "body" => "메시지내용", 
    );
    send_notification($tokens, $message);
?>



  

 

4. 실행해서 확인해보자

주소창 http://localhost/경로/3번php파일.php 입력

핸드폰, 에뮬에

 

다음과 같이 알람이 온다면 성공이다.

반응형