forked from OpenSooq/yii2-firebase-notification
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FirebaseNotifications.php
87 lines (78 loc) · 2.84 KB
/
FirebaseNotifications.php
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
<?php
namespace mackiavelly\firebase;
use Yii;
use yii\base\Object;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
class FirebaseNotifications extends Object {
/**
* @var string the auth_key Firebase cloude messageing server key.
*/
public $authKey;
public $timeout = 5;
public $sslVerifyHost = false;
public $sslVerifyPeer = false;
/**
* @var string the api_url for Firebase cloude messageing.
*/
public $apiUrl = 'https://fcm.googleapis.com/fcm/send';
public function init() {
if (!$this->authKey) throw new \Exception("Empty authKey");
}
/**
* send raw body to FCM
* @param array $body
* @return mixed
*/
public function send($body) {
$headers = [
"Authorization:key={$this->authKey}",
'Content-Type: application/json',
'Expect: ',
];
$ch = curl_init($this->apiUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYHOST => $this->sslVerifyHost,
CURLOPT_SSL_VERIFYPEER => $this->sslVerifyPeer,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_BINARYTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FRESH_CONNECT => false,
CURLOPT_FORBID_REUSE => false,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => Json::encode($body),
]);
$result = curl_exec($ch);
if ($result === false) {
Yii::error('Curl failed: '.curl_error($ch).", with result=$result");
throw new \Exception("Could not send notification");
}
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code < 200 || $code >= 300) {
Yii::error("got unexpected response code $code with result=$result");
throw new \Exception("Could not send notification");
}
curl_close($ch);
return Json::decode($result);
}
/**
* high level method to send notification for a specific tokens (registration_ids) with FCM
* see https://firebase.google.com/docs/cloud-messaging/http-server-ref
* see https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
*
* @param array $tokens the registration ids
* @param array $notification can be something like array ['title' => 'title', 'body' => 'body', ...]
* @param array $options other FCM options
* @return mixed
*/
public function sendNotification($tokens, $notification, $options = []) {
$body = [
'registration_ids' => $tokens,
'notification' => $notification,
];
$body = ArrayHelper::merge($body, $options);
return $this->send($body);
}
}