Google GCM Server devuelve el Error no autorizado 401


Estoy usando servicios GCM para enviar información desde el servidor. Si utilizo la tecla del navegador, muestra el mesaage de éxito como : {"multicast_id":4849013215736515938,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1348742583011905%2adac3a0f9fd7ecd"}]} pero no recibí ninguna notificación en el dispositivo. Y si uso la clave del servidor, muestra Error no autorizado 401. Mi código se muestra a continuación:

$apiKey = "xxxxx";
$registrationIDs = array("xxxxxxxx");
$message = "testing Process";
$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'
        );
$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_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) );

$result = curl_exec($ch);
if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); }
curl_close($ch);
echo $result;

Por favor ayúdame para este asunto. Gracias de antemano.

Author: Sushil Kandola, 2012-09-27

14 answers

¿Ha incluido en la lista blanca la IP de su servidor? Esto no es necesario de forma predeterminada para la clave del navegador, pero sí para la clave del servidor.

Puedes comprobarlo aquí:

Https://code.google.com/apis/console/#project: [SU NÚMERO DE PROYECTO]: access

 31
Author: Jos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-03 09:00:58

Otra respuesta ya sugirió incluir la dirección IP en la lista blanca, lo que parece bastante obvio. Lo que lo arregló para mí fue la lista blanca de mi dirección IPv6. Esa era la clave! Espero que esto ayude a alguien más.

 19
Author: DanO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-11 18:17:57

Probé todo en este hilo, y todavía no hay suerte.

Así que comprobé APIs habilitadas ( APIs y Auth -> APIs, APIs habilitadas), y me di cuenta de que había habilitado Google Cloud Messaging for Chrome no Google Cloud Messaging for Android. Tan pronto como lo habilité, funcionó de inmediato.

Compruebe que tiene la API correcta habilitada!

 14
Author: Dan Bartlett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-26 13:29:12

Como muchas personas escribieron, tienes que incluir tu servidor en la lista blanca IPV4 e IPV6. Si solo desea IPV4, agregue esto a su curl php init:

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
 3
Author: Thomas Decaux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-27 16:09:05

Use la clave del navegador usando la opción crear nueva clave del navegador y use esta clave en su código. https://code.google.com/apis/console/?pli=1#project:42053154xxxx:access

 2
Author: mayur bhagat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-09 18:50:49

Solía poner a la

$apiKey = "xxxxx"

Como el número de proyecto (id de proyecto) que puse en la aplicación Cliente de Android, pero me he equivocado en el servidor tiene que ser appkey de Google cloud console, (donde se activa Google Cloud Messaging para Android)

    ProjectXXX -> APIs & auth -> Registered Apps -> Web App -> Server Key
 -> Api key

en mi caso, tenía un proyecto predeterminado 'Service Account-project' en la plataforma: 'Web', pero solo había Hosted Application section y no había evidencia sobre ninguna clave api. pero cuando creo nuevo Web Apps llamado 'Mi aplicación' que contenía 4 secciones OAuth 2.0 Client ID, Certificate, Clave del Servidor, Browser Key finalmente encuentro la clave api;-)

Puede que solo yo que no lo sepa, pero creo que esta respuesta también podría ayudar a alguien

 2
Author: m1uan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-05 02:31:48

Para mí el problema era que tienes que habilitar la api. Tener una API configurada no es suficiente. Compruebe que Google Cloud Messaging para Android aparece en las API habilitadas en API - > API habilitadas.

Si no es así, haga clic en la pestaña Biblioteca de API en API y habilítela. \

 1
Author: Nir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-21 15:20:18

Si no me equivoco, su APIKEY debe estar codificado en base64.

También intente var_dump (results results) para ver si obtiene información.

 0
Author: Case,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-27 10:58:23

Mirando el código, reconozco que esto es de un ejemplo de php-gcm publicado en algún lugar en línea. Es bastante agradable y puedo asegurarle que tanto las teclas del navegador como las IP de la lista blanca (no IPV6 o bas64 apikey) funcionan.

La razón por la que no se muestra ningún mensaje es porque la función de notificación de envío que está utilizando 'data' => array("message"=>$message) apunta a una clave de "mensaje", esto es lo que debe pasar a su intención pendiente es decir

notification.setLatestEventInfo(context, title, message, intent);

Esto permitirá al intent leer el mensaje contenido bajo esta clave..el el mensaje en sí se obtiene del método GCMIntentService pegado a continuación:

 @Override
protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Received message");
    String message = intent.getExtras().getString("message");
    Log.d(TAG, "The intent contains: " + intent.getExtras());
    displayMessage(context, message);
    // notifies user
    generateNotification(context, message);
}
 0
Author: Lettings Mall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 10:52:15

Aquí está el problema: estaba usando 2 servidores, 1 staging y el otro el servidor de producción. Para mi servidor de ensayo, que se alojaba con digital ocean, ingresé la dirección inet en la clave para aplicaciones de servidor direcciones IP permitidas, y funcionó bien.

Sin embargo, falló cuando cambié a mi dirección inet desde mi servidor de producción. En su lugar, tuve que usar inet6 addr: / 64 Alcance: Global para que esto funcione. Para obtener el valor si se encuentra con el mismo problema, simplemente introduzca ifconfig , y encuentre la entrada anterior. Introducir ese valor en las direcciones IP permitidas y funcionará bien.

 0
Author: Qin Zhengquan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-31 10:19:08

Debe tener un proyecto diferente al predeterminado. Cree un proyecto y luego cree una clave. No utilice el proyecto predeterminado.

 0
Author: Pavan Pyati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-03 19:44:15

Tuve este problema, estaba usando GCM (Google cloud messaging). Pero después de septiembre de 2016, la clave del servidor en el GCM no funcionará, debe usar FCM (firebase cloud messaging). Cree nuevas claves de servidor solo en la consola Firebase utilizando la pestaña Cloud Messaging del panel de configuración. Fui a la consola de la base de fuego. console.firebase.google.com (Todavía no lo había usado) y me pidió que importara mi proyecto. De repente había una nueva clave de servidor en la consola de GCM. Si usa GCM, use el "clave heredada"aparece en la lista.

 0
Author: Nate Hammond,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-17 00:45:17

Asegúrese de que ha habilitado su Clave de API Survery!

 -1
Author: user3559800,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-23 23:00:27

Estamos buscando soluciones en días. Más específicamente, agregue esta opción de curl: curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

 -1
Author: Kamilklkn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-24 02:23:59