I have added the .php files on my server to send the notifications using FCM, but the code stops running when I create the actual message. I have a constructor for push and when I call it in sendSinglePush, it does not do anything.
The rest is working properly. I get the parameters ok, and the devicetoken. I just need to create that push and it should work. I've used the same sendSinglePush.php for testing on localhost, and it works. When I add it on server it just stops.
EDIT: As per #ADyson, who helped me understand abit about logging my errors, I started to log every variable from the start to the point where it crashes. The $push it's alright, the problem it's on Firebase.php:
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => array($registration_ids),
'data' => $message,
);
//print_r($fields);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
print_r(curl_error($ch));
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
print_r($result);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
print_r(curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
And the methods are called from sendSinglePush.php, where all the variables are sent correctly:
$mPushNotification = $push->getPush();
//print_r($mPushNotification);
//getting the token from database object
$devicetoken = $db->getTokenByEmail($_POST['email']);
//print_r($devicetoken);
//creating firebase class object
$firebase = new Firebase();
//sending push notification and displaying result
$firebase->send($devicetoken, $mPushNotification);
I have added different print_r() to check the output using POSTMAN and, from that code, the $headers are fine, after the $ch = curl_init(); nothing else shows up. I tried to add print_r(curl_error($ch)); but it does not show enything. Also, I tried with print_r(1); under the $ch = curl_init();to see if the code keeps running, but on postman there was no answer, only a blank screen and 500 Internal Server Error.
Related
Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);
I am trying to get notification in my app using GCM. i am using android studio tool and i tried lots of tutorials. most of them where done using eclips tool.
finally, i tried this one,
http://rmarcejaeger.com/2015/09/18/tutorial-how-to-implement-push-notifications-using-google-cloud-messaging-for-android-part-1-client-app/#comment-576070,
https://github.com/googlesamples/google-services/tree/master/android/gcm
and i finish android client part using above tutorial. But the problem is, i need to setup app server in php which connect my application through GCM. i have no idea to make it possible. i tried the follwing link,
https://developers.google.com/cloud-messaging/server
but i couldn't get much more.So please anyone suggest me better solution.
you need to understand below steps
for more details Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL
First you need to create browser key from Console.
This is the code you need to add for Sending notification GOOGLE_API_KEY is the key you created from Console.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// 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;
}
}
?>
Now using this method of GCM class you can send notification to the device by calling its method.
pass reg.id that is token id you got from Android device and message you want to pass.
$gcm = new GCM();
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
I am using the new Google Cloud messaging functionality and it's developed successfully in client side and receiving push notification without any dropping. But I'm using an old Send function on the server. Now I want to implement new send function (XMPP) using PHP.
I have registered here also https://services.google.com/fb/forms/gcm/ and got the response mail and key from the google.
And from that I got that I have to implement the SmackCcsClient Java class and two libraries. But I have no idea how to host that file to my PHP server.
After some research I got the function for PHP and xmphp libraries for PHP
$conn = new XMPPHP_XMPP($host, $port, $user, $password, $resource,
$server, $printlog, $loglevel);
But can't get the success it's saying could not connect.
You can use this class:
class gcm {
public static function send_notification($deviceid, $message) {
// include config
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => (is_array($deviceid) ? $deviceid : array($deviceid)),
'data' => array("message" =>$message),
);
$headers = array(
'Authorization: key=YOUR-AUTH-KEY',
'Content-Type: application/json'
);
// 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);
}
}
I'm working on GCM to send messages to android devices. It worked perfectly with in localhost. But when I tried with the remote server, GCM not allowing the to access it. It shows as "Failed to connect to : Permission denied". I thought, it is the problem with using the same api key for both localhost and remote server. I also changed the api key. Can anyone explain me whats the problem with this. Thanks. The GCM code goes like this.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// 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;
}
}
?>
Clear all the IP Address from Server Key Page of Google Console, maybe this will solve your problem. If not please contact in comments.
I've searched a lot but couldn't find any solution for this question.
I'm using a PHP server and is trying to send PushNotifications to my Android app. But when I'm trying out my code in the browser I get this error: "Error=MissingRegistration".
Here is the code that I run:
registration_ids = array($regId);
$message = array(
'hangMessage' => $message,
'userId' => $user_id
);
$result = $gcm->send_notification($registration_ids, $message);
And this is the code that I call:
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => $regisration_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type= application/json',
);
//Open connection
$ch = curl_init();
//Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
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 psot
$result = curl_exec($ch);
if($result == false){
die('Curl failed: ' . Curl_error($ch));
}
//Close connection
curl_close($ch);
echo $result;
The Request doesn't even come all the way to the server according to the Google APIs Console Report system.
Anyone have any idea what could be wrong?
Your request should look like this :
Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
"data" : {
...
},
}
Therefore I believe the error might be in this line :
'Content-Type= application/json'
Try to change the = to :.
Since the content type header is invalid, the GCM server may assume a default value for the content type (which might be application/x-www-form-urlencoded;charset=UTF-8, in which case the Registration ID requires a different key, which would explain the MissingRegistration error).
BTW, the fact that you get a MissingRegistraton error means that the request does reach the GCM server. GCM requests are not logged in the Google APIs Console Report system.