2

Hello Im trying to use GCM on my android app.

My problem is that when trying to sent message I get 401 error, Unauthorized error.

I made a key for server applications in the google cloud console and followed this instructions: http://developer.android.com/google/gcm/gs.html

This my code:

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

    }

from my app I sent POST to this PHP code:

    include_once './GCM.php';

        $gcm = new GCM();

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

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

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

    echo $result;
SteAp
  • 11,853
  • 10
  • 53
  • 88
dasdasd
  • 1,971
  • 10
  • 45
  • 72

2 Answers2

4

I removed all allowed ip so any ip is allowed and its working.

dasdasd
  • 1,971
  • 10
  • 45
  • 72
  • I had a similar problem from my server and removing the IPs worked for me too. Oddly, I was able to send via nodejs but not from my .Net web application. I wasted hours on this, so thanks for the suggestion. – raider33 Jul 10 '14 at 23:27
0

Make sure you are using GCM "Server Key" and not "Android Key" for your API key.

user3059993
  • 324
  • 1
  • 4
  • 9