如何从 PHP 向 Android 发送推送通知

5

你好,我正在尝试从我的PHP Web服务器向Android手机发送通知...但是我收到的响应是:

Unauthorized Error 401

以下是我的代码。
<?php $url = 'https://android.googleapis.com/gcm/send';
$device_ids = array('devise ID' );
$headers = array('Authorization: key=api key',
'Content-Type: application/json');
$t_data = array();
$t_data['message'] = array('Someone commented on your business.');
$t_json = array( 'registration_ids' => $device_ids , 'data' => $t_data );

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $t_json ) );
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
if ($result === FALSE)
{
 die('Curl failed: ' . curl_error($ch));
}

curl_close($ch);

echo $result;
?>

我该如何解决这个错误


1
请仔细检查 API key - Mehul Joisar
是的,我检查过了,但没有运气。 - sasi kanth
你是否定义了 API 密钥?格式为 "Authorization: key=api key"。该 API 密钥是在应用程序在 Google 上注册 GCM 服务时发行的。请确认一下。 - AndroidHacker
还要检查一下这个网址:https://dev59.com/nWcs5IYBdhLWcg3wu2Yp - AndroidHacker
1个回答

1
这是我在自己的GCM项目中实施的工作脚本。尝试运行此脚本。 确保更改“api_key”和“registrationids”。
 <?php
        $api_key = "AIzBpx4XbXkhkjwKd8P-v2d1Jk";
        $registrationIDs = array("APA91bjkj3Rjlo8T_URx15NqvxY2mRyQ");
        $message = "congratulations";
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "message" => $message ),
                    );

        $headers = array(
                        'Authorization: key=' . $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_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch);
        curl_close($ch);

    echo $result;
    ?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接