According to the author of faye i can send messages from any platform
and the format to post a message with curl is:
curl -X POST http://192.168.1.101:8000/faye -H 'Content-Type:
application/json' -d '{"channel":"/foo","data":{"hello":"world"}}'
I format the previous line to be used in php
$data = array("channel" => "/one", "result" => "Hello World from PHP!!");
$data_string=json_encode($data);
$ch = curl_init('http://192.168.1.101:8000/faye');
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:application/json','Content-Length:'strlen($data_string)));
$result = curl_exec($ch);
Somehow the subscriber to channel one DOES not GET the result
the publish function in java script works seamlessly (see line below)
var publication = client.publish('/one',{ result: 'Hello World from JS'});<br/>
Please let me know what is missing or my mistake thanks
This one works for me:
$data = array("channel" => "/one", "data" => array ("result"=>"HelloWorld from PHP!!"));
$data_string=json_encode($data);
$ch = curl_init('http://localhost:8000/faye');
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:application/json'));
echo $result = curl_exec($ch);
Related
I am trying to use the zoho inventory api and converting thier sample curl code for use in php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://inventory.zoho.com/api/v1/salesorders");
$vars = array(
"authtoken" => "",
"organization_id" => "",
"JSONString" => '{
"customer_id": 4815000000044080,
}'
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Zoho-authtoken ',
'Content-Type: application/json;charset=UTF-8',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);
On the page I get this response
{"code":4,"message":"Invalid value passed for JSONString"}
The original code from the docs is
$ curl https://inventory.zoho.com/api/v1/salesorders?authtoken=ba4604e8e433g9c892e360d53463oec5&organization_id=10234695
-X POST
-H "Authorization: Zoho-authtoken ba4604e8e433g9c892e360d53463oec5"
-H "Content-Type: application/json;charset=UTF-8"
-d JSONString='{
"customer_id": 4815000000044080,
}'
I have tried various google searches and it seems that a lot of people have had this same issue and there is no answer given for it yet.
I believe I am trying to add the JSONString in the wrong way
What is the correct way to send the JSONString in php using curl?
Following is the C# code that will not give the following error:
"{"code":4,"message":"Invalid value passed for JSONString"}"` error.
I use a servise http://httpbin.org/post to look, how my post query looks for zoho.
and find an error with symbols \ufeff before JSONString, this is BOM encoding.
So, i change encoding and all right.
Look Example
I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
I want to understand what is web-push and how can i use for my projects...
Have found this example https://mobiforge.com/design-development/web-push-notifications
But always getting an error when try to send notification via Firebase Cloud Messaging (FCM is the new version of GCM)
{"multicast_id":6440031216763605980,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
What it means "InvalidRegistration"? What i'm doing wrong?
My php curl, but i am sure that there is no problem here
$link = "https://gcm-http.googleapis.com/gcm/send";
$header = array();
// $header[] = "Content-length: 0";
$header[] = "Content-type: application/json";
$header[] = "Authorization: key=AIzaSy...";
$contentArray = array(
"collapse_key" => "All",
"registration_ids" => array(
"gAAAAABX06BLKhA4n1yHNlsyzu02wxsDjZf89oxIljwM4ZdLpMZU7ty64TFEYahPQZaTmCeYlJo-WDWnfFHOKXzKURhNtRWmN0OgBgn9hJdmgatSGoiTkt69TeJpiD8F034WOr5HMEG2",
),
"data" => array(
"title" => "This is a Title",
"message" => "This is a GCM Topic Message!"
)
);
$jsonData = json_encode($contentArray);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $link);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$string = curl_exec($ch);
echo $string;
$data['curl'] = curl_errno($ch);
if(!curl_errno($ch) && !strpos($string, "503"))
$data = array_merge($data, explode("\n", $string));
curl_close($ch);
?><pre><? print_r($data); ?></pre><?
some from Cosole.log
ServiceWorker registration successful with scope: https://.../app/
PushSubscription { endpoint="https://updates.push.ser...rjYvTTapou7WcEDgu3V7IOY", options=PushSubscriptionOptions, getKey=getKey(), ...}
PushSubscription { endpoint="https://updates.push.ser...rjYvTTapou7WcEDgu3V7IOY", options=PushSubscriptionOptions, getKey=getKey(), ...}
gAAAAABX06OYvBIk4q2rRF3AsE6UwRYUpzpZ0jpuiWz6TRrSptb8_cBKjy8Ci-_u5UtAyiGfAYJ_ycYnJjoukSuez7BN6UnSX-GL_EWNAWzEpAVMhCT2wrjYvTTapou7WcEDgu3V7IOY
Please try checking the subscription ID that you used.
As mentioned in Check the response,
If the response shows an invalid registration error, check the subscription ID you used.
As discussed further in making a request to GCM, make sure to use your own API key and subscription ID when you run the cURL command.
For more information, please check the documentation on how to send a request from the command line for GCM to push a message.
It is not working. I have been trying a lot times. here below is how I tried in POSTMan
From my experience, the registration_id you are using seems to be from a subscription on a Firefox browser. But yet you're trying to send it to the Chrome push server.
A Chrome registration_id should look like that:
APA91bGdUldXgd4Eu9MD0qNmGd0K6fu0UvhhNGL9FipYzisrRWbc-qsXpKbxocgSXm7lQuaEOwsJcEWWadNYTyqN8OTMrvNA94shns_BfgFH14wmYw67KZGHsAg74sm1_H7MF2qoyRCwr6AsbTf5n7Cgp7ZqsBZwl8IXGovAuknubr5gaJWBnDc
It's a pretty new technology and earlier versions codes are still available on the google developer platform, so it's not really easy to understand what to do. I'm still experimenting with it.
Check this codelab it's a good example to understand the basics.
I would like to share my answer in this post too.
Check https://stackoverflow.com/a/40447040/4677062 for the same invalid registration id issue.
Its resolved. Works as expected.
I'm creating a search functionality for my website and I'm using Parse.com for storing data. I have a class Posts with a "plainContent" column which stores the content of my article in plain text format. I've found this article:
http://blog.parse.com/learn/engineering/implementing-scalable-search-on-a-nosql-backend/
which is very useful. I've added the cloud code which splits my plain text into single words and puts them into an array. Now I have my Posts with an extra column "words" which stores an array with all the single words for article's content. I got the the step of retrieving data now but the problem is the following code:
curl -v -X GET
-H "X-Parse-Application-Id: ${APPLICATION_ID}"
-H "X-Parse-REST-API-Key: ${REST_API_KEY}"
-G
--data-urlencode 'where={"hashtags":{"$all":["#parse", "#ftw"]}}'
"https://api.parse.com/1/classes/Post"
precisely the --data-urlencode row which in my case would be:
--data-urlencode 'where={"words":{"$all":["word1", "word2"]}}'
I can't create the curl query with PHP. What exactly is the $all variable in the example?
Here's my php script:
$url = 'https://api.parse.com/1/classes/Posts?';
$headers = array(
"Content-Type: application/json",
"X-Parse-Application-Id: " . $MyApplicationId,
"X-Parse-REST-API-Key: " . $MyParseRestAPIKey
);
$query = urlencode('where={"words":{"$all":["parseobjectcontains", "compatible"]}}');
$ch = curl_init($url.$query);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($handle);
curl_close($handle);
$array = json_decode($data);
var_dump($array);
This script returns all results without filtering.
The question is how to build this sentence to reflect the example in the article from the link? What should be that $all variable?
$query = urlencode('where={"words":{"$all":["parseobjectcontains", "compatible"]}}');
EDIT
I had an error in my script:
$ch = curl_init($url.$query);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
Correction:
$handle = curl_init($url.$query);
//$handle = curl_init();
//curl_setopt($handle, CURLOPT_URL, $url);
Assuming $all is needed as it is you have shown in your code (as per parse.com). Here are few catch.
1) You are doing urlencode over the whole request parameter. But actually you have to do it over the value of where in your example. So change it as below:
$query = 'where='.urlencode('{"words":{"$all":["parseobjectcontains", "compatible"]}}');
2) The data you are posting here is not json, it is actually key=value pared data. So remove Content-Type: application/json thing from your code.
That's all!
I has follow step on Path API about how to Authentication User. In the tutorial auth process, user is begin to redirect to the following URL and prompt to grant access:
https://partner.path.com/oauth2/authenticate?response_type=code&client_id=THE_CLIENT_ID
And after that, server will give response as authorization code via URL Address (i have complete this step and got the code).
As from docs explain, Code is should be exchanged for an access token using /oauth2/access_token as long with Client ID and Client Secret (get access_token)
But i don't have any clue how to POST data via cURL to the server, i has try so many curl_setopt() option and combination, but it still give me a nothing.
From the Docs, Request is look like this:
POST /oauth2/access_token HTTP/1.1
Host: partner.path.com
Content-Type: application/x-www-form-urlencoded
Content-Length: <LENGTH>
grant_type=authorization_code&client_id=CLIENT&client_secret=SECRET&code=CODE
And cURL format like this:
curl -X POST \
-F 'grant_type=authorization_code' \
-F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'code=CODE' \
https://partner.path.com/oauth2/access_token
And server will give response like this:
HTTP/1.1 201 CREATED
Content-Type: application/json
Content-Length: <LENGTH>
{
"code": 201,
"type": "CREATED"
"reason": "Created",
"access_token": <ACCESS_TOKEN>,
"user_id": <USER_ID>,
}
To perform a POST request in PHP with cURL, you can do something like:
$handle = curl_init('https://partner.path.com/oauth2/access_token');
$data = array('grant_type' => 'authorization_code', 'client_id' => 'CLIENT', 'client_secret' => 'SECRET', 'code' => 'CODE');
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($handle);
You can then use json_decode($json_encoded) to get an associative array from the server response.
Not sure if you have figured this out yet or not since i see it was from awhile ago, but I just had this problem and this is how I figured it out.
$code = $_GET['code'];
$url = 'https://YourPath/token?response_type=token&client_id='.$client_id.'&client_secret='.$client_secret.'&grant_type=authorization_code&code='.$code.'&redirect_uri='.$redirect_uri;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST,true);
$exec = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info);
curl_close($ch);
$json = json_decode($exec);
if (isset($json->refresh_token)){
global $refreshToken;
$refreshToken = $json->refresh_token;
}
$accessToken = $json->access_token;
$token_type = $json->token_type;
print_r($json->access_token);
print_r($json->refresh_token);
print_r($json->token_type);
Hope that helps
addition to Fox Wilson answer:
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);