SERVER/LARAVEL & PHP

laravel fcm push 보내기

나나나나나나나ㅏ나난ㄴ나ㅏ나나 2020. 1. 23. 11:23
728x90

진짜 어제 하루종일 삽질하다가 오늘 사수분덕분에 30분만에 해결해서 너무 슬퍼서 작성중... 8ㅅ8

 

서버 :  laravel php

클라이언트 : phonegap

cordova: 9.0

anrdroid platform 8.0

 

사용하고 있는 fcm plugin : cordova-plugin-firebase-messanging

https://www.npmjs.com/package/cordova-plugin-firebase-messaging

 

cordova-plugin-firebase-messaging

Cordova plugin for Firebase Messaging

www.npmjs.com

 

나는 이때까지 계속 어디서 찾은 laravel에서 curl을 이용한 방법으로 push를 보내고있었다

$url = 'https://fcm.googleapis.com/fcm/send';
if(Input::get('user_type')==1){
    /* 전체 전송 */
    $member_info = $memberModel->selectDefault()->whereNotNull('fcm_token')->get();
    foreach($member_info as $member) {
        array_push($token, $member->fcm_token);
    }

}else{
    /* 특정유저에게 전송 */
    $select_member_info = $memberModel->selectDefault()->where('member_no', '=', Input::get('member_no'))->get()[0];
    if($select_member_info->fcm_token != null){
        array_push($token, $select_member_info->fcm_token);
    }
}

if(count($token)<=0){
    $commonLib->alert("push 메세지를 보낼 수 없습니다.");
    $commonLib->reload();

    return 0;
}
$fields = array(
    'registration_ids' => $token,
    'data' => array(
        'title' => Input::get('fcm_title'),
        'body' => Input::get('fcm_content')
    )
);
$header = array(
    'Content-Type:application/json',
    'Authorization: key='. 'server_key'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
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);

return $result;

* 누가 볼지는 모르겠지만 혹시 보고 도움이 될수도있어서 올립니다 *

 

이렇게 했을때 구글에서는 잘 됬다고 메세지를 return 했다

하지만 핸드폰은 아주 잠잠했고 push는 오지 않았다

심지어 console로 찍어서 확인 했을때 도착했다고 했지만 push 알림은 오지 않았다.

 

그래서 왜 안되는지 이유를 찾아찾아 찾아서 위에 상단에 있는 cordova plugin 사이트에서 진짜 영어도 못하는데 하나하나 다 보면서 삽질을 하다가 오늘 출근해서 사수분께 SOS를 청한 결과!

내가 문제였다 🤦🏻‍♀️🤦🏻‍♀️🤦🏻‍♀️🤦🏻‍♀️🤦🏻‍♀️🤦🏻‍♀️🤦🏻‍♀️🤦🏻‍♀️

 

내가 직접 짠게 아니라 누가 만든 github를 보고 수정하였다

https://github.com/brozot/Laravel-FCM

 

brozot/Laravel-FCM

Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud Messaging (FCM). - brozot/Laravel-FCM

github.com

 

너무나도 착한사람ㅠㅠ 복받으실꺼예요 brozot씨ㅠㅠㅠㅠㅠㅠ

위에 링크에 나온 순서대로 하면 되지만 나처럼 영어 울렁증인 사람들을 위해

 

1. 먼저 composer 모듈부터 설치

composer require brozot/laravel-fcm

2. config/app.php에 들어가서 추가!

'providers' => [
	// ...

	LaravelFCM\FCMServiceProvider::class,
]

'aliases' => [
	...
	'FCM'      => LaravelFCM\Facades\FCM::class,
	'FCMGroup' => LaravelFCM\Facades\FCMGroup::class, // Optional
]

3. 변경된 사항들을 적용해주어야 하기때문에 터미널에 입력하자

php artisan vendor:publish --provider="LaravelFCM\FCMServiceProvider"

4. env 파일에 구글 firebase에서 확인할 수 있는 server key와 sender_id를 입력해주자

(이건 console.firebase에서 setting에서 확인 할 수있다)

FCM_SERVER_KEY=my_secret_server_key
FCM_SENDER_ID=my_secret_sender_id

5. controller단에 선언해주기 

use LaravelFCM\Message\OptionsBuilder;
use LaravelFCM\Message\PayloadDataBuilder;
use LaravelFCM\Message\PayloadNotificationBuilder;
use FCM;

$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);

$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
				    ->setSound('default');

$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => 'my_data']);

$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();

// You must change it to get your tokens
$tokens = MYDATABASE::pluck('fcm_token')->toArray();

$downstreamResponse = FCM::sendTo($tokens, $option, $notification, $data);

$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();

// return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();

// return Array (key : oldToken, value : new token - you must change the token in your database)
$downstreamResponse->tokensToModify();

// return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();

// return Array (key:token, value:error) - in production you should remove from your database the tokens present in this array
$downstreamResponse->tokensWithError();

그 결과!! 진행중인 프로젝트를 공개하면 안되서 사진으로 올릴수는 없지만 알람이 아주 잘오는걸 볼 수있다 ☺️ 

 

자세한 설명이나 제대로된 document는 상단의 링크로 들어가서 보면 된다

나를 비롯한 push 알림 기능을 구현하고 있는 사람들에게 모두모두 도움이 되었으면 좋겠다 🙇🏻‍♀️

 

항상 글을 마칠때 어떻게 끝내야되나 고민하는데 오늘은 사수분을 찬양하면서 글을 마쳐야겠다

 사수분 짱짱 당신덕분에 오늘도 해결합니다💃🏼

 

728x90