Skip to content

Instantly share code, notes, and snippets.

@jjjjcccjjf
Created February 7, 2019 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jjjjcccjjf/6544600dbc863a7ce1148a63fa857755 to your computer and use it in GitHub Desktop.
Save jjjjcccjjf/6544600dbc863a7ce1148a63fa857755 to your computer and use it in GitHub Desktop.
<?php
#class declaration
class Firebase_model extends CI_model
{
public function __construct()
{
parent::__construct();
define('FIREBASE_API_KEY', 'AAAAh66AGWk:APA91bE83vgJIkt-Edb9iStKIWErZ0iE2UvQR8hXM_iQOzNwZu25C1IChOn8GmxyWg5yzMuCpFa55UhMvoqRLzS0hPZt4jUtQUjMq6IHbMMHMVM3IbguGLgQCqKmneqKIG1c9SWi7khL1g7GkOLiase7xPtvJ_WKIw');
}
// sending push message to single user by firebase reg id
public function send($to, $message, $notification) {
$fields = array(
'to' => $to,
'notification' => $notification,
'data' => $message,
'priority' => 'high'
);
return $this->sendPushNotification($fields);
}
// Sending message to a topic by topic name
public function sendToTopic($to, $message, $notification) {
$fields = array(
'to' => '/topics/' . $to,
'notification' => $notification,
'data' => $message,
'priority' => 'high'
);
return $this->sendPushNotification($fields);
}
// sending push message to multiple users by firebase registration ids
public function sendMultiple($registration_ids, $message, $notification) {
$fields = array(
'to' => $registration_ids,
'notification' => $notification,
'data' => $message,
'priority' => 'high'
);
return $this->sendPushNotification($fields);
}
// function makes curl request to firebase servers
private function sendPushNotification($fields) {
// Firebase API Key
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
} # end of class
##########################
#### Sample usage ########
##########################
$firebase_response = $this->firebase_model->sendToTopic($topic_name_string,
['data' => []],
['title' => 'New notification', 'body' => 'Hello world']
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment