How to get data from block.io webhook? - php

I'm using block.io api in my localhost. I've tested basic wallet api which contains generating new address, getting balance of an address, withdraw and etc. All of them works fine but I've stuck at Real-Time Notifications API. I can't get it done. I've set the call back url and I'm using testnet bitcoin network for testing. When a transaction occurs how can I get the data from POSTed notification to my callback.php page?? API sends me JSON data type like this
{
"notification_id": "..."
"delivery_attempt": 1,
"created_at": 1426104819,
"type": "address",
"data": {
"network": "BTC",
"address": "3cBraN1Q...",
"balance_change": "0.01000000", // net balance change, can be negative
"amount_sent": "0.00000000",
"amount_received": "0.01000000",
"txid": "7af5cf9f2...", // the transaction's identifier (hash)
"confirmations": X, // see below
"is_green": false // was the transaction sent by a green address?
}
}
and my callback.php code is this
require_once 'block.io/block_io.php';
$data = json_decode(file_get_contents('php://input'), true);
$type = $data['type'];
$network = $data['data']['network'];
$address = $data['data']['address'];
$balence_change = $data['data']['balance_change'];
$tx = $data['txid'];
$confirmations = $data['confirmations'];
echo 'Type: ' . $type;
echo 'Network: ' . $network;
echo 'Address: ' . $address;
echo 'Balance change: ' . $balance_change;
echo 'Confirmations: ' . $confirmations;
I use testnet to send bitcoins then refresh the page but nothing is returned. The variables are all empty. Please help me to get this done.
Thanks

Related

Why my PHP script does not "see" the webhook from Dialogflow?

I am using DIalogflow (api.ai) to create chat interfaces. I created a webhook from Dialogflow to a simple app containing a php script deployed on Heroku.
Therefore, I placed in the webhook form of Dialogflow the url of my Heroku app which resembles to this: https://my_heroku_app_name.herokuapp.com.
My ultimate goal is to fetch some data from a database (through the php script) and then feed Dialogflow with them. For now, I am only trying to connect the Heroku app (php script) with Dialogflow through a webhook.
The php script of the Heroku app is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'GET'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->metadata->intentName->text;
switch ($text) {
case 'Name':
$speech = "This question is too personal";
break;
default:
$speech = "Sorry, I didnt get that.";
break;
}
$response = new \stdClass();
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
Keep in mind the following:
$method is GET for some reason instead of POST as it is supposed to be from Dialogflow.
if you try to echo any of the variables $requestBody, $json or $text then nothing is printed.
I have tested that the if branch is executed and that the default branch is executed at switch.
Why my PHP script cannot "see" the webhook from DIaloflow and fetch the data from it so as to respond appropriately?
P.S. My question is not a duplicate of Valid JSON output but still getting error. The former is about the input of the php script whereas the latter is about the output of the php script. These two things do not necessarily constitute identical problems.
try to do something like this with some modification in your code.
First, I suggest you to use action instead of using intent name for switch case.
index.php
<?php
require 'get_wardinfo.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'wardinfo':
$param = $input["result"]["parameters"]["number"];
getWardInfo($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_wardinfo.php
<?php
require 'config.php';
function getWardInfo($param){
$wardinfo="";
$Query="SELECT * FROM public.wardinfo WHERE wardno=$param";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$wardinfo= "Here is details that you require: Name: " . $row["name"]. " --- Address: " . $row["address"]. " --- MobileNo: " . $row["contact"];
$arr=array(
"source" => "RMC",
"speech" => $wardinfo,
"displayText" => $wardinfo,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "Have some problem .",
"displayText" => "Have some problem .",
);
sendMessage($arr);
}
}
?>
It seems you know each parameter and all about dialogflow and how it works with PHP arrays and all still if you have confusion in above code or method kindly put a comment.
And I will suggest you don't go for Heroku directly first try it with ngrok it will make your local server live and put the URL as webhook in dialogflow and you can easily debug the errors and all.
I managed to connect Dialogflow to my php script on Heroku.
I made the following changes on my php script (on Heroku) and on Dialogflow which led to this result:
I replaced the condition if($method == 'GET') with the condition if($method == 'POST') so as to anticipate the POST request of Dialogflow.
Keep in mind that until I solved the whole problem I was not receiving any POST request but I GET request so I thought that the POST request from Dialogflow leads to GET request because of a webpage redirection which I could not really see at that moment.
I replaced $text = $json->metadata->intentName->text; with $text = $json->results->metadata->intentName; which was the right json parsing for retrieving the value of intentName. (I have published here the json request from Dialogflow but nobody noticed my mistake)
I published my bot on Dialogflow through its built-in web demo and on Slack. This may sound quite irrelevant but also one person on the Dialogflow forum stated that: "Maybe it should rementioned somewhere. that api.ai98 is not parsing any parameters/values/data to you service untill you bot is published!!" (See the second post here: https://discuss.api.ai/t/webhook-in-php-example/229).

Google maps API key causing issue with file_get_contents() in php

I have a pho script that takes an address and returns the lat/lon. Works fine until I put the google api key at the end of the url. I tested the url in the browser and it works fine there.
This works fine:
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
This causes an error:
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'+&sensor=false+CA&key=[MyAPIKeyHere]');
It causes the error: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
I've seen consulted similar posts such as,
Warning while using file_get_contents for google api , but they weren't much help.
Here is the complete code:
<?php
// Address
$address = '1451 Broadway New York, NY 10036';
// Address from command line
// $address = readline("Enter an address: ");
// $address = str_replace(' ','+',$address);
// Get JSON results from this request
// This url works
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
// This url creates an error
//$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'+&sensor=false+CA&key=[MyAPIKeyHere]');
// Convert the JSON to an array
$geo = json_decode($geo, true);
if ($geo['status'] == 'OK') {
// Get Lat & Long
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
// $address = str_replace('+',' ',$address);
echo "The address ". $address. " has the following coordinates:\n" ;
echo "Lat: ". $latitude. " Lon: ". $longitude. "\n";
?>
Try using this API. It worked for me.
https://maps.googleapis.com/maps/api/geocode/json?address='.$address.'&key=YOUR_API_KEY'

PHP Curl to get ajax data or something like that

I don't know if the question is right, but here is my problem..
I want to crawl this site: https://www.easports.com/fifa/ultimate-team/compete/leaderboards to get the leaderboard data.
When I do so with the following code, I only get the header + footer, but not the leaderboard data.
$client = new HttpClient();
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$client->setUri("https://www.easports.com/fifa/ultimate-team/compete/leaderboards");
$content = $client->send()->getBody();
var_dump($content);
Is there a problem with my curl or can this data not be curled? If so, maybe you got a solution for me ;)
If you open the Developer Tools in your browser you can see which extra requests are done to get the leaderboard filled. You should use the url https://www.easports.com/cgw/api/fifa/fut/leaderboard?platform=xboxone&region=ams&period=curr to get the leaderboard. This returns a JSON in the following layout:
[
{
"rank": 1,
"persona": "persona",
"hasProfile": false,
"wins": 1,
"skill": "6",
"qualified": 0
}]
Using your code this would be:
$client = new HttpClient();
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$client->setUri("https://www.easports.com/cgw/api/fifa/fut/leaderboard?platform=xboxone&region=ams&period=curr");
$content = $client->send()->getBody();
var_dump($content);
Which can then be processed for example with:
$client = new HttpClient();
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$client->setUri("https://www.easports.com/cgw/api/fifa/fut/leaderboard?platform=xboxone&region=ams&period=curr");
$content = $client->send()->getBody();
$leaderBoard = json_decode($content);
foreach($leaderBoard as $member){
echo $member['rank'] . '. ' . $member['persona'] . '(' . $member['wins'] . ' Wins)<br />';
}

