/
FirebaseCloudMessaging.php
92 lines (83 loc) · 3.19 KB
/
FirebaseCloudMessaging.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
88
89
90
91
92
<?php
namespace traversient\yii;
use yii\base\Component;
use yii\base\InvalidCallException;
use yii\base\InvalidParamException;
use yii\helpers\VarDumper;
use yii\httpclient\Client;
use yii\web\ServerErrorHttpException;
/**
* Cloud Messaging components that provides easy-to-use mechanism to send messages from your Yii2 code through to FCM
*/
class FirebaseCloudMessaging extends Component
{
protected $myConfig;
protected $apiClient;
protected $api_key;
protected $project_id;
public function __construct(array $config)
{
parent::__construct();
$this->myConfig = $config;
$this->apiClient = new Client([
'transport' => 'yii\httpclient\CurlTransport',
'requestConfig' => [
'format' => Client::FORMAT_JSON
],
'responseConfig' => [
'format' => Client::FORMAT_JSON
],
]);
if (empty($this->myConfig)){
throw new InvalidCallException("Config must be passed!");
}
if (empty($this->myConfig['api_key'])){
throw new InvalidCallException("api_key must be present in config array!");
}
$this->api_key = $this->myConfig['api_key'];
if (empty($this->myConfig['project_id'])){
throw new InvalidCallException("project_id must be present in config array!");
}
$this->project_id = $this->myConfig['project_id'];
}
public function sendMessage(string $to,array $notificationPayload = null, array $dataPayload = null){
if (empty($to)){
throw new ServerErrorHttpException("A recipient MUST be provided as registration token id OR full topic path OR notification key");
}
$fullPayload = ["to" => $to];
if (empty($notificationPayload) && empty($dataPayload)){
throw new ServerErrorHttpException("At least one of notificationPayload or dataPayload MUST be provided");
}
if (!empty($notificationPayload)){
$fullPayload["notification"] = $notificationPayload;
}
if (!empty($dataPayload)){
$fullPayload["data"] = $dataPayload;
}
$sfullPayload = VarDumper::dumpAsString($fullPayload);
\Yii::info("Sending message to FCM: $sfullPayload","cron");
$request = $this->apiClient->createRequest();
$request->setUrl("https://fcm.googleapis.com/fcm/send")
->setMethod("POST")
->setData($fullPayload)
->setHeaders([
"Accept"=>"application/json",
"Content-Type"=>"application/json",
"Authorization"=>"key=$this->api_key"
])
;
$response_send = null;
try{
$response_send = $request->send();
}
catch (InvalidParamException $exception){
\Yii::error("Exception caught while trying to send FCM request: $exception","cron");
}
if (! $response_send->getIsOk()){
$imploded = VarDumper::dumpAsString($response_send->getData());
throw new ServerErrorHttpException("Did not get ok response, data: {$imploded}");
}
$responseData = $response_send->getData();
return $responseData;
}
}