Receiving JSON in php, and using data - php

I have been trying to set up a Shopify webhook (documentation here) through the Shopify admin section. So far I have not been able to grab any of the data being sent in a test webhook using multiple methods, but I know it is sending because I created a Requestbin and have been seeing data come through.
I found this chunk of code here on Stackoverflow.
header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input");
$file = "log.txt";
$current = file_get_contents($file);
$current .= $postdata;
file_put_contents($file, $current);
echo $current;
So far it is the only code I have been able to use to actually see any JSON. But Im not wanting to write the JSON to the "log.txt" file every time the webhook is fired. But once I try to remove or adjust the code in anyway I no longer see any JSON. It seems that I have to write $postdata to a file, and then retrieve the contents to get an array.
Is is possible to access the JSON without having to first write it to another file?

So to begin, my fundamental thought process was flawed on how webhooks worked.
header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input");
$file = "log.txt";
$current = file_get_contents($file);
$current .= $postdata;
file_put_contents($file, $current);
echo $current;
The reason this code needed to write the contents of file_get_contents("php://input") to the text file was because the POST request sent by the Shopify webhook, only hits the page briefly. As soon as you refresh the page, you lose all the POST data...seems obvious I know. That said I needed a way to determine if the JSON Shopify is sending out is working all fine on my server. So I created this...
$json = json_decode(file_get_contents("php://input"));
file_put_contents('./realRequests.txt', $json->id . "\n", FILE_APPEND);
What this does is capture the ID of an order everytime Shopify fires the webhook, and wrties it to a new line in a requests file. That way you know you are able to recive working code from shopify.

Related

Issue while trying to receive message notifications from Slack

About
I am trying to receive message posted on my server as soon as user post message the message in group or channel or direct in slack.
App Status
Code in the verified file where challenge was posted.
header('Content-type: application/json');
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
$data = json_decode(file_get_contents('php://input'), true);
fwrite($myfile, $data["challenge"]);
fclose($myfile);
$json = '{"challenge":' . $data["challenge"] . '}';
echo json_encode(["challenge" => $json]);
Question
Now that the above url has been verified successfully, I am still not able to receive the posted messages. I was expecting messages posted at same url which was used to verify challenge parameter. Is that correct?
Am I missing anything retrieving the messages posted on my server?
Update - 1
Due to some reasons I am not even able to verify the url anymore. My server is not receiving any data. I am trying to save whatever is being posted my side but it is always blank everytime,
I think your assumptions are correct.
According to slack documentation you should be receiving posts with the given payload in this endpoint:
https://api.slack.com/apis/connections/events-api#the-events-api__receiving-events__events-dispatched-as-json
I'm still unsure how are you validating that this isn't the case though, if you kept the code above you would see no result of the post data sent by slack, also if you don't return a response status 200, slack will stop posting to this endpoint after 1 hour.
https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
Can you try adding test.php file something like:
<?php
// get all the POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST") {
file_put_contents('test.json', json_encode($_POST, JSON_PRETTY_PRINT), FILE_APPEND);
// return 200
http_response_code(200);
echo json_encode(["success" => true]);
return;
}
At the very beginning, validate the url again and check if the requests start being saved on test.json.
Alternatively can you check if you web server is routing POST requests to this url?
Try using postman to validate that

How do I get data from Webhook to store in a database?

I am working with a Webhook based of of SendGrid's API v3. The Webhook is completely set up with an endpoint that SendGrid posts to, but I need to be able to receive that parsed data and store it in a database using PHP, but do not know how to do that.
I have worked with APIs before where I initiate the retrieval or POST of data, but when the API server is the one POSTing, how do I catch the data being parsed through the Webhook endpoint? I have some simple thus far, but am really unclear of how to tackle this:
<?php
$json = file_get_contents('https://example.com/webhook.php');
$json_decoded = json_decode($json, true);
$var_dump(json_decoded);
?>
I have tried sending multiple emails to the host, but every time I make this call I return NULL.
Try using the code from this example. This will give you the raw HTTP request body bytes to decode.
<?php
$data = file_get_contents("php://input");
$events = json_decode($data, true);
foreach ($events as $event) {
// Here, you now have each event and can process them how you like
process_event($event);
}
?>
More info on php://input

Dropbox API PHP - notification request is empty

I have what should be a very simple issue to solve, but I can't figure out what is going wrong.
Just started a project to use the new Dropbox API v2 to receive notifications for file/folder changes. Following the steps provided in the documentation provided, but I run into an issue right off the bat.
I've verified the webhook, and I do receive a POST request from Dropbox every time a file is changed, but the POST request just contains an empty array. The code is simple, as I have just begun the project:
// USED for initial verification
/*
$challenge = $_GET['challenge'];
echo $challenge;
*/
$postData = $_POST;
$post_dump = print_r($postData, TRUE);
$fpost = fopen('postTester.txt', 'w');
fwrite($fpost, $post_dump);
fclose($fpost);
$postData is an empty array with sizeOf() 0.
Any ideas?
Here is the updated code with the solution. Very simple fix.
$postData = file_get_contents("php://input");
$post_dump = print_r($postData, TRUE);
$fpost = fopen('postTester.txt', 'w');
fwrite($fpost, $post_dump);
fclose($fpost);
I believe this is because $_POST is only for application/x-www-form-urlencoded or multipart/form-data Content-Types. The payload delivered by Dropbox webhooks is application/json.
It looks like you'll instead want to use $HTTP_RAW_POST_DATA or php://input, depending on your version of PHP.
You can get the raw payload and then json_decode it to get the structured information.

Get and Send file with PHP and RESTful API

One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/

Read Google Calendar API Push Notification in PHP

I have successfully configured Google API Calendar Event Change Push Notifications. My notification page gets called as it should be when I set up the notification or change the calendar.
BUT...being a bit of a PHP dunce I don't understand how to see the content of the notification.
SO (MAIN QUESTION)...how do I get at the variables in the notification? The notification calls my designated page. What are the variables? How are they sent? How are they organized?
There is the larger question of how one should determine the content of a call to a page in PHP. I tried all manner of var_dump, print_r, etc. All I get with:
<?php
$arr = get_defined_vars();
error_log(print_r($arr),0);
?>
is: 1 Yes, just the number 1 in my error_log.
The way I read the respose is:
$content = apache_request_headers();
If you print $content the data is self explenatory. However; for more information hwo to read the header check the link below:
https://developers.google.com/google-apps/calendar/v3/push#receiving
Thanks. it's working. i wrote to file.
$content = apache_request_headers();
get_contents($content);
function get_contents($result) {
$fp = fopen('config.json', 'w');
fwrite($fp, json_encode($result));
fclose($fp);
}

Categories