Skip to content

Instantly share code, notes, and snippets.

@zeromodule
Created January 9, 2020 10:08
Show Gist options
  • Save zeromodule/59d02ba71c249bb2df1516a7f62e9d44 to your computer and use it in GitHub Desktop.
Save zeromodule/59d02ba71c249bb2df1516a7f62e9d44 to your computer and use it in GitHub Desktop.
FCM message send service
<?php
namespace Core\InfrastructureBundle\Service\Firebase;
use Core\ApplicationBundle\Interfaces\PassengerDeviceNotificationSenderInterface;
use Google\Auth\Credentials\ServiceAccountCredentials;
use GuzzleHttp\Client as HttpClient;
use Psr\Http\Message\StreamInterface;
class MessageSend implements PassengerDeviceNotificationSenderInterface
{
private const FCM_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
private const FCM_BASE_URL = 'https://fcm.googleapis.com/v1/projects/elpass-intercity/messages:send';
/**
* @var HttpClient
*/
private $httpClient;
public function __construct()
{
$headers = [
'Content-Type' => 'application/json; UTF-8',
];
$this->httpClient = new HttpClient([
'http_errors' => false,
'headers' => $headers,
'connect_timeout' => 15.0,
'read_timeout' => 15.0,
'timeout' => 15.0,
'curl' => [
CURLOPT_CONNECTTIMEOUT => 15,
]
]);
}
public function execute(
string $deviceToken,
string $messageTitle,
string $messageText,
array $data = []
): StreamInterface {
$credentials = new ServiceAccountCredentials(
self::FCM_SCOPE,
__DIR__ . '/../../Resources/config/elpass-intercity-firebase.json'
);
$credentials->fetchAuthToken();
$token = $credentials->getLastReceivedToken()['access_token'];
$message = [
'token' => $deviceToken,
'notification' => [
'body' => $messageText,
'title' => $messageTitle,
],
];
if ($data) {
$message['data'] = $data;
}
$response = $this->httpClient->post(self::FCM_BASE_URL, [
'json' => [
'message' => $message,
],
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);
return $response->getBody();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment