Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GoogleCloudMessaging PHP script always returning invalidregistration

I know there are lots of posts with the same issue, but after read all of them I could not find the reason of the problem.

I wrote a GCM client to register my device to receive messages from my server. It is working and I can store the registration ID in my database.

My problem is in the server side. I'm using a script found somewhere googling, but I always receive an error result:

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

The PHP code is (I'm using BROWSER API instead of SERVER API as told on tutorial, but trying both keys returns the same message):

<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyACln4edhSZW30XcmYpqoMz_gcRCC1iFjY";

// Replace with real client registration IDs 
$registrationIDs = array( "APA91bEdf1w4dQtsUqPT1jHhWEpvrpxzB1yrpL3RVtKrVxfzxfg2-Yl-pwHorsnmSnkqywQ8G90YcGEBoqCjgQU8CnjA0N7mOWF8bHMhHAs4ty46PPTX8yh6eSaSqvU3JTMmb-P0ma90EBG0rsQQbUh3aX895KxitI3LCiGOYqRfE5pZQ");

// Message to be sent
$message = "this is a test";

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$fields = array(
                'registration_ids'  => $registrationIDs,
                'data'              => array( "message" => $message ),
                );

$headers = array( 
                    'Authorization: key=' . $apiKey,
                    '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 );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

// Execute post
$result = curl_exec($ch);

// Close connection
curl_close($ch);

echo $result;
?>

I put the real ids and key to see if I'm doing right. Any ideas?

like image 605
Joubert Vasconcelos Avatar asked Dec 09 '22 13:12

Joubert Vasconcelos


2 Answers

I had the same problem a couple of minutes ago.

Change this

$fields = array(
            'registration_ids'  => $registrationIDs,
            'data'              => array( "message" => $message ),
            );

to this:

$fields = array(
             'registration_ids'  => array($registrationIDs),
             'data'              => array( "message" => $message ),
             );
like image 171
Christian Jb Avatar answered Dec 11 '22 10:12

Christian Jb


I found my problem. My PHP library removed some characters from post or get variables. And one of that characteres is '_', because it can be use as SQL injection. That was my problem. Fixed!

like image 42
Joubert Vasconcelos Avatar answered Dec 11 '22 08:12

Joubert Vasconcelos