Chrome extension not receiving Firebase Cloud Messages - google-chrome

Something really weird is happening with me. Yesterday atfernoon I realized my chrome extension wasn't receiving Firebase Cloud Messages sent by my server. I've tried to create a new Chrome Extension with nothing more than the GCM API and a simple server page with the message sender, but it still not working.
Suddenly it started working again and I received ALL the messages that I sent in that period!! I thought it was a server issue and ok. Today in the morning it was working perfectly. BUT AGAIN, in the afternoon, it stopped! I don't know what to do, I've been using Chrome extension with the GCM API for months and it have never happened before.
My extension:
manifest.json
{
"name": "__MSG_myextension__",
"version": "1.3",
"icons": {
"128": "images/my-icon.png"
},
"permissions": [
"background",
"gcm",
"storage"
],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2,
"default_locale" : "en"
}
background.js (yes I copied from here)
function registerCallback(registrationId) {
console.log(registrationId);
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
return;
}
}
var senderIds = ["MY-SENDER-ID"];
chrome.gcm.register(senderIds, registerCallback);
chrome.gcm.onMessage.addListener(function(message) {
console.log(message);
});
My server:
$registration_id = '...';
$key = '...';
$message = '{"collapse_key":"'.time().'","data":{"message":"hello world"},"priority":"high","registration_ids":["'.$registration_id.'"]}';
$headers = array(
'Content-Type: application/json; charset=UTF-8',
'Authorization:key=' . $key );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$result = curl_exec($ch);
var_dump($result);
As a result from my curl, I'm getting always success.
I'm pretty sure I'm sending the message to the right registration ID.
Can somebody help me??

Related

PHP Curl POST with JSON returns Server Error 500 - Django

