Accessing Results of CURL request + PHP - php

I'm executing a curl request using php:
//Initiate cURL.
$ch = curl_init($url);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($data);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
The browser returns:
{"success":"true","lead_id":"141872","code":201}
OR
{"error":true,"duplicate":true,"message":"Duplicate: This has already been submitted to the API.","code":400}
How do I access the data in $result it current only returns 1

Set return transfer to true to get the page response in $result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$options = array (
CURLOPT_CONNECTTIMEOUT => 1, // timeout on connect
CURLOPT_TIMEOUT => 1, // timeout on response
CURLOPT_MAXREDIRS => 1 ,
CURLOPT_HTTPHEADER => array("REMOTE_ADDR: $proxy", "HTTP_X_FORWARDED_FOR: $proxy"),
CURLOPT_URL => $url
);
$ch = curl_init();
curl_setopt_array ( $ch, $options );
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
your solution :

Related

How send POST request with JSON in php?

I try to send request from post type to server but it not success, It return me BadRequest with status 400,
My code:
<?php
$products = array('1'=>array('amount'=>'1','product_id'=>'11250'));
$data = array('id' => '67', 'shipping' => '61', 'payment'=> '2','products'=> $products);
$cert = base64_encode('myapp#myapp.co.il:1234abcd');
$url = "https://myapp.co.il/api/aaa";
$ch = curl_init($url);
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"authorization: Basic ".$cert,
"Content-Type: application/json",
"cache-control: no-cache"
));
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
?>
It return me so:
array (2) {["message"] => string (51) "Bad Request: Syntax error, distorted JSON" ["status"] => int (400)}
I see that you prepared variable $payload to send, but sent $postdata instead at curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata).

JIRA REST API POST call via cURL with OAuth access token returns 401

I have went through steps of getting an access token ( i did this though a terminal using java)
When i try to use a GET request in terminal with java like this:
java -jar rest-oauth-client-1.0.one-jar.jar request ACCESS_TOKEN http://locahost:8015/rest/api/2/issue/TP-113
It works and returns an Issue JSON
But when i try to GET or POST an ISSUE using PHP and cURL like this
$FieldSummary = substr($items[0]->summary,strpos($items[0]->summary,'- ')+2);
$FieldDescription = substr($items[0]->description,0);
$FieldStartTime = new DateTime($items[0]->start->dateTime);
$FieldEndTime = new DateTime($items[0]->end->dateTime);
$dateStart = $FieldStartTime->format("Y-m-d\Th:m:s.sOZ");
$dateEnd = $FieldEndTime->format("Y-m-d\Th:m:s.sOZ");
$url = "http://".$config['jiraAdress']."/rest/api/2/issue/".$FieldKey;
$ch = curl_init($url);
$headers = array(
'Authorization: Bearer ACCESS_TOKEN',
'Accept: application/json',
'Content-Type: application/json'
);
$data = json_encode ( array (
'fields' => array (
'summary' => $FieldSummary,
'description' => $FieldDescription,
'customfield_10007' => $dateStart,
'customfield_10008' => $dateEnd
)
), JSON_PRETTY_PRINT );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
It returns error 401 and error JSON:
{
"errorMessages": [
"You do not have the permission to see the specified issue.",
"Login Required"
],
"errors": {
}
}
What am I doing wrong? Remember that this is JIRA REST API.

get curl request to eBay Post Order API giving empty string (PHP)

