Daniel Chan Daniel Chan - 1 month ago 48
Android Question

How to send FCM messages by using php? (Keep getting error 401)

Below is the code I write to send a message out, the key is from the Firebase messaging tab. However, I keep getting the unauthorised message. Any Help?

<?php
$ch = curl_init("https://fcm.googleapis.com/fcm/send");

$header = array("Authorization:key=MY_KEY",
"Content-Type:application/json"
);

$json = array();
$json['notification'] = array("title"=>"Testing", "body"=>"abcdef");
$json['to'] = "c2Fl77B0tH4:APA91bHvt8Z2QX_g2E0tSV9ognaM4F2Ci86D9fwsKf1pq3l-NeReGQQk43EvQ8_m_Ixs3gB6EX4RUWwRyQPC-Z_JGQzfVxkpZbQ7Nv4DpD26YExRlL4jBr75qy5QLljgU2S83Dag3Jt0";
$body = json_encode($json);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_exec($ch);
curl_close($ch);
?>

Answer

Use this

<?php
$url = "https://fcm.googleapis.com/fcm/send";

$values = array();
$values ['title'] = "Testing";
$values ['body'] =  "abcdef";

$data = array();
$data ['to'] = "c2Fl77B0tH4:APA91bHvt8Z2QX_g2E0tSV9ognaM4F2Ci86D9fwsKf1pq3l-NeReGQQk43EvQ8_m_Ixs3gB6EX4RUWwRyQPC-Z_JGQzfVxkpZbQ7Nv4DpD26YExRlL4jBr75qy5QLljgU2S83Dag3Jt0";
$data ['notification'] = $values;

$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array(
            "Content-type: application/json",
            "Authorization: key=Your Authorization Key"
            ));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);
$response = json_decode($json_response, true);
?>