I am using the code below to make PHP Curl POST request. Could someone tell me , why the server sends me Server Error Code 500? When open the api link in the browser and test it with json data everything is ok. I use the similar code to make PUT request and I don`t have problems.
$postArray = array(
"email" => $email
);
$json = json_encode( $postArray, JSON_PRETTY_PRINT );
$pl4m_url = "api-link";
$ch = curl_init($pl4m_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

post request with json data cross domain

I have been reading tutorials for two days and I really cant understand what are my options. I have a machine with HMI that runs web server (I dont know what kind of web server that is). I can acces HMI tags values trought POST request with json data.
The rquest example look like this
$( document ).ready(function() {
var data0 = {"getTags":["Start_dav","CutON","run_rot_actual"],"includeTagMetadata":true};
var json = JSON.stringify(data0 );
$.ajax({
url: "http://ipaddress/tagbatch",
type: "POST",
dataType: "json",
data: json,
The response is json data.
The problem is of course in cross domain policy. I have no control over the machine and there is no option to set up CORS. I have read about proxy, iframe and yql solutions but as I understand I cant send json data with these workarounds. Is there any way how to send post request with json cross domain?
Thank you for you help
I found a solution. I am using php curl for sending a request.
Here is the working code:
$data = array("getTags" => array("Var1","Var2"), "includeTagMetadata" => false);
$data_string = json_encode($data);
$agent= 'Mozilla/5.0 (Windows; U;Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
//open connection
$ch = curl_init();
$f = fopen('request.txt', 'w'); //writes headers to this file
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,"domainipaddress");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
$tmpfname = dirname(__FILE__).'/cookie.txt'; //saves the cookie from server
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
curl_setopt( $ch, CURLOPT_STDERR, $f );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Connection: keep-alive',
"Keep-Alive: 300"
)
);
//execute post
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
fclose($f);

How to structure JSON to be sent over PHP's cURL

I have an api which works fine when I use POSTMAN, but now that I am trying to send it with PHP I am getting an API error message in response.
Format Error: The exception message is 'The incoming message has an unexpected message format 'Raw'
Which I am sure is related to my data structure. can someone tell me where I am going wrong?
Header
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
JSON Body
{
"accessID": "ASASD22",
"password": "DASD2DQA",
"messages": [
{
"DestinationID": "22D2D2D22D",
"UserMessageID": 133,
"RawPayload": [1,31, 34, 43]
}
]
}
Here is the PHP code I wrote, but returns an error code; can you guys see any issues?
$headers= array('Connection: Keep-Alive','Content-Type: application/json; charset=utf-8','Connection: Keep-Alive');
$data = array(
"accessID" => "ASASD22",
"password" => "DASD2DQA",
"messages" => array(
"DestinationID" => "22D2D2D22D",
"UserMessageID" => "133",
"RawPayload" => "[1,31, 34, 43]"
)
);
$url_send ="http://api.SITE.com/RST-MESSAGE.svc/submit.json/";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
echo " " . sendPostData($url_send, $str_data);
It's difficult to guess, you should check the API's documentation.
But, if the data posted as "JSON Body" is the request you send when it works then you should replicate it exactly in PHP (which you don't):
$data = array(
"accessID" => "ASASD22",
"password" => "DASD2DQA",
"messages" => array(
array(
"DestinationID" => "22D2D2D22D",
"UserMessageID" => "133",
"RawPayload" => array(1, 31, 34, 43),
),
)
);
I did two changes to your data structure. See below the pieces of JSON body that ask for changes in the structure of $data:
"messages": [ { ... } ] - messages is an array of objects, not a single object;
"RawPayload": [1, 31, 34, 43] - RawPayload is an array of integers, not a string;
I found a way to correctly send the entire JSON with in the PHP cURL function
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.SITE.com/Messages.svc/submit.json/" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, '{
"accessID": "ASASD22",
"password": "DASD2DQA",
"messages": [
{
"DestinationID": "22D2D2D22D",
"UserMessageID": 133,
"RawPayload": [1,31, 34, 43]
}
]
}' );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json'));
$result=curl_exec ($ch);
echo $result;
?>
so basically I wrapped the entire JSON into curl_setopt($ch, CURLOPT_POSTFIELDS, $data) and send it that way!

Standard Json objects for different push notification services

Is there actually a required json object which each push service requires. For example I always see the following in every tutorial:
Android:
var notification = "{\"data\":{\"msg\":\"Breaking " + category + " News!\"}}";
Apple:
var alert = "{\"aps\":{\"alert\":\"Breaking " + category + " News!\"}}";
Do these structures have to be kept? or can I send my own custom objects down to the phone?
I think your question is quite specific to certain platform you are trying to send the Push Notification. If you want to just implement the GCM on standard Android Native App.. You can just embed the code in your server implementation.
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;
}
So the answer to your question is No.

Querying Microsoft Dynamics NAV 2013 Odata service as JSON Format

i have read here, that the Odata Webservice also supports the JSON format. But how can I get that?
When I send a request i only get the following format> application/atom+xml
Try something like that:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest)
{
ProcessReturnedEntities(data.d.results);
ProcessReturnedEntity(data.d);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
See this site for a complete example.
For WinJS inside Windows 8 apps with HTML & JS its the following:
WinJS.xhr({
type: "GET",
datatype: "json",
url: 'http://localhost:7048/DynamicsNAV70/OData/P_21/',
headers: {
"Content-type": "application/json; charset=utf-8", "Accept": "application/json" },
}).done(function (data, textStatus, XmlHttpRequest) {
console.log();
},
function (err) {
console.log();
});
Please note the different definition of the header. The values are exactly the same.
To communicate with your OData web services using JSON instead of XML, you really only need to set the following two headers :
Accept: application/json
Content-Type: application/json; charset=utf-8
Alternatively, you could also put ?$format=json at the end of your URL.
This it true no matter what programming language you're using to communicate with Microsoft Dynamics NAV. It works the same for JavaScript, JAVA, Python, Ruby, PHP, ...
Demo code
Here's how to do a basic GET request from PHP :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://<Server>:<WebServicePort>/<ServerInstance>/OData/Company(\'<CompanyName>\')/customer(\'1\')');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
]);
$response = json_decode(curl_exec($ch), TRUE);
echo json_encode($response, JSON_PRETTY_PRINT);
// Close handle
curl_close($ch);
Here's how to do a basic POST request from PHP :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://<Server>:<WebServicePort>/<ServerInstance>/OData/Company(\'<CompanyName>\')/customer');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
"Name" => "This is a test customer",
...
]));
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
]);
$response = json_decode(curl_exec($ch), TRUE);
echo json_encode($response, JSON_PRETTY_PRINT);
curl_close($ch);
Here's how to do a basic PATCH request from PHP :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://<Server>:<WebServicePort>/<ServerInstance>/OData/Company(\'<CompanyName>\')/customer(\'1\')');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
"Name" => "This is a test customer",
...
]));
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
'If-Match: W/"\'' . $etag . '\'"'
// You can get your etag value by doing a get request first
]);
$response = json_decode(curl_exec($ch), TRUE);
echo json_encode($response, JSON_PRETTY_PRINT);
curl_close($ch);
Here's how to do a basic DELETE request from PHP :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://<Server>:<WebServicePort>/<ServerInstance>/OData/Company(\'<CompanyName>\')/customer(\'1\')');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
'If-Match: W/"\'' . $etag . '\'"'
// You can get your etag value by doing a get request first
]);
$response = json_decode(curl_exec($ch), TRUE);
echo json_encode($response, JSON_PRETTY_PRINT);
curl_close($ch);
Note 1
If you need to create / update data, don't forget to Json-encode your POST fields :
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
"Name"=> "This is the name of my new customer"
]));
Using a query string or array instead will generate an error An error occurred while processing this request., which could leave you puzzled for quite a while...
Note 2
For those who don't like working with raw cURL requests, I just uploaded a basic OO wrapper class, which you can find at this gist.