How to send json data from advance rest client and then receive in php web API?

I am writing API's in PHP for the ios developer for that I am writing the API that receives the array of items in API firstly I am unable to send the JSON data.
But I get the response that is not valid you can view the image below.
So how can I send the JSON array data and get the response? I had developed many apis by sending one key value pair that works fine but not knows how to send the array of items. Here is the code in am try to get the values.
require_once('db/db_config.php');
$enable_log = 0;
if ($enable_log) {
$data = ' GET DATA ' . print_r($_GET, 1);
$data = ' GET DATA ' . print_r($_FILES, 1);
$data .= ' POST DATA ' . print_r($_POST, 1);
$time = #date('[d/M/Y:H:i:s]');
error_log($time . $data . PHP_EOL, 3, "login.log");
}
//call to helper function
$app_type = request_check();
$token = isset($_REQUEST['token']) ? $_REQUEST['token'] : '';
$employee_id = isset($_REQUEST['employee_id']) ? $_REQUEST['employee_id'] : '';
$order_item_array = isset($_REQUEST['ordered_items']) ? $_REQUEST['ordered_items'] : '';
$decode = (array) json_decode($_REQUEST['ordered_items'], true);
echo "<pre>";print_r($decode);exit;
Thanks in advance.
convert your data into Json and than base 64 and call the url using post you can send a lot of data converting into Json

get coordinates with php

The following code should return with the coordinates of the place, but it returns with a comma only....
<?php
function getCoordinates($address){
$address = str_replace(" ", "+", $address);
$url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";
$response = file_get_contents($url);
$json = json_decode($response,TRUE);
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
}
echo getCoordinates('740 Story Rd San Jose CA 95122');
?>
I have solved half of the problem:
{ "error_message" : "You have exceeded your daily request quota for this API.", "results" : [], "status" : "OVER_QUERY_LIMIT" }
Because I had not set my API KEY i had limited access.
Can anyone show me how can i set my APIkey in php?

Categories