PHP: How to capture data from Livehealth Webhook API - php

You need to place this code first in your end file (which you shared with the live health API team.)
They will enable access to this file and once any report will submit, data will be sent on endfile.
you need to place this below code in that file and you will get a file created in the same root and will see data received from live health API.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// decode json
$object = json_decode($json,true);
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
die(header('HTTP/1.0 415 Unsupported Media Type'));
}
$time = time();
$fname ='_callback.test.txt';
file_put_contents($time.$fname , print_r($object, true));
$jdonFile = time().'_json_callback.test.txt';
$filename = $jdonFile;
$handle = fopen($filename, "w");
fwrite($handle, $json);
fclose($handle);
}

Using this code i was able to get data and i store this data into txt file. you can insert this data in sql database.
just copy and past the same code and your script will execute.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// decode json
$object = json_decode($json,true);
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
die(header('HTTP/1.0 415 Unsupported Media Type'));
}
$time = time();
$fname ='_callback.test.txt';
file_put_contents($time.$fname , print_r($object, true));
$jdonFile = time().'_json_callback.test.txt';
$filename = $jdonFile;
$handle = fopen($filename, "w");
fwrite($handle, $json);
fclose($handle);
}

Related

Json decode returns nothing

I am working with Webhook to receive data, so I can store it into database, so I got data as Json and tried to decode it, so I can retrieve each one using json_decode and save them in a text file but I got nothing the file was empty
so here is me code :
<?php
require_once('vendor/autoload.php');
$payload = #file_get_contents('php://input');
if (isset($payload) && !empty($payload)) {
$data = json_decode($payload, true);
$myFile2 = "file.txt";
$myFileLink2 = fopen($myFile2, 'w+') or die("Can't open file.");
$newnbord = $data;
fwrite($myFileLink2, $newnbord);
fclose($myFileLink2);
}
and this is an example of data I received through webhook :
{"accountingCurrency":"USD","address1":"test address","billedCurrency":"EUR","billedRecurringPrice":"0.00","bin":"444444","cardType":"VISA","city":"testcity","country":"FR","initialPeriod":"30","lastName":"test","timestamp":"2020-11-12 06:05:49","username":"llllll","threeDSecure":"NOT_APPLICABLE"}

Get incoming webhook of woocommerce

I'm trying to receive a JSON of a woocommerce webhook in a tracker.php to manipulate the content, but something is wrong because it doesn't save anything in $_SESSION. This is my code ....
(!isset($_SESSION))? session_start() : null;
if($json = json_decode(file_get_contents("php://input"), true)) {
$data = json_decode($json, true);
$_SESSION["json"] = $data;
} else {
var_dump($_SESSION["json"]);
}
tested the webhook with http://requestbin.fullcontact.com/ and received the content. here a capture
issue is in this line
$data = json_decode($json, true);
here $json is array and jsondecode expect string.
here is code which will work.
(!isset($_SESSION))? session_start() : null;
if($json = json_decode(file_get_contents("php://input"), true)) {
//this seection will execute if you post data.
$_SESSION["json"] = $json;
} else {
//this will execute if you do not post data
var_dump($_SESSION["json"]);
}

PHP header('Content-Type: application/json'); is not working

