PHP Post JSON value to next page - php

I want to grab json string, set objects and httpheaders in 1.php (for example). Get these values in JSON format and display in next page (2.php).
I tried to use CURL method. I m very new to PHP. Not sure whether CURL method is the best to POST data.. Session or cookie method no need. Is there any other method other than this to POST data?
1.PHP:
<?php
$data = array($item_type = "SubscriptionConfirmation";
$message = "165545c9-2a5c-472c-8df2-7ff2be2b3b1b";
$Token = "2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d6";
$TopicArn = "arn:aws:sns:us-east-1:123456789012:MyTopic";
$Message = "You have chosen to subscribe to the topic arn:aws:sns:us-east-1:123456789012:MyTopic.\nTo confirm ";
$SubscribeURL = "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:MyTopic&Token=2336412f37fb6";
$Timestamp = "2012-04-26T20:45:04.751Z";
$SignatureVersion = "1";
$Signature = "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=";
$SigningCertURL = "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem";);
$json_data = json_encode($data);
$ch = curl_init('http://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CAINFO, "/path/to/CA.crt");
curl_setopt($ch, CURLOPT_HTTPHEADER,array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
$result = json_decode($output);
echo $result;
?>
2.PHP:
How to post 1.php json value to 2.php.. either through CURL or other posting method.. Tried my best.. cant able to figure out the solution.
Thanks

1.php
$data = array(
'test' => 'data',
'new' => 'array');
$json_data = json_encode($data);
// Only work with your example, curl need full url
$request_url = 'http://teshdigitalgroup.com/2.php';
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
print_r($output);
AND 2.php
print_r(file_get_contents('php://input'));
// Response 1.php's request HTTP Header
function parseRequestHeaders() {
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}
print_r(parseRequestHeaders());

Related

Binance REST API - Placing a PHP Order (POST) via Query String

I am struggling using Binance's REST API. I have managed to get working GET request via query string such as pinging the server, ticker information, etc. My challenge now is performing POST request via query string using cURL. I have been scraping code from various places and referring back to the API to get pieces to work but I am unsure as to why I am getting this error returned from the result... {"code":-1102,"msg":"Mandatory parameter 'signature' was not sent, was empty/null, or malformed."}
(ERROR SHOWN ON WEBPAGE). I echo out the signature and its a load of gibberish so I would believe that the hash_hmac performed at the top would be working, but honestly I got pretty lucky making the GET request work. Does anyone have any suggestions as to why this would be broken? Thanks!
$apikey = "MYKEY";
$apisecret = "MYSECRET";
$timestamp = time()*1000; //get current timestamp in milliseconds
$signature = hash_hmac('sha256', "TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp, $apisecret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.binance.com/api/v3/order/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
As per their API docs:
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
You are sending the signature via neither of these methods and are instead sending it through the header.
Change this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
To this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=" . $timestamp . "&signature=" . $signature);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey));
<?php
$secret = "F................";
$key = "D.................";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v3/account?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
?>
Here is an example, using php-curl-class
// Variables
// url, key and secret is on separate file, called using require once
$endPoint = "/api/v3/order/test";
$coin = "BTC";
$fiat = "EUR";
$symbol = $coin . "" . $fiat;
$side = "BUY";
$type = "LIMIT";
$timeInForce = "GTC";
$quantity = 1;
$price = 10000;
$timestamp = time();
// Constructing query arrays
queryArray = array(
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"timeInForce" => $timeInForce,
"quantity" => $quantity,
"price" => $price,
"timestamp" => $timestamp*1000
);
$signature = hash_hmac("sha256", http_build_query($queryArray), $secret);
$signatureArray = array("signature" => $signature);
$curlArray = $queryArray + $signatureArray;
// Curl : setting header and POST
$curl->setHeader("Content-Type","application/x-www-form-urlencoded");
$curl->setHeader("X-MBX-APIKEY",$key);
$curl->post($url . "" . $endPoint, $curlArray);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
}
$order = $curl->response;
print_r($order);
I had the same problem, and nothing of above doesn't helped.
So I finaly figured out how to make order on my way.
So, maybe this helps someone.
function Kupovina($buy_parametri) {
$key = "xxxxxxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$s_time = "timestamp=".time()*1000;
$timestamp = time()*1000; //get current timestamp in milliseconds
$sign = hash_hmac('sha256', $buy_parametri."&timestamp=".$timestamp, $secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.binance.com/api/v3/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $buy_parametri."&".$s_time."&signature=".$sign);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$key));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$buy_parametri = "symbol=BTCUSDT&type=market&side=buy&quantity=0.00086";
Call function:
Kupovina($buy_parametri);

How to parse json output?

I tried to parse this url
https://esewa.com.np/epay/transdetails?pid=AddFund-C-11970239- 9625960&amt=100&scd=nprhosting&rid=00C3LF0
{
"code":"00",
"msg":"Success",
"txnDetail": {
"txnCode":"00C3LF0",
"amt":"100.0",
"date":"2015-07-16 23:44:18.0",
"payerId":"dipsnwc#gmail.com",
"status":"COMPLETE",
"pid":"AddFund-C-11970239-9625960",
"txAmt":"0",
"psc":"0",
"pdc":"0"
}
}
Like this
$fields = array(
'pid' => "AddFund-C-11970239-9625960";
'amt' => "100.0";
'scd' => "nprhosting";
'rid' => "00C3LF0";
);
$field2 = json_encode($fields);
$url = "https://esewa.com.np/epay/transdetails";
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $field2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($field2))
);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
//
///Deocde Json
$data = (json_decode($result, true));
var_dump($data);
$message =$data['msg'];
$status =$data['txnDetail']['status'];
echo $message;
echo $status;
Still no output ??
I tried it and worked..
$url = 'https://example.com/epay/transdetails?pid=AddFund-C-11970239-9625960&amt=100&scd=nprsite&rid=00C3LF0';
$data = file_get_contents($url);
$arr = json_decode($data,true);
echo $arr['txnDetail']['status'];
print_r($arr);
Array is incorrect, remove ::
$fields = array(
'pid' => "AddFund-C-11970239-9625960",
'amt' => "100.0",
'scd' => "nprhosting",
'rid' => "00C3LF0"
);
and try
$url = "http://examplesite.com/epay/transdetails?" . http_build_query($fields);
Chuck the POSTFIELDS and HTTPHEADER
curl_setopt($ch, CURLOPT_POST, false);
The parameters are expected to be as GET(as per the link you have provided), keep it simple.
Also check this answer for better understanding on how to send HTTP GET request with PHP CURL.

