for sending through google you must use authentication method. which means that you must acquire key.json first from firebase console
- goto https://console.firebase.google.com/
- goto the intended project
- click on cogs button
- click on service accounts
- click on Generate New Private Key button.
it should be contain like this
{
"type": "",
"project_id": "",
"private_key_id": "",
"private_key": "",
"client_email": "",
"client_id": "",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url": "",
"universe_domain": "",
}
then you should use require google library.
im using this
composer require google/apiclient
require that on your project like this
require APPPATH . '/libraries/php-google/autoload.php';
use Google\Auth\Credentials\ServiceAccountCredentials;
on my example, i create a function to create a authentication
function getAccessToken() {
$key = json_decode(file_get_contents('/config/key.json'), true);
$scopes = ['https://www.googleapis.com/auth/cloud-platform']; // Define the scopes you need
$credentials = new ServiceAccountCredentials($scopes, [
'client_email' => $key['client_email'],
'private_key' => $key['private_key']
]);
return $credentials->fetchAuthToken()['access_token'];
}
change ‘/config/key.json’ to the path of your key.. best to dont put it on public folder.
here is for send notification function
0, "message" => "Notification couldn't be sent"];
$tokenArr = $token;
$msgNotification = [
"title" => $title,
"body" => $body,
];
$extraNotificationData = [
"notification_id" => "",
"title" => $title,
"link" => $link
];
$fcmNotification = [
"message" => [
"token" => $tokenArr,
"notification" => $msgNotification,
"android" => [
"priority" => "normal"
],
"data" => $extraNotificationData
]
];
$headers = [
"Authorization: Bearer ".getAccessToken(),
"Content-Type: application/json"
];
if ($token == null || $token == '') {
$result="";
}
else {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
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, $encodedData);
$result = curl_exec($ch);
if ($result === FALSE) {
$result = curl_error($ch);
}
curl_close($ch);
}
$response = ["status" => 1, "message" => "Notification sent to users", "payload" => $result];
return [$response,$token];
}
?>