Laravel
Laravel + Push 푸시알림 (http v1 버전)
짱구를왜말려?
2024. 6. 25. 10:58
반응형
SMALL
1. 앱개발자에게 키정보 담긴 .json 파일 받아서 프로젝트 루트에 놓기
FIREBASE_CREDENTIALS=./service-account-file.json
2. services.php에 firebase 설정 추가
"firebase" => [
"credentials" => env("FIREBASE_CREDENTIALS", ""),
],
3. Pusher 모델 생성
<?php
namespace App\Models;
use App\Enums\TypeAlarm;
use Firebase\JWT\JWT;
use http\Client;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Http;
class Pusher extends Model
{
public function sendNotification(Alarm $alarm)
{
$credentials = json_decode(file_get_contents(base_path(env('FIREBASE_CREDENTIALS'))), true);
$client = new Client();
$url = 'https://fcm.googleapis.com/v1/projects/' . $credentials['project_id'] . '/messages:send';
$response = $client->post($url, [
'headers' => [
'Authorization' => 'Bearer ' . $this->getAccessToken($credentials),
'Content-Type' => 'application/json',
],
'json' => [
'message' => [
'token' => $alram->user->push_token,
'notification' => [
'title' => 'Title',
'body' => 'Body',
],
'data' => [
'url' => 'https://example.com', // 클릭 시 이동할 URL
],
],
],
]);
if ($response->getStatusCode() == 200) {
return response()->json(['message' => 'Notification sent successfully'], 200);
} else {
return response()->json(['message' => 'Failed to send notification'], 500);
}
}
private function getAccessToken($credentials)
{
$client = new Client();
$response = $client->post('https://oauth2.googleapis.com/token', [
'json' => [
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $this->createJwt($credentials),
],
]);
$token = json_decode($response->getBody(), true);
return $token['access_token'];
}
private function createJwt($credentials)
{
$now = time();
$token = [
'iss' => $credentials['client_email'],
'sub' => $credentials['client_email'],
'aud' => 'https://oauth2.googleapis.com/token',
'iat' => $now,
'exp' => $now + 3600,
'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
];
return JWT::encode($token, $credentials['private_key'], 'RS256');
}
}
4. 활용하기
$pusher = new Pusher();
$pusher->sendNotification($model);
LIST