Amos
Amos

Reputation: 1341

GCM - One registration id is working but fails with multiple registration ids

I want to send GCM messages to several registered devices. When sending only to one (as a test), it works but when adding the rest of the ids, I get invalidregistration error and nothing is sent.

I do the following:

$sql = "select group_concat(gcm_id) from users where gcm_id is not null";

if there is only 1 id (regid1), it works, if there are more than one (regid1,regid2), it fails with invalidregistration. I tried the following:

$sql = "select group_concat(concat('\"',gcm_id,'\"')) from users where gcm_id is not null";

this fails for both 1 id ("regid1") and several id ("gcmid1","gcmid2").

How should the reg ids be formatted for this to work?

$sql = "select group_concat(gcm_id) from users where gcm_id is not null";
    if ($stmt = $con->prepare($sql)) {
        if ($stmt->execute()) {                             
            $stmt->bind_result($gcm_ids);
            $stmt->fetch();         
            $ids = array($gcm_ids);
            $stmt->close();                         
        } else trigger_error("Problem retrieving gcm ids");
    } else trigger_error("Problem retrieving gcm ids");
    $con->close();      

if (empty($gcm_ids)) trigger_error("no registrations"); 
    else sendGoogleCloudMessage(  $data, $ids );

    function sendGoogleCloudMessage( $data, $gids ) {   
        $apiKey = '...';
        $url = 'https://android.googleapis.com/gcm/send';

        $post = array('registration_ids' => $gids,'data' => $data);

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

        $ch = curl_init();
        // Set URL to GCM endpoint
        curl_setopt( $ch, CURLOPT_URL, $url );
        // Set request method to POST
        curl_setopt( $ch, CURLOPT_POST, true );
        // Set our custom headers
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
        // Get the response back as string instead of printing it
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        // Set post data as JSON
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
        // Actually send the push!
        $result = curl_exec( $ch );
        if (curl_errno($ch)) trigger_error('Error: '.curl_error($ch));
        else echo "sent: ".$result;
        curl_close( $ch );                  
    }   

Upvotes: 1

Views: 236

Answers (1)

Phenbach
Phenbach

Reputation: 38

Try using explode

$ids = explode(",",$gcm_ids);

The registration_ids should be submit as an array.

{ "collapse_key": "score_update",
  "time_to_live": 108,
  "delay_while_idle": true,
  "data": {
    "score": "4x8",
    "time": "15:16.2342"
  },
  "registration_ids":["4", "8", "15", "16", "23", "42"]
}

More info can be found here https://developer.android.com/google/gcm/http.html

Upvotes: 1

Related Questions