Sorry if it is repeated question, already tried every single suggestion in google and StackOverflow.
For some reason, my response header always comes as Content-Type:text/html; charset=UTF-8.
I want content type to be json (Content-Type:application/json), Not sure what am I doing wrong. here is my code
<?php
header('Access-Control-Allow-Origin: *');
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/api/csvtojson.php');
require_once(__ROOT__.'/api/retrieve-login-data.php');
require_once(__ROOT__.'/api/access-control.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
$filename = $decoded['filename'];
// open csv file
if (!($fp = fopen($filename, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024",",");
// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",",")) {
$json[] = array_combine($key, $row);
}
// release file handle
fclose($fp);
// encode array to json
header('Content-Type: application/json;charset=utf-8');
echo (json_encode($json, JSON_PRETTY_PRINT));
Response:
I had the same problem. This occurs because in one php file i had several
section.
======== File.php =========
<?php
//some code
?>
<?php
//some other code
?>
===========================
I've fixed it by mergin the code within the one tag only .
test this way :
ContentType : "application/x-www-form-urlencoded"
Please check if there is no warning before this line:
header('Content-Type: application/json;charset=utf-8');

JSON post method in php

I don't get what do I do wrong when I try to get my values from post method from angular to php, it seems that everything is correct but then I am not able to see any values to postman/return the correctly.
this is my php method with all my attempts:
public function created()
{
$json = file_get_contents('php://input');
$json_string_in_array = array($json);
$json_array =json_decode($json_string_in_array[0]);
var_dump($json_string_in_array);
var_dump($json_array);
//return $json_array;
// $data = json_decode(file_get_contents('php://input'), true);
// $data = json_encode(file_get_contents("php://input"));
// $request = json_decode($data);
// var_dump($data);
// return $data;
// return $request;
// $json = file_get_contents('php://input');
//$obj = json_decode($json);
// get the raw POST data
// $rawData = file_get_contents("php://input");
// this returns null if not valid json
// return response()->json($rawData);
// DatabaseModel::DatabaseModel($json_array);
}
what I am trying to do is get that data and then send it to DatabaseModel in order to add it to database.
First you header, content-type, should be application/json. Are you manually setting the headers in angular? I am pretty sure angular will detect (or at least it is the default) the content type if its not set so in your case it would be application/json
<?php
$json = file_get_contents('php://input');
$request = json_decode($json);
$name = $request->name;
$email = $request->email;
# etc
?>

Yahoo Finance: 404 response code (PHP)

I'm using PHP to grab CSV files from Yahoo Finance based on an array of stock tickers.
My code is simple and is as follows:
$file = 'http://ichart.yahoo.com/table.csv?s='.$this->symbol.'&a='.$a.'&b='.$b.'&c='.$c.'&d='.$d.'&e='.$e.'&f='.$f.'&g='.$g.'&q=q&y=0&z='.$this->symbol.'&x=.csv';
$handle = fopen($file, "r");
//Then use fgetcsv to grab data,
fclose($handle);
I'm getting the following error:
Warning: fopen(http://ichart.yahoo.com/table.csv?s=ANA.L&a=2&b=16&c=2016&d=2&e=19&f=2016&g=d&q=q&y=0&z=ANA.L&x=.csv): failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in y.php on line x
Manually entering the previous URL (http://ichart.yahoo.com/table.csv?s=ANA.L&a=2&b=16&c=2016&d=2&e=19&f=2016&g=d&q=q&y=0&z=ANA.L&x=.csv) gets the CSV file with no problem, so I'm confused as to why I'm getting a 404 response code.
EDIT:
I have added a cURL request prior to using fopen. This is to check for a 404 response code. I am not getting any 404 response codes from the cURL but still getting the same error as mentioned above.
$curlhandle = curl_init($file);
curl_setopt($curlhandle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($curlhandle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curlhandle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
echo "404:".$this->symbol."<br>";
curl_close($curlhandle);
return null;
break;
} else {
curl_close($curlhandle);
$handle = fopen($file, "r");
}
You need to URL encode all of your params otherwise you can have an invalid URL...
$file = 'http://ichart.yahoo.com/table.csv?s='.urlencode($this->symbol).'&a='.urlencode($a).' //etc
Try changing ichart.yahoo.com to ichart.finance.yahoo.com. i.e.
file = 'http://ichart.finance.yahoo.com/table.csv?s='.$this->symbol.'&a='.$a.'&b='.$b.'&c='.$c.'&d='.$d.'&e='.$e.'&f='.$f.'&g='.$g.'&q=q&y=0&z='.$this->symbol.'&x=.csv';
$handle = fopen($file, "r");
//Then use fgetcsv to grab data,
fclose($handle);

Categories