GCM Implementation using PHP always facing Unauthorized Error 401

微笑、不失礼 提交于 2019-12-18 08:56:43

问题


I am always getting 401 error.Please any one could let me know exactly what should be HTTP referrers if i am using my local server. i.e Currently I am using:

    http://localhost/GCM/index.php 

and generating a API access key using it.

Here is my php code for GCM request.

                $key='mykey';
                $headers=array('Contenttype:application/json','Authorization:key='.$key);
                $url = 'https://android.googleapis.com/gcm/send';
                $ch = curl_init();
                $curlConfig = array(
                CURLOPT_URL            => $url,
                CURLOPT_POST           => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS     => json_encode(array('field1' => 'some date','field2' => 'some other data',)),
                CURLOPT_HTTPHEADER     => $headers,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                );
                curl_setopt_array($ch, $curlConfig);
                $result = curl_exec($ch);
                curl_close($ch);
                if($result==FALSE){
                    echo curl_error($ch);
                    echo curl_getinfo($ch);
                }else{
                    echo $result;
                }

回答1:


I battled same problem. Turned out it was IPv6 related! I created server key as described in http://developer.android.com/google/gcm/gs.html using 0.0.0.0/0 as permitted host IP, but that does not match IPv6. So I added another permitted host line IP as 0::0/0 and that worked (AFTER some time, to update cached config?).

Leaving the IP field blank allows ANY IP and is easier.




回答2:


I can see several errors:

  1. Contenttype:application/json should be Content-Type: application/json.
  2. You forgot to include the registration ids in the JSON.
  3. I'm not sure if CURLOPT_SSL_VERIFYPEER => false and CURLOPT_SSL_VERIFYHOST => false are required.

You can find many PHP GCM samples that work (for example - here).




回答3:


This is due to you are not enable you IP to access GCM,To Know your network IP type "my ip" in GOOGLE,after that create SERVER KEY in you Google_Api_Console and Use the ip in SERVER KEY generation,Use the SERVER KEY in your php file in local server,the first image show's the list of key in google console to select,choose server key and second image show's that to put the ip what you need to enable.



来源:https://stackoverflow.com/questions/18736162/gcm-implementation-using-php-always-facing-unauthorized-error-401

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