Skip to content

Commit 00df4d9

Browse files
authored
Merge pull request #10 from CrazyFreeMan/master
Add send FCM to topic
2 parents 74103ce + c044720 commit 00df4d9

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

readme.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,17 @@ fcm()
6565
->send();
6666
```
6767

68+
If You want to send a FCM to topic, use method toTopic($topic) instead to() :
69+
```php
70+
fcm()
71+
->toTopic($topic) // $topic must an string (topic name)
72+
->notification([
73+
'title' => 'Test FCM',
74+
'body' => 'This is a test of FCM',
75+
])
76+
->send();
77+
```
78+
6879
If You want to send a FCM with just notification parameter,this is an example of usage sending a FCM with only notification parameter :
6980
```php
7081
fcm()

src/Fcm.php

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
class Fcm
1010
{
1111
protected $recipient;
12+
protected $topic;
1213
protected $data;
1314
protected $notification;
1415

@@ -19,6 +20,13 @@ public function to(array $recipient)
1920
return $this;
2021
}
2122

23+
public function toTopic(string $topic)
24+
{
25+
$this->topic = $topic;
26+
27+
return $this;
28+
}
29+
2230
public function data(array $data = [])
2331
{
2432
$this->data = $data;
@@ -38,17 +46,22 @@ public function send()
3846
$fcmEndpoint = 'https://fcm.googleapis.com/fcm/send';
3947

4048
$fields = [
41-
'registration_ids' => $this->recipient,
4249
'content-available' => true,
4350
'priority' => 'high',
4451
'data' => $this->data,
4552
'notification' => $this->notification
4653
];
4754

55+
if ($this->topic) {
56+
$fields['to'] = "/topics/" . $this->topic;
57+
} else {
58+
$fields['registration_ids'] = $this->recipient;
59+
}
60+
4861
$serverKey = config('laravel-fcm.server_key');
4962

5063
$headers = [
51-
'Authorization:key='.$serverKey,
64+
'Authorization:key=' . $serverKey,
5265
'Content-Type:application/json'
5366
];
5467

@@ -60,8 +73,8 @@ public function send()
6073
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CURL_IPRESOLVE_V4);
6174
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
6275
$result = json_decode(curl_exec($ch));
63-
curl_close($ch);
64-
65-
return $result;
76+
curl_close($ch);
77+
78+
return $result;
6679
}
6780
}

0 commit comments

Comments
 (0)