Подтвердить что ты не робот

Как разобрать GCM, чтобы удалить неверный идентификатор регистрации с сервера с помощью php

У меня возник вопрос о Google Cloud Messaging...

Я отправляю GCM в Google для трех регистрационных идентификаторов, затем Google отвечает, что 2 регистрационных идентификатора отправлены успешно, а один нет, потому что идентификатор регистрации был неправильным!

Но это не говорит мне, какой идентификатор регистрации не отправлен...

Теперь вот мой вопрос: как я могу разобрать ответ Google GCM, чтобы получить тот, который не был отправлен идентификатор регистрации? У Google есть API или что-то такое, что я могу дать ему "multicat_id", и он сообщает мне, какой идентификатор регистрации имел проблему?

Любая помощь была бы очень оценена, я просто так смущен:)

4b9b3361

Ответ 1

Он основан на порядке:

Предположим, вы отправили это сообщение:

{ "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"]
}

И получите ответ от Google:

{ "multicast_id": 216,
  "success": 3,
  "failure": 3,
  "canonical_ids": 1,
  "results": [
    { "message_id": "1:0408" },
    { "error": "Unavailable" },
    { "error": "InvalidRegistration" },
    { "message_id": "1:1516" },
    { "message_id": "1:2342", "registration_id": "32" },
    { "error": "NotRegistered"}
  ]
}

Это означает, что 3-й идентификатор регистрации, который вы отправили (15), недействителен, а 6-й (42) не зарегистрирован. Оба должны быть удалены из вашей базы данных.

Ответ 2

Вот как я это сделал:

$gcm_result = $gcm->send_notification($registration_ids, $message);
$jsonArray = json_decode($gcm_result);

if(!empty($jsonArray->results)){

    $remove_ids = array();

    for($i=0; $i<count($jsonArray->results);$i++){
        if(isset($jsonArray->results[$i]->error)){
            if($jsonArray->results[$i]->error == "NotRegistered"){
                $remove_ids[$i] = "'".$registration_ids[$i]."'";
            }
        }
    }

    if(!empty($remove_ids)){

        $remove_ids_string = implode(', ',$remove_ids);
        include_once SCRIPTS.'gcm_server_php/db_functions.php';
        $dbf = new DB_Functions();
        $res = $dbf->deleteUsers($remove_ids_string);
        echo count($remove_ids)." users have unregistered from notifications since the last one was sent out.";

    }
}

Ответ 3

Основываясь на том, что я читаю здесь:

http://developer.android.com/google/gcm/http.html#error_codes http://developer.android.com/google/gcm/server-ref.html#error-codes

Я разработал следующее (еще не проверено):

$result = $gcm->send_notification($registration_ids, $message);
$jsonArray = json_decode($result);

if($jsonArray->canonical_ids != 0 || $jsonArray->failure != 0){
    if(!empty($jsonArray->results))
    {
        for($i = 0 ; $i<count($jsonArray->results) ; $i++){
            $result = $jsonArray->results[$i];
            if(isset($result->message_id) && isset($result->registration_id))
            {
                // You should replace the original ID with the new value (canonical ID) in your server database
            }
            else
            {
                if(isset($result->error))
                {
                    switch ($result->error)
                    {
                        case "NotRegistered":
                        case "InvalidRegistration":
                            // You should remove the registration ID from your server database
                            break;
                        case "Unavailable":
                        case "InternalServerError":
                            // You could retry to send it late in another request.
                            break;
                        case "MissingRegistration":
                            // Check that the request contains a registration ID
                            break;
                        case "InvalidPackageName":
                            // Make sure the message was addressed to a registration ID whose package name matches the value passed in the request.
                            break;
                        case "MismatchSenderId":
                            // Invalid SENDER_ID
                            break;
                        case "MessageTooBig":
                            // Check that the total size of the payload data included in a message does not exceed 4096 bytes
                            break;
                        case "InvalidDataKey":
                            // Check that the payload data does not contain a key that is used internally by GCM.
                            break;
                        case "InvalidTtl":
                            // Check that the value used in time_to_live is an integer representing a duration in seconds between 0 and 2,419,200.
                            break;
                        case "DeviceMessageRateExceed":
                            // Reduce the number of messages sent to this device
                            break;

                    }
                }
            }
        }
    }
}