来自GCM Server的401错误

时间:2014-02-13 21:57:38

标签: php android google-cloud-messaging

您好我试图在我的Android应用程序上使用GCM。

我的问题是,当尝试发送消息时,我收到401错误,未经授权的错误。

我在Google云端控制台中为服务器应用程序创建了一个密钥,并按照以下说明操作:http://developer.android.com/google/gcm/gs.html

这是我的代码:

    class GCM {

        //put your code here
        // constructor
        function __construct() {

        }

        /**
         * Sending Push Notification
         */
        public function send_notification($registatoin_ids, $message) {

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

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

            $headers = array(
             'Content-Type: application/json',
                'Authorization: key=**MY_KEY***'        
            );
            // 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);

            // 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;
        }

    }

从我的应用程序我发送POST到这个PHP代码:

    include_once './GCM.php';

        $gcm = new GCM();

        $message = array("status" => "1");

    $ids = array('**my_gcm_id**');

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

    echo $result;

2 个答案:

答案 0 :(得分:4)

我删除了所有允许的ip,因此允许任何ip并且正常工作。

答案 1 :(得分:0)

确保您的API密钥使用GCM“服务器密钥”而不是“Android密钥”。

相关问题