CoinBase "invalid signature" PHP Buy API Request

I have looked over the code many times but whenever I send request to API it returns "message":"invalid signature"
I am thinking it has to do with hashing the body, possibly. I'm new to PHP and its my first project. :)
Anyone see an error? Thanks.
<?php
$arr = array('size' => ".01", 'price' => '240', 'side' => 'sell',
'product_id' => 'BTC-USD');
$output = json_encode($arr);
echo json_encode($arr)."<br/>";
$key = "f23612b06cb4d020cda7e04b1ae6ef9a";
$secret = "RENqodtuTCn4v7g7Pn/FFdQAIKReVXGayNPrNN/Zb7AjATI0hP4R0MCDD5RqnDu60qTZ5Qry329fFu7kcObGBw==";
$passphrase = "tradebot";
$time = time();
$url = "https://api.gdax.com/orders";
$data = $time."POST"."/orders";
echo $data . "<br/>";
$hashinput = "$output"."$data";
$sign = base64_encode(hash_hmac("sha256", $hashinput, base64_decode($secret), true));
echo $sign . "<br/>";
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
var_dump($headers);
echo $url;
static $ch = null;
if (is_null($ch)) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'local server');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $output);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
echo $res;
}
replace
$hashinput = "$output"."$data";
with
$hashinput = "$data"."$output";
and replace
curl_setopt($ch, CURLOPT_POST, $output);
with
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
(from Coinbase Community forum)

Correct way to send JSON DATA via POST php

Is the correct way to send $json data via CURL? in PHP,
I have my $json data in one php, I can send the data information via POST using CURL to my api,??
Do you have some examples, thanks a lot!!
Yes. You can do.
Eg.
// $json_string : Your json String
$ch = curl_init('http://api.example.com/post');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_string))
);
$result = curl_exec($ch);
Please find before post:
http://bavotasan.com/2011/post-url-using-curl-php/
In some key on $data, put your $json.
Example
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
$json = json_encode($your_json); //Your json data
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan",
"json" => $json
);
post_to_url("http://yoursite.com/post-to-page.php", $data);

How to post data using curl and get reponse based on posted data

Here is my code to POST data:
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
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);
curl_close($ch);
$json_result = json_decode($result, true);
?>
<p>Your confirmation number is: <strong><?php echo $json_result['ConfirmationCode']; ?></strong></p>
Whereas on domain/server curl.php file code as under:
<?php
// header
header("content-type: application/json");
if($_POST):
echo json_encode(array('ConfirmationCode' => 'somecode'));
else:
echo json_encode(array('ConfirmationCode' => 'none'));
endif;
?>
But it always return 'none'. Am I missing something?
The actual problem is in grabbing it..
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
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);
curl_close($ch);
echo $result;
//$json_result = json_decode($result, true);
?>
your code for curl.php
<?php
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
/*if($rawData):
echo json_encode(array('ConfirmationCode' => 'somecode'));;
else:
echo json_encode(array('ConfirmationCode' => 'none'));
endif;*/
?>
Since You are sending the data as raw JSON in the body, it will not populate the $_POST variable
Hope this will help you
The function on this link will work.
<?php
function post_to_url($url, $data) {
$fields = '';
foreach ($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
return $result;
}
$data = array(
"name" => "new Name",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
$surl = 'http://mydomain.com/curl.php';
echo post_to_url($surl, $data);
?>
Whereas, on curl.php
<?php
file_put_contents('abc.text', "here is my data " . implode('->', $_POST));
if ($_POST['name']):
print_r($_POST['name']);
endif;
?>
The "correct" Content-Type header for a POST request should be application/x-www-form-urlencoded, but you overrode it with application/json (which is only needed from the server side).
Change your code to below:
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true); // no need to use custom request method
// ----- METHOD #1: no need to "stringify"
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_array);
// ----- METHOD #2: or if you really like to JOSN-ify
curl_setopt($ch, CURLOPT_POSTFIELDS, array("json"=>$data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* ------ this will be handled by PHP/cURL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
*/
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
?>

Categories