Standard Json objects for different push notification services - json

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.

Related

How to get results from Udemy Api with search?

I want use udemy api in my website with search field in api.
Udemy gives my this url:
/api-2.0/courses/?search=mysql
which when I use I'm getting an empty array in my results.
However, when I use this url:
/api-2.0/courses/
It works fine, and I'm getting 1000 rows of course details..
Please help me out with the search option, how do I make it work?
<?php
echo "API testing is going on\n";
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Accept:
application/json, text/plain, */*',
'Content-Type: application/json;charset=utf-8',
'Authorization: xxx',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
$URL="https://www.udemy.com/api-2.0/courses?search=mysql',auth=
('xxclientidxx','xxclientsecretxx')'";
$get_data = callAPI('GET',$URL,false);
$response = json_decode($get_data, true);
$file_json=$response['results'];
$fp=fopen('results.json','w');
fwrite($fp,json_encode($response));
fclose($fp);
echo '<br>';
print_r($response['results']);
?>
It would be good if you can check the API docs available from Udemy. Swagger API platform seems available for them.
Please check the URL for the courses API: https://www.udemy.com/developers/affiliate/methods/get-courses-list/

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

Can't create a Folder using BOX API v2.0

function post($url, $params, $headers) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$parent_id = 0;
$name = 'examplefolder';
$params = array('name' => $name => json_encode(array('id' => $parent_id)));
$resp = post('https://api.box.com/2.0/folders', $params, array('Authorization: Bearer ' . $ACCESS_TOKEN_HERE));
When this code executes I got this error in Json format
{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"missing_parameter","name":"parent","message":"'parent' is required"},{"reason":"missing_parameter","name":"name","message":"'name' is required"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Bad Request","request_id":"204107642652b93aceca050"}
Is there anything I'm missing?
Additional note.
I even tried to make the params a query string like this.
name=examplefolder&parent={"id":0}
and this gives me a different error
{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"invalid_parameter","name":"entity-body","message":"Invalid value 'name=examplefolder&parent={\"id\":0}'. Entity body should be a correctly nested resource attribute name\/value pair"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Bad Request","request_id":"154368831052b93bb027779"}
I'm not totally familiar with this language syntax, but it looks to me like the parent object is not declared in your POST body. You need to be sending this:
{"name":NAME, "parent":{"id":"0"}}
You might be able to accomplish that by changing your $params like so:
$params = array('name' => $name, 'parent' => json_encode(array('id' => $parent_id)));
Also, per the documentation the $parent_id should be serialized as a string, not as an integer.
{"name":NAME, "parent":{"parent_id":"0"}}
This worked for me when I was working Angular 1 - angular file upload module.
However it is different with angular2, still working on..
vm.uploader.onBeforeUploadItem = function (item) {
if (!vm.parentFolderId || item.isVersionUpload) return;
item.headers = { Authorization: 'Bearer ' + vm.userToken };
item.formData = {
name: item.file.name,
parent: {
parent_id: vm.parentFolderId
}
};
}

post json data with php curl for multipart/form-data for file upload vía cakephp 2

i want to post json data with php curl for a multipart/form-data with a file upload field.
i tried this in cakephp 2 in a action:
public function json_post(){
$this->autoRender = false;
debug('json post test');
$data = array('Post' => array(
'subject' => 'test subject content',
'body' => 'test body content'
'fileName' => '/Users/mar/Pictures/cow_wall_90.jpg'
));
$data_string = json_encode($data);
$ch = curl_init('http://www.mydomain.com/posts/phone_upload.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//'Content-Type: multipart/form-data',
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
debug($result);
}
fileName is the equivalent for the file upload field in a form.
subject and body are the equivalent for text fields in a form.
i miss something may be in the data array or in the Content-Type but can't find the problem.
thanks for any help, regards, martin
From http://dtbaker.net/web-development/uploading-a-file-using-curl-in-php/:
notice the # infront of the file path, this is the magic part.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"#/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
Seems you were missing the magic part.
You may also switch from cURL to CakePHP's HttpSocket, but that's just personal prefrence.
http://book.cakephp.org/2.0/en/core-utility-libraries/httpsocket.html