GET /post-order/v2/casemanagement/{caseId} call of eBay Post Order API giving an empty string. Can anyone clear out where does my code go wrong? Am I passing the headers correctly? Especially is the syntax of authorization correct?
<?php
error_reporting(E_ALL); // Turn on all errors, warnings and notices for easier debugging
//Seller Authorization Token
$userAuthToken= 'Authorization:TOKEN abc123';
//Endpoint URL to Use
$url = "https://api.ebay.com/post-order/v2/casemanagement/xyz";
//Initializle cURL
$connection = curl_init();
//Set Endpoint URL
curl_setopt($connection,CURLOPT_URL,$url);
//Set HTTP Method
curl_setopt($connection, CURLOPT_HTTPGET, true);
//Create Array of Required Headers
$headers = array();
$headers[] = $userAuthToken;
$headers[] = 'Content-Type:application/json';
$headers[] = 'X-EBAY-C-MARKETPLACE-ID:EBAY-DE';
//var_dump($headers);
//set the headers using the array of headers
curl_setopt($connection,CURLOPT_HTTPHEADER,$headers);
//set it to return the transfer as a string from curl_exec
curl_setopt($connection,CURLOPT_RETURNTRANSFER,1);
//stop CURL from verifying the peer's certificate
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
//Execute the Request
$response = curl_exec($connection);
//close the connection
curl_close($connection);
var_dump($response);
Try this code it is working fine for me.
<?php
// Your ID and token
$authToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// The data to send to the API
$post_data = json_encode(array("legacyOrderId"=>"110181400870-27973775001"));
$url = 'https://api.sandbox.ebay.com/post-order/v2/cancellation/check_eligibility';
//Setup cURL
$header = array(
'Accept: application/json',
'Authorization: TOKEN '.$authToken,
'Content-Type: application/json',
'X-EBAY-C-MARKETPLACE-ID: EBAY-UK'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if(curl_errno($ch)){
echo "ERROR:".curl_error($ch);
}
curl_close($ch);
echo json_decode($response,true);
?>
Response:
Array
(
[legacyOrderId] => 110181400870-27973775001
[eligible] => 1
[failureReason] => Array
(
)
[itemEligibilityResult] => Array
(
[0] => Array
(
[itemId] => 110181400870
[transactionId] => 34573775001
[eligible] => 1
[failureReason] => Array
(
)
)
)
[eligibleCancelReason] => Array
(
[0] => OUT_OF_STOCK_OR_CANNOT_FULFILL
[1] => BUYER_CANCEL_OR_ADDRESS_ISSUE
)
)
ADD
curl_setopt($connection, CURLOPT_HEADER, 1);
To return the headers and see what your problem might be.
I also don't know if it matters but my headers array looks like:
$headers = array (
'Authorization: ' . "TOKEN $token",
'Content-Type: ' . 'application/json',
'X-EBAY-C-MARKETPLACE-ID: ' . 'EBAY-US',
'Accept: ' . 'application/json',
);
So you can see there is a space after the colon.

How to make a POST request with data in XML format and get the result

I have an API which says all requests are made as POST requests with data in XML format, and it gives me a sample XML data:
<?xml version="1.0" ?>
<Request>
<SystemName>SomeSystemName</SystemName>
<Client>SomeClientID</Client>
<Method action="SomeAction">MethodParams</Method>
</Request>
Now I use curl to do it, like in this function:
function curl_post_xml($url, $xml, array $options = array())
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $xml,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
And in $xml I put that XML string from above. Am I doing it right? Because I heard that when using POST, the data must be in key-value format, but the API doesn't say anything about which variable should I assign XML string to.
Am I doing it right? Because I heard that when using POST, the data must be in key-value format,
Yes, you are right, you have to specify that you are sending an XML that's all.
CURLOPT_HTTPHEADER => array("Content-Type: application/xml"),
// or text/xml instead of application/xml
You do not need to put the $xml under a key. Just pass it as you are doing, its fine.
This works for me:
<?php
$xml_data ='<Request>
<SystemName>SomeSystemName</SystemName>
<Client>SomeClientID</Client>
<Method action="SomeAction">MethodParams</Method>
</Request>';
$URL = "https://www.yourwebserver.com/path/";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
?>

How to create the REST API for this curl operation in PHP

I want executed this simple curl operation through php how can i execute this in simple php not any framework , can i do it in simple php or do i need the framework?
curl -XPOST localhost:12060/repository/schema/fieldType -H 'Content-Type: application/json' -d '
{
action: "create",
fieldType: {
name: "n$name",
valueType: { primitive: "STRING" },
scope: "versioned",
namespaces: { "my.demo": "n" }
}
}' -D -
what i tried is :
<?php
$url="localhost:12060/repository/schema/fieldType";
//open connection
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
$fieldString=array(
"action"=> "create",
"fieldType"=>array(
"name"=> "n$name",
"valueType"=> array( "primitive"=> "STRING" ),
"scope"=> "versioned",
"namespaces"=> array( "my.demo"=> "n" )
)
);
//for some diff
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{json: $fieldString}"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt_array( $ch, $options );
//execute post
$result = curl_exec($ch);
$header = curl_getinfo( $ch );
echo $result;
//close connection
curl_close($ch);
?>
But it is giving me this
The given resource variant is not supported.Please use one of the following: * Variant[mediaType=application/json, language=null, encoding=null]
Your problem lies here:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{json: $fieldString}"));
The $fieldString is not actually an string as its name implies. It was an array at this point still. And you are trying to reencode an mangled faux json string, with just Array as data. Won't work.
Instead use this to get the desired(?) effect:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fieldString));

Categories