Cannot retrieve JSON POST via PHP: cURL - php

I tried implementing the following PHP code to POST JSON via PHP: cURL (SOME FORCE.COM WEBSITE is a tag that signifies the URL that I want to POST):
$url = "<SOME FORCE.COM WEBSITE>";
$data =
'application' =>
array
(
'isTest' => FALSE,
key => value,
key => value,
key => value,
...
)
$ch = curl_init($url);
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POST, true);
//Send blindly the json-encoded string.
//The server, IMO, expects the body of the HTTP request to be in JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array
(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string)
)
);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
echo '<pre>';
echo $_POST;
$jsonStr = file_get_contents('php://input'); //read the HTTP body.
var_dump($jsonStr);
var_dump(json_decode($jsonStr));
echo '</pre>';
The output of the above is the following:
"Your TEST POST is correct, please set the isTest (Boolean) attribute on the application to FALSE to actually apply."
Arraystring(0) ""
NULL
OK, the above confirms that I formatted the JSON data correctly by using json_encode, and the SOME FORCE.COM WEBSITE acknowledges that the value of 'isTest' is FALSE. However, I am not getting anything from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". I decided to just ignore that fact and set 'isTest' to FALSE, assuming that I am not getting any JSON data because I set 'isTest' to TRUE, but chaos ensues when I set 'isTest' to FALSE:
[{"message":"System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing body, need at least one of html or plainText: []\n\nClass.careers_RestWebService.sendReceiptEmail: line 165, column 1\nClass.careers_RestWebService.postApplication: line 205, column 1","errorCode":"APEX_ERROR"}]
Arraystring(0) ""
NULL
I still do not get any JSON data, and ultimately, the email was unable to be sent. I believe that the issue is resulting from an empty email body because there is nothing coming from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". Can you help me retrieve the JSON POST? I would really appreciate any hints, suggestions, etc. Thanks.

I solved this question on my own. I was not sure if I was doing this correctly or not, but it turns out that my code was perfect. I kept refreshing my website, from where I am POSTing to SOME FORCE.COM WEBSITE. I believe that the people managing SOME FORCE.COM WEBSITE were having issues on their end. Nothing was wrong with what I did. For some reason, I got a code 202 and some gibberish text to go along with it. I would be glad to show the output, but I do not want to POST again for the sake of the people managing SOME FORCE.COM WEBSITE that I am POSTing to. Thank you guys for your help.

Related

PHP : cURL is printing the result on it's own without specifying it

Long story short, I'm trying to connect to PayPal sandbox API
,it's getting a response without errors
my issue is it's printing the response without specifying it for some reason, I don't know where that response is stored, it's just inserted automatically in the page
code :
[CONTENT HERE]
$paypal_api_sandbox = 'https://api-m.sandbox.paypal.com/v1/oauth2/token';
$curl = curl_init($paypal_api_sandbox);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($curl,CURLOPT_POSTFIELDS,'grant_type=client_credentials');
curl_setopt($curl , CURLOPT_USERPWD ,'USER:PASS');
$res = curl_exec($curl);
[CONTENT HERE]
fields are :
USER - My client id
PASS - secret key
print_r($res) // returns 1
Full output :
[CONTENT]
['content':'PayPal response printed automatically on the page']
[CONTENT]
1
Where's the leak ?

How can I get an object out of more than one JSON array in PHP?

I'm new to StackOverflow, so I apologize if I'm not formatting this correctly. I'm using the GitHub API and my goal is to get a list of a user's repositories in a dropdown form that they can select from.
Let's say the repository list URL is https://api.github.com/users/MY_GITHUB_USERNAME/repos (The way I sat things up I can get the repo URL by doing $userdata->repos_url). When I use the following:
$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL, $userdata->repos_url);
curl_setopt($curl1, CURLOPT_HEADER, 0);
curl_setopt($curl1, CURLOPT_HTTPHEADER, array(
'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth'
));
curl_setopt($curl1,CURLOPT_USERAGENT,'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth');
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl1, CURLOPT_SSL_VERIFYHOST, 0);
$cont1 = curl_exec($curl1);
curl_close($cont1);
echo $cont1;
It responds with the following:
[
{
(information I don't need)
"full_name": "github-username/this-is-what-i-want",
(information I don't need)
}
]
I only have one repository at the moment. What I want to do is make a code that echos only the full_name and if there's more than one array echo each one. (All arrays will have full_name.)
Does anyone know how I could do this?
Decode it to an array, then loop through the arrays until you get to what you want:
$data=json_decode($cont1, true); <~~~ tells php to decode the JSON into an array
$results=$data['FirstArray']['SecondArray']['NumResultsReturned']; <~~ most JSON's have a value showing how many arrays got sent back to you in the results. You didn't give a true data example as a reply, so can't give exacts on these fields for you.

Get values from JSON data using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm using PHP to get a JSON response from a website and then process the response using json_decode. This is my PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.checkwx.com/taf/LLBG/?format=json");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'X-API-Key: 555555555'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close ($ch);
$json=json_decode($response,true);
$fulltaf = $json['status']['success']['data']['icao'];
This doesn't work.
This is the JSON data returned to be processed by json_decode:
{
"status": "success",
"data": [
{
"icao": "KPIE",
"observed": "07-03-2017 # 14:20Z",
"raw_text": "KPIE 071353Z 13017G23KT 10SM CLR 21\/13 A3031 RMK AO2 SLP262 T02060128",
"wind_degrees": 130,
}
]
}
You don't specify what didn't work?
First problem is that your JSON has a syntax error. I tried to validate your JSON using http://jsonlint.com and it flagged an extra comma after the 130 for wind_degrees. Check that actual response doesn't have that comma. The JSON won't parse properly with the extra comma.
The next problem is that data is an array (because its data is enclosed in brackets). In this example the array only has one element, [0], therefore to access icao you need to reference it as I show below.
My guess is that the following line didn't work correctly:
$fulltaf = $json['status']['success']['data']['icao'];
Based on the JSON you listed, this line should be the following if you want to retrieve the icao member of data.
$fulltaf = $json['data'][0]['icao'];
The following reference should return 'success' if you want to test for a successful response.
$json['status']

Need assistance with doing redirect with variables without query string

Hello: I have some code in on file and it needs to redirect to a WP page and carry some variables with it. Now I know I can do this with a "printf" statement and add some query string variables on the end of the URL of the page. But I do not want the variables up in the URL. I know if it was a form - it could be done with GET or POST variables. And post variables are not up in the URL. But the only way I know how to do post variables is with a form. I cannot use a form for this that needs a "submit" button that needs to be pressed. It needs to be something that is automatically executed when the script is loaded like a printf statement would be. Does anyone have any ideas on how this could be done ?
Thanks, Gerard
******* update 12/13 1:32PM EST ***************
Hello Arkascha - I have attempted to do what you suggested in your comment, and created the Curl call along with the post variables. But it would not actually redirect to the page. Not sure if I just did it wrong or if it cannot do that. But i was researching and saw where people did a header redirect along with the CURL. And so i thought i would try that. What I have does do the redirect; but it does not seem to carry the post variables with it. So I am not sure if something is wrong with my CURL code, or whether or not I need a header redirect.... etc etc...
here is my code:
$buy_refi='purchase';
$to_borrow=$entry["58"];
$home_worth=$entry["57"];
$down_payment=$entry["62"];
$purchase_price=$entry["54"];
$credit=$entry["15"];
$data = array(
'buy_refi' => $buy_refi,
'to_borrow' => $to_borrow,
'home_worth' => $home_worth,
'down_payment' => $down_payment,
'purchase_price' => $purchase_price,
'credit' => $credit,
);
$data = http_build_query($data); // convert array to urlencoded string
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://www.mydomain.dev/purchase-options/',
CURLOPT_POST => true,
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$resp = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
header("Location:http://www.mydomain.dev/purchase-options/");
*********** here is the code on redirect page which will receive post variables...
$_POST['input_2']=$_POST['buy_refi'];
$_POST['input_58']=$_POST['to_borrow'];
$_POST['input_57']=$_POST['home_worth'];
$_POST['input_62']=$_POST['down_payment'];
$_POST['input_54']=$_POST['purchase_price'];
$_POST['input_15']=$_POST['credit'];
echo "post buy refi: ".$_POST['buy_refi'];
echo "<br/>";
echo "<br/>";

PHP HTTP Post to REST Service not updating database [duplicate]

This question already has answers here:
curl POST format for CURLOPT_POSTFIELDS
(10 answers)
Closed 4 years ago.
I have this curl request below, which was successfully troubleshooted in another post. Right now, my PHP seems to work through this code without any errors, moves onto the next part of the IF statement and sends the confirmation email. It just doesn't update the database as it should from the web service. I will have to email the creator of the web service if this does not work but I just want to be sure that the code is fairly solid before I do this. Any one have any ideas? Here is the code:
$url = 'http://127.0.0.1:85/AccountCreator.ashx';
$curl_post_data = array(
'companyName' =>urlencode($companyName),
'mainContact' =>urlencode($mainContact),
'telephone1' =>urlencode($telephone1),
'email' => urlencode($email),
'contact2' => urlencode($contact2),
'telephone2' => urlencode($telephone2),
'email2' => urlencode($email2),
'package' => urlencode($package)
);
foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
//die("Test: ".$fields_string);
$ch = curl_init();
curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
Firstly, what is the problem? It would be easier to troubleshoot it if you explained exactly what the failure in the code was. Secondly, there are a couple of odd things you are doing in this code:
I don't see why you are doing
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
CURLOPT_POST requires a boolean (true/false) setting. You should set it to true.
Secondly, you don't need to encode CURLOPT_POSTFIELDS manually. Make an array and let cURL deal with it internally:
$curl_post_data = array(
'companyName' =>$companyName,
'mainContact' =>$mainContact,
'telephone1' =>$telephone),
'email' => $email,
'contact2' => $contact2,
'telephone2' => $telephone2,
'email2' => $email2,
'package' => $package
);
These might not fix the problem, but they may help.
The CURLOPT_POSTFIELDS option accepts an associative array of POST-data. Probably better to use that one rather than to construct the query string yourself so you got someone else to blame when it blows up.
PHP Manual:
The full data to post in a HTTP "POST"
operation. To post a file, prepend a
filename with # and use the full path.
This can either be passed as a
urlencoded string like
'para1=val1&para2=val2&...' or as an
array with the field name as key and
field data as value. If value is an
array, the Content-Type header will be
set to multipart/form-data.

Categories