5

hi iam trying to send notification from my php web server to android mobile...but i am getting response as

Unauthorized Error 401

below is my code

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

how can i resolve this error

sasi kanth
  • 2,637
  • 4
  • 17
  • 29

1 Answers1

1

this is the working script which i have implemented in my own GCM project. Try to run this. Make sure to do changes in the "api_key" and "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;
    ?>
rajat ghai
  • 153
  • 1
  • 11