user7781428
user7781428

Reputation:

Firebase FCM server php-android

I created a simple php code to send a notification to my android devices which have google log in method from firebase implementation. Their tokens are already stored in my database. When I execute my php, it doesn't send the notification. Whoever , if i send a notification trough firebase notification console it works. This is my php code .

function sendGCM($message, $registration_ids) {
    //FCM URL
    $url = "https://fcm.googleapis.com/fcm/send";
//prepare data
$fields = array (
    'registration_ids' => array ($registration_ids),
    'data' => array ("message" => $message)
);
$fields = json_encode ( $fields ); 

//header data
$headers = array ('Authorization: key=<YOUR_API_KEY>', 'Content-Type: application/json');

//initiate curl request
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

// execute curl request
$result = curl_exec ( $ch );

//close curl request
curl_close ( $ch );

//return output
return $result;
}

Error: when I execute this php file, throw this error:

{

    "multicast_id": 5359746182596118281,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
    {
    "error": "InvalidRegistration"
    }
                ]
    }

Upvotes: 1

Views: 1346

Answers (1)

hablema
hablema

Reputation: 550

Try this:-

    <?php

// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'your_key' );
$registrationIds = array($id); //$id is string not array


// prep the bundle
$notification = array
(
    'title'     => 'title',
    'body'      => 'body',
    'icon'      => 'logo',
    'sound'     => 'default',
    'tag'       => 'tag',
    'color'     => '#ffffff'

);

$data = array
(
    'message' => 'message body',
    'click_action' => "PUSH_INTENT"
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'      => $notification,
    'data'              => $data,
    'priority'          => 'normal'

);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
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 );
echo $result;

?>

Upvotes: 2

Related Questions