728x90

안드로이드 어플 사용자에게 PUSH 메시지를 발송하기 위해서는 PHP 서버에서 관련 코드를 구현해야 한다.

앱이 백그라운드에서 실행중이거나 앱이 죽어있을 때에도 동작하게 하려면 FCM API를 직접 호출해주는 방식을 사용해야 한다.


api url :: https://fcm.googleapis.com/fcm/send


https://console.firebase.google.com/ 에 접속한다.





서버키 4번을 복사해서 아래 코드에 붙여넣기를 한다.


=== fcmpush.php ====

 <?php
require_once 'dbconnect.php'; // db접속
//데이터베이스에 접속해서 토큰들을 가져와서 FCM에 발신요청
$sql = "select tokenID From member_data where LENGTH(tokenID)>63";
$result = mysqli_query($dbconn,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
    while ($row = mysqli_fetch_assoc($result)) {
        $tokens[] = $row['tokenID'];
    }
} else {
    echo 'There are no Transfer Datas';
    exit;
}

mysqli_close($dbconn);

$title = isset($_POST['title'])? $_POST['title'] : "PUSH TEST";
$message = isset($_POST['message'])? $_POST['message'] : "새글이 등록되었습니다";

$arr = array();
$arr['title'] = $title;
$arr['message'] = $message;

$message_status = Android_Push($tokens, $arr);
//echo $message_status;
// 푸시 전송 결과 반환.
$obj = json_decode($message_status);

// 푸시 전송시 성공 수량 반환.
$cnt = $obj->{"success"};

echo $cnt;

function Android_Push($tokens, $message) {
    $url = 'https://fcm.googleapis.com/fcm/send';
    $apiKey = "서버키";

    $fields = array('registration_ids' => $tokens,'data' => $message);
    $headers = array('Authorization:key='.$apiKey,'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;
}
?>


=== fcmsender.php 샘플 파일 ===

<!DOCTYPE html>
<head>
<title>FCM Sender</title>
    <meta charset="utf-8" />
</head>
<body>
    <form action="fcmpush.php" method="post">
        <table style="width:100;padding:0;margin:0px;border:none">
        <tr>
            <th style="width:20%">제목</th>
            <td style="width:80%"><input type="text" name="title" value="" style="width:100%"></td>
        </tr>
        <tr>
            <th>내용</th>
            <td>
            <textarea name="message" rows=5 cols=42></textarea>
            </td>
        </tr>
        <tr>
            <td colspan=2 style="text-align: center;"><input type="submit" value="Send Notification" /></td>
        </tr>
        </table>
    </form>
</body>
</html>


FCM PUSH PHP 서버 샘플 소스를 첨부한다.


FCM_Push_Sample.zip


블로그 이미지

Link2Me

,