Invalid Registration Id with my gcm php server

余生颓废 提交于 2019-12-25 04:29:10

问题


So I'm POSTing to my gcm.php and sending the registration id of the users phone to be put in a text file on my server (Will implement a DB afterwards). For some reason, I'm getting an invalid registration error when I post to the gcm server.

I've checked my txt file and it's not getting populated (which is the problem) So I'm curious what I'm doing wrong in my android client side code that isn't sharing the user's ID with my php server.

gcm.php (server)

<?php


//generic php function to send GCM push notification
   function sendPushNotificationToGCM($registatoin_ids, $message) {
        //Google cloud messaging GCM-API url
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
        // Google Cloud Messaging GCM API Key
        define("GOOGLE_API_KEY", "AIzaSyDA5dlLInMWVsJEUTIHV0u7maB82MCsZbU");        
        $headers = array(
            'Authorization: key=' . GOOGLE_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_SSL_VERIFYHOST, 0);   
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);               
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
?>
<?php

    //this block is to post message to GCM on-click
    $pushStatus = "";   
    if(!empty($_GET["push"])) { 
        $gcmRegID  = file_get_contents("GCMRegId.txt");
        $pushMessage = $_POST["message"];   
        if (isset($gcmRegID) && isset($pushMessage)) {      
            $gcmRegIds = array($gcmRegID);
            $message = array("m" => $pushMessage);  
            $pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
        }       
    }

    //this block is to receive the GCM regId from external (mobile apps)
    if(!empty($_GET["shareRegId"])) {
        $gcmRegID  = $_POST["regId"]; 
        file_put_contents("GCMRegId.txt",$gcmRegID);
        echo "Ok!";
        exit;
    }   
?>
<html>
    <head>
        <title>Google Cloud Messaging (GCM) Server in PHP</title>
    </head>
    <body>
        <h1>Google Cloud Messaging (GCM) Server in PHP</h1> 
        <form method="post" action="gcm.php/?push=1">                                                
            <div>                                
                <textarea rows="2" name="message" cols="23" placeholder="Message to transmit via GCM"></textarea>
            </div>
            <div><input type="submit"  value="Send Push Notification via GCM" /></div>
        </form>
        <p><h3><?php echo $pushStatus; ?></h3></p>        
    </body>
</html>

And here is the android client (where I try to share the regId with the server MainActivity.java

 class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {

    private GoogleCloudMessaging gcm;
    private Context context;

    // TODO: change to your own sender ID to Google Developers Console project number, as per instructions above
    private static final String SENDER_ID = "617516375608";

    public GcmRegistrationAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(Void... params) {
        if (regService == null) {
            Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                    .setRootUrl("https://keen-proton-827.appspot.com/_ah/api/");
            // end of optional local run code

            regService = builder.build();
        }

        String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            String regId = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regId;

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.


            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://68.84.84.84/gcm.php?shareRegId=1");

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("regId", regId));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);

            Log.d("STATUS", response.toString());

            regService.register(regId).execute();

        } catch (IOException ex) {
            ex.printStackTrace();
            msg = "Error: " + ex.getMessage();
        }
        return msg;
    }

    @Override
    protected void onPostExecute(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        Logger.getLogger("REGISTRATION").log(Level.INFO, msg);
    }
}

回答1:


Registration Id: the token got after sucessfully registered in Android client

String token =
                            InstanceID.getInstance(mContext).getToken(senderId,
                                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);


来源:https://stackoverflow.com/questions/28116313/invalid-registration-id-with-my-gcm-php-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!