GoogleCloudMessaging PHP script always returning i

2019-01-25 20:32发布

问题:

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?

回答1:

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 ),
             );


回答2:

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!



回答3:

I got the same problem. My problem was my gcm_regid. The length of gcm_regid is 183 bytes. However my database use 150 bytes to store this value. Certainly the stored gcm_regid is incomplete. I fixed the problem by increase the storage size for the key. Then the problem solved.



回答4:

You can use this code:

<?php

// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyDiQ76wcVW2kcwIUQJasuym1JBXXXXX' );


$registrationIds = array( $_POST['id'] );

// prep the bundle
$msg = array
(
    'message'   => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'          => $msg
);

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

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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.$registrationIds[0];

You can change notification to data as you wish.



回答5:

Just replace the code with this and it will work. make sure you replace YOUR_REGISTRATION_ID, YOUR_MESSAGE, YOUR_API_KEY, REGISTRATION_IDS and other comment with original.

<?php
$regId=YOUR_REGISTRATION_ID;
$msg=YOU_MESSAGE;
$message = array("message" => $msg);
$regArray[]=REGISTRATION_IDS;
$url = 'https://android.googleapis.com/gcm/send';

$fields = array('registration_ids' => $regArray, 'data' => $message,);
$headers = array( 'Authorization: key=YOUR_API_KEY','Content-Type: application/json');

$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

$result=curl_exec($ch);
echo $result; 
if($result==FALSE)
{
    die('Curl Failed');
}
curl_close($ch);
}
?>


回答6:

Are you sure the value of the registration ID you are sending to Google is correct?

Invalid Registration ID

Check the formatting of the registration ID that you pass to the server. Make sure it matches the registration ID the phone receives in the com.google.android.c2dm.intent.REGISTRATION intent and that you're not truncating it or adding additional characters. Happens when error code is InvalidRegistration.

While I don't know what's the format of a valid Registration ID, I've never seen a Registration ID with a 2 characters section between two dashes as you have in your Registration Id : ...2-Yl-p....



回答7:

Post an array data to it..

ex :

$registatoin_ids = array($regId);
$message = array(
            "msg_category"      => "cat001",
            "msg_identifier"    => "msg01",
            "user_id"           => "1234",
            "title"             => $title,
            );

and then call the function..

$result = $gcm->send_notification($registatoin_ids, $message);

public function send_notification($registatoin_ids, $message) {
    // include config
    include_once './config.php';

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

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

    $headers = array(
        'Authorization: key=' . GOOGLE_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);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);   

    // 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);
    echo $result;
}


回答8:

Similar problem and at the end it was the bad registration ID (token) received.

I added the following line

echo "id=[$id]";

to the PHP code to verify that the ID is exactly as the token printed in the logcat and found out, using the above echo line, that there was a space added to the beginning and the end of the id. Once I removed the spaces the message was sent with no error.