Last active
June 17, 2019 05:57
-
-
Save ImaginativeShohag/bc1e4887a7a25c637ea00d75cd35d9f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Gist by: | |
* Md. Mahmudul Hasan Shohag | |
* imaginativeshohag@gmail.com | |
* | |
* Help Doc: | |
* - https://firebase.google.com/docs/cloud-messaging/http-server-ref | |
* | |
* How to get FCM Server Kay: | |
* - https://developer.clevertap.com/docs/find-your-fcm-sender-id-fcm-server-api-key | |
*/ | |
/** | |
* Use example: | |
* | |
* $data = array( | |
* 'key1' => 'value1', | |
* 'key2' => 'value2' | |
* ); | |
* | |
* send_notification("topic_name", "title", "message", $data); | |
*/ | |
/** | |
* Firebase Cloud Messaging server key. | |
*/ | |
const FCM_SERVER_KEY = ""; | |
/** | |
* @param $topic string Single topic name | |
* @param $title string Notification title | |
* @param $message string Notification message | |
* @param null|array $data | |
*/ | |
function send_fcm_notification_to_a_topic($topic, $title, $message, $data = null) | |
{ | |
$fcmUrl = 'https://fcm.googleapis.com/fcm/send'; | |
# Notification payload | |
$notification = array | |
( | |
'title' => $title, | |
'body' => $message, | |
'sound' => 'default' | |
); | |
if ($data == null) { | |
$fields = array | |
( | |
'to' => "/topics/$topic", | |
'notification' => $notification | |
); | |
} else { | |
$fields = array | |
( | |
'to' => "/topics/$topic", | |
'notification' => $notification, | |
'data' => $data | |
); | |
} | |
$headers = array | |
( | |
'Authorization: key=' . FCM_SERVER_KEY, | |
'Content-Type: application/json' | |
); | |
# Send Request To Firebase Server | |
$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, json_encode($fields)); | |
$result = curl_exec($ch); | |
curl_close($ch); | |
var_dump($result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment