-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotifier.php
67 lines (54 loc) · 1.78 KB
/
Notifier.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
<?php
namespace uzdevid\fcm;
use Exception;
use Yii;
use yii\base\Component;
use yii\web\BadRequestHttpException;
/**
* Class Notifier
* @package uzdevid\yii2-fcm
* @category Yii2 Extension
* @version 1.0.0
* @author UzDevid - Ibragimov Diyorbek
* @license MIT
*/
class Notifier extends Component {
private string|null $_serverKey = null;
public function getServerKey(): string|null {
return $this->_serverKey;
}
public function setServerKey(string $serverKey): void {
$this->_serverKey = $serverKey;
}
/**
* @throws Exception
*/
public function notify($to, $data, $params = []) {
$fields = array_merge([
'to' => $to,
'notification' => $data,
], $params);
$headers = [
'Authorization: key=' . $this->_serverKey,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
if ($result === false) {
throw new Exception(Yii::t('app', 'Curl error: {error}', ['error' => curl_error($ch)]));
}
if (empty($result)) {
throw new BadRequestHttpException(Yii::t('app', 'Empty response from FCM server'));
}
if (!$result['success']) {
throw new BadRequestHttpException(Yii::t('app', 'FCM server error: {error}', ['error' => json_encode($result, JSON_UNESCAPED_UNICODE)]));
}
return $result;
}
}