xxxxxxxxxx
private function getGoogleAccessToken(){
$credentialsFilePath = 'the-folder-and-filename-of-your-downloaded-service-account-file.json'; //replace this with your actual path and file name
$client = new \Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
return $token['access_token'];
}
xxxxxxxxxx
public function sendMessage(){
$apiurl = 'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send'; //replace "your-project-id" with...your project ID
$headers = [
'Authorization: Bearer ' . $this->getGoogleAccessToken(),
'Content-Type: application/json'
];
$notification_tray = [
'title' => "Some title",
'body' => "Some content",
];
$in_app_module = [
"title" => "Some data title (optional)",
"body" => "Some data body (optional)",
];
//The $in_app_module array above can be empty - I use this to send variables in to my app when it is opened, so the user sees a popup module with the message additional to the generic task tray notification.
$message = [
'message' => [
'notification' => $notification_tray,
'data' => $in_app_module,
],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
$result = curl_exec($ch);
if ($result === FALSE) {
//Failed
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
}