How to capture POST request from another web service - php

I am using Block.io Web Hooks. It says that the notification service requires to communicate through POST requests. It also stated that all notification events will use the following JSON objects structure:
{
"notification_id" : "...", // a unique identifier issued when you created the notification
"delivery_attempt" : 1, // number of times we've tried deliverying this object
"type" : "...", // the type of notification, helps you understand the data sent below
"data" : {
... // the notification data
},
"created_at" : 1426104819 // timestamp of when we created this notification
}
I have provided my callback URL and I saw there is row inserted into my database but the value is blank. Yes I know that my code will insert blank but when I trigger the API it is also insert blank.
<?php
$post = '';
foreach($_POST as $k => $v){
$post .= $k.'='.$v.'&';
}
// save data into database
?>

The webhook returns json and this will not be parsed to the $_POST array by PHP.
Instead, you need to get the string from:
file_get_contents('php://input')
This you can parse yourself. To get an array:
$array = json_decode(file_get_contents('php://input'), true);

Related

Get JSON from a URL by PHP

I have a URL that returns a JSON object like this:
{
"USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
"AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}
URL : https://blockchain.info/ticker
more info : https://blockchain.info/api/exchange_rates_api
I want to get all the data from the first line and echo it and to have it keep requesting it so its live
I have used the examples on git hub
https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md
but it displays all of the data output and you have to refresh it to get it updated
please can some one point me in the right direction
ideally I would end up with something like
15 m Last Buy Sell
USD ($) 7794.87 7794.87 7795.72 7794.02
I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields
How can I do it through PHP?
What you need is a request php page, which will make:
1 - Get data from te site:
$data = file_get_contents('https://blockchain.info/ticker');
2 - decode the json
$decodedData = json_decode($data);
3 - Here you can access it using OOP:
var_dump($decodedData->USD);
The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.
Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.
This Should do it:
<?
$seconds = 5;
function get_live_quote($key){
$json_string = file_get_contents('https://blockchain.info/ticker');
$json_array = json_decode($json_string, TRUE);
$quote = $json_array[$key];
$keys = implode(" ",array_keys($quote));
$values = implode(" ", array_values ($quote));
return "$keys $values \n";
}
while(TRUE){
echo get_live_quote("USD");
sleep($seconds);
}
Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php

i am using a rest API i need to parse a forever changing json result

Okay so here goes i am using a rest api called strichliste
i am creating a user credit payment system
i am trying to grab a users balance by username problems is
my restapi i can only get the blanace via its userid
I have created a bit of php that grabs all the current users and the corresponding id and balance using this below
function getbal(){
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://example.io:8081/user/'
)
);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
}
this is the resulting respinse i get after using this in my main php script
<? getbal(); ?>
result --- #
{
"overallCount":3,
"limit":null,
"offset":null,"entries":[
{"id":1,
"name":"admin",
"balance":0,
"lastTransaction":null
},
{"id":2,
"name":"pghost",
"balance":0,
"lastTransaction":null
},
{"id":3,
"name":"sanctum",
"balance":0,
"lastTransaction":null
}
]
}
as you can see there are only currently 3 users but this will grow everyday so the script needs to adapt to growing numbers of users
inside my php script i have a var with the currently logged in use so example
$user = "sanctum";
i want a php script that will use the output fro gatbal(); and only output the line for the given user in this case sanctum
i want it to output the line in jsondecode for the specific user
{"id":3,"name":"sanctum","balance":0,"lastTransaction":null}
can anyone help
$user = "sanctum";
$userlist = getbal();
function findUser($u, $l){
if(!empty($l['entries'])){
foreach($l['entries'] as $key=>$val){
if($val['name']==$user){
return $val;
}
}
}
}
This way, once you have the list, and the user, you can just invoke findUser() by plugging in the userlist, and the user.
$userData = findUser($user, $userlist);
However, I would suggest finding a way to get the server to return only the user you are looking for, instead of the whole list, and then finding based on username. But thats another discussion for another time.

Problems manipulating JSON data in PHP

I'm not that handy with JSON so here goes. I'm receiving Amazon SNS notifications for bouncing email addresses to a listener (in PHP 5.5) which does:
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
This gives me:
Type => Notification
MessageId => #####
TopicArn => #####
Message => {
"notificationType":"Bounce",
"bounce": {
"bounceSubType":"General",
"bounceType":"Permanent",
"bouncedRecipients":[{"status":"5.3.0","action":"failed","diagnosticCode":"smtp; 554 delivery error: dd This user doesn't have a yahoo.com account (testuser#yahoo.com) [0] - mta1217.mail.bf1.yahoo.com","emailAddress":"testuser#yahoo.com"}],
"reportingMTA":"dsn; ######",
"timestamp":"2014-10-27T16:37:42.136Z",
"feedbackId":"######"
},
"mail": {
"timestamp":"2014-10-27T16:37:40.000Z",
"source":"myemail#mydomain.com",
"messageId":"######",
"destination":["testuser#yahoo.com"]
}
}
I was expecting an associative array all the way down but instead it's an array only at the top level and with JSON strings inside. I've tried everything I can think of, including json_decoding further parts of the array, but I'm struggling to access the data in a simple way. What I need is the "destination" email address which should be in $object['Message']['mail']['destination'][0].
Can anyone point out what I'm doing wrong here? Thanks.
It looks like $object['Message'] is also json encoded. Perhaps because it's using some generic container format for service call results. Try this
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
//Message contains a json string
$object['Message'] = json_decode($object['Message'], true);
//Then access the structure using array notation
echo $object['Message']['mail']['destination'][0];

Facebook API Real Time update v2.2 read update

I was working in php
I did the work and sottoiscrizione
facebook api is v.2.2
but now there is a problem
how do I read the updates of the feeds I get ?
The code is :
<?php
//file of program
require_once('LoginFb.php');
require_once('FbClass.php');
require_once('dbClass.php');
require_once('FacebookClass.php');
//receive a Real Time Update
$method = $_SERVER['REQUEST_METHOD'];
// In PHP, dots and spaces in query parameter names are converted to
// underscores automatically. So we need to check "hub_mode" instead
// of "hub.mode".
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == 'thisisaverifystring') {
echo $_GET['hub_challenge']; //print the code on the page that Facebook expects to read for confirmation
} else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
// Replace with your own code here to handle the update
// Note the request must complete within 15 seconds.
// Otherwise Facebook server will consider it a timeout and
// resend the push notification again.
$testo=json_decode($updates["entry"]);
$var=fopen("nome_file.txt","a+");
fwrite($var, "ciao");
fwrite($var, $updates );
fclose($var);
error_log('updates = ' . print_r($updates, true));
}
?>
In the above file "$update" contains an updated feed, but how to extract?
Note: subscription WORKS and updates arrived on my server.
Help me please :)
According to the Facebook documentation [link]:
Note that real-time updates only indicate that a particular field has changed, they do not include the value of those fields. They should be used only to indicate when a new Graph API request to that field needs to be made.
So, you don't get the updated data instead you get the updated feild name. On receiving an update, you should extract the changed field (I have explained this below) and make a new Graph API request to that field. Finally, you will get the updated field data.
How to extract the user name and changed field?
You receive this:
{"entry":[{"id":"****","uid":"****","time":1332940650,"changed_fields":{"status"]}],"object":"user"}
where "id" is my pageId and "changed_fields" is an array of changed fields.
You can extract these as following:
$entry = json_decode($updates["entry"]); <br>
$page = json_decode($entry["uid"]); <br>
$fields = json_decode($entry["changed_fields"]);
Hope it helps! :)
No function -> the respose contain a array of array the correct code is:
$json = json_decode($updates["entry"][0]["uid"], true);

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Categories