-
Laravel + Push 푸시알림 (http v1 버전)Laravel 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'Laravel' 카테고리의 다른 글
laravel queue job test 하는법 (테스트) (0) 2024.06.16 API Validation (API 유효성 검사 하는법) #validation #유효성 #API (0) 2024.02.19 Laravel Mail 메일 locale 언어 설정 먹게하는법 #다국어 #locale #메일 #mail (1) 2023.12.06 laravel media library로 다른 사이트 이미지 활용법 (A사이트에서 B사이트 이미지 사용하기) (0) 2023.07.16 Laravel excel 001 -> 1처럼 0 사라질 때 처리법 (0) 2023.06.09