1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| <?php
namespace App\Services\Notifications;
use Google\Client as GoogleClient; use Illuminate\Support\Facades\Http;
class FCMService { protected string $projectId; protected string $accessToken; public function __construct() { $this->projectId = config('services.fcm.project_id'); $this->accessToken = $this->getAccessToken(); } public function send(string $token, array $notification, array $data = []): array { $message = [ 'message' => [ 'token' => $token, 'notification' => $notification, 'data' => $this->formatData($data), 'android' => [ 'notification' => [ 'click_action' => 'FLUTTER_NOTIFICATION_CLICK', 'sound' => 'default', ], ], 'apns' => [ 'payload' => [ 'aps' => [ 'sound' => 'default', 'badge' => 1, ], ], ], ], ]; $response = Http::withToken($this->accessToken) ->post("https://fcm.googleapis.com/v1/projects/{$this->projectId}/messages:send", $message); return $response->json(); } public function sendMultiple(array $tokens, array $notification, array $data = []): array { $results = []; foreach (array_chunk($tokens, 500) as $chunk) { $message = [ 'message' => [ 'notification' => $notification, 'data' => $this->formatData($data), ], ]; foreach ($chunk as $token) { $message['message']['token'] = $token; $results[] = $this->send($token, $notification, $data); } } return $results; } public function sendToTopic(string $topic, array $notification, array $data = []): array { $message = [ 'message' => [ 'topic' => $topic, 'notification' => $notification, 'data' => $this->formatData($data), ], ]; $response = Http::withToken($this->accessToken) ->post("https://fcm.googleapis.com/v1/projects/{$this->projectId}/messages:send", $message); return $response->json(); } public function subscribeToTopic(string $topic, array $tokens): array { $response = Http::withToken($this->accessToken) ->post("https://iid.googleapis.com/iid/v1:batchAdd", [ 'to' => "/topics/{$topic}", 'registration_tokens' => $tokens, ]); return $response->json(); } protected function getAccessToken(): string { $client = new GoogleClient(); $client->setAuthConfig(config('services.fcm.credentials')); $client->addScope('https://www.googleapis.com/auth/firebase.messaging'); return $client->fetchAccessTokenWithAssertion()['access_token']; } protected function formatData(array $data): array { return array_map('strval', $data); } }
|