강좌게시판

제목 FCM(FirebaseCloudMessage) 간단 구현 (부제 chatGPT에게 물어보았다)
글쓴이 kaido 작성시각 2024/05/09 17:08:42
댓글 : 0 추천 : 0 스크랩 : 0 조회수 : 818   RSS

안녕하세요 

최근 프롬프트로 AI  갈구는 취미(?)에 눈을 뜬  kaido 입니다.

 

우선 컴포저로 가볍게 패키지를 설치 합니다.

composer require kreait/firebase-php

[출처 https://packagist.org/packages/kreait/firebase-php ]

 

그럼 여러분의 php 버전에 맞추어서 설치가 완료 될것입니다.

 

컴포저가 무엇? 난 설치 안되었는데? 하시는 분들은 https://getcomposer.org/ 방문하여 설치 하거나

리룩스 환경 상에서 curl 과 php가 설치 되어있다면 간단히 설치 가능합니다.

curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

 

 

그리고 chatGPT 에게 여러번 문의 결과 에러 없는 소스를 획득 !

 

<?php

require 'vendor/autoload.php'; // Load Composer's autoloader

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\MulticastSendReport;

// Initialize Firebase
$factory = (new Factory)->withServiceAccount('/path/to/serviceAccountKey.json');

// Get an instance of the Messaging service
$messaging = $factory->createMessaging();

// Create an array of messages to send
$messages = [
    ['token' => 'device_token_1', 'title' => 'Title 1', 'body' => 'Body 1', 'link_url' => '/page1'],
    ['token' => 'device_token_2', 'title' => 'Title 2', 'body' => 'Body 2', 'link_url' => '/page2'],
    // Add more messages as needed
];

// Create an array of CloudMessage instances
$cloudMessages = [];
foreach ($messages as $messageData) {
    $cloudMessages[] = CloudMessage::withTarget('token', $messageData['token'])
        ->withData([
            'title' => $messageData['title'],
            'body' => $messageData['body'],
            'link_url' => $messageData['link_url'] // Include link_url in the message data
        ]);
}

// Send the messages to all devices
$sendReport = $messaging->sendAll($cloudMessages);

// Check for errors
if ($sendReport->hasFailures()) {
    foreach ($sendReport->failures() as $index => $failure) {
        $error = $failure->error();
        echo "Failed to send message to device with index $index: $error\n";
    }
} else {
    echo "Messages sent successfully to all devices\n";
}

 

 

serviceAccountKey.json 파일은 구글 파이어베이스에 접속해서 프로젝트를 생성 하면  계정정보가 담긴 json 파일을 하나 던져줍니다.

해당 파일을 서버 상에 올려놓고 파일 path에 맞춰서 넣어주세요.

 

파라메터 설명

title    알림의 제목 [상단]

body  알림의 본문 [접힌거 펼치면 나오는 부분]

link_url 터치시 이동할 URL 주소 

 

이렇게 데이터를 맞춰서 실행 하면 끝 !

FCM 구현을 간단히 하고 싶으신 분들은 참고해 보세요.

 

해당 패키지 메뉴얼  https://firebase-php.readthedocs.io/en/7.10.0/index.html 

 

 이전글 Responsive-Grid-System Demo (2)

댓글

없음