In general, if you want to send to only 1 device, you need to get the Firebase token while the app is running and save it to your server. Then your server will send that token to Firebase to push.
I have a table named "fcm" that maps users to device tokens:
This is the code I'm using to doing Firebase pushing. The "registration_ids" is a list of Firebase device tokens. I'm using Fat Free Framework for some of the lines that contain "$f3". Note that Firebase supports 3 types of push messages (notification, data, and both). You can read more about it
here. The code below only uses "notification" type.
CODE
public static function fcmpush( $title, $text, $registration_ids ) {
$errors = [];
$f3 = Base::instance();
$data = [
"registration_ids" => $registration_ids,
"notification" => [
"title" => $title,
"text" => $text,
"sound" => "default"
],
"priority" => "high"
];
$fcmserverkey = $f3->get('fcmserverkey');
if ( empty($fcmserverkey) ) {
$errors[] = 'Invalid fcmserverkey in config.';
return $errors;
}
$data_string = json_encode( $data );
$curl = curl_init();
if(curl_errno($curl)){
$errors[] = 'Curl error: ' . curl_error($curl);
return $errors;
}
curl_setopt($curl, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type:application/json",
'Authorization:key=' . $fcmserverkey,
));
if(curl_errno($curl)){
$errors[] = 'Curl error: ' . curl_error($curl);
return $errors;
}
// curl_exec can crash for some reason, probably something to with SSL
$result = curl_exec($curl);
if (!$result) {
$errors[] = 'fcmpush: curl_exec returned ' . $result;
}
curl_close($curl);
return $errors;
}
This post has been edited by Andrew Lim: Aug 20 2017, 09:24 PM