Using CURL to post JSON with PHP variables - php

I'm trying to set up account creation via a payment form on my website using ZenDesk's API. The example code they give is:
curl -v -u {email_address}:{password} https://{subdomain}.zendesk.com/api/v2/users.json \
-H "Content-Type: application/json" -X POST -d '{"user": {"name": "Roger Wilco", "email": "roge#example.org"}}'
Since I need to include PHP variables, I'm trying to use this:
$data = array("name" => $entry["1"], "email" => $entry["3"], "role" => "end-user");
$data_string = json_encode($data);
$ch = curl_init('https://xxxx.zendesk.com/api/v2/users.json');
curl_setopt($ch, CURLOPT_USERPWD, "xxxx#example.com:xxxx");
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);
However, it's not working. Is my code correct in terms of duplicating the function of the first snippet?

I found another example of ZenDesk's API and was able to come up with this:
<?PHP
define("ZDAPIKEY", "SECRETKEYGOESHERE");
define("ZDUSER", "me#mysite.com");
define("ZDURL", "https://mysite.zendesk.com/api/v2");
/* Note: do not put a trailing slash at the end of v2 */
function curlWrap($url, $json, $action)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_URL, ZDURL.$url);
curl_setopt($ch, CURLOPT_USERPWD, ZDUSER."/token:".ZDAPIKEY);
switch($action){
case "POST":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
break;
case "GET":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
default:
break;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$decoded = json_decode($output);
return $decoded;
}
$arr = array("z_name"=>$namevariable,
"z_email"=>$emailvariable,
"z_role"=>"end_user",
"z_verified"=>"yes"
);
$create = json_encode(array('user' => array('name' => $arr['z_name'], 'email' => $arr['z_email'], 'role' => $arr['z_role'])), JSON_FORCE_OBJECT);
$data = curlWrap("/users.json", $create, "POST");
var_dump($data);
?>
It appears to be working on its own, so this answers the question as it exists here.
Thanks for your help everyone :)

I know the question is answered, but since I found it while having the same issue and since it did not solve my issue, I figured I'd post what I did. Hopefully, it can help someone else.
Here is the combination that worked for me in a case where I had to submit json data via PUT:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 90);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json', 'Content-Length: ' . strlen($json), 'X-HTTP-Method-Override: PUT'));
Note that it does NOT require CURLOPT_CUSTOMREQUEST or CURLOPT_PUT since the X-HTTP-Method-Override: PUT parameter takes care of that.

Related

Update data using PUT with CURL PHP

I m try to update some data on mongodb using cms api
on terminal i can update information like this
curl -X PUT -d name=12345a https://api1.MYWEBISITE.com/api/v1in/user/2039/?t=mytoken
now using PHP i have try so many ways and no one looks to work for me
tried like this
class Curl {
public function put($url, $data_string){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
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);
return $result;
}
}
$curl = new Curl;
$data_string = '{"name" : "name123"}';
$url = "https://api1.MYWEBSITE.com/api/v1in/user/2039/?t=mytoken";
echo $curl->put($url, $data_string);
also i tried like this
$data = array( "name" => '12344');
$url = "https://api1.mywebsite.com/api/v1in/user/2039/?t=mytoken";
$curl = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$response = json_decode($result);
var_dump($response);
curl_close($curl);
both php solutions dont works, nothing is updated, no error msg is showing
any help?

PHP Curl: Could not verify the provided CSRF token because your session was not found

I am trying to get an Access Token on The Taboola Backstage API according to this documentation.
Backstage API - Authentication and General API Usage.pdf
My Sample Code looks like this:
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$post = array(
"client_id" => "secret"
, "client_secret" => "secret"
, "grant_type" => "client_credentials"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile );
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile );
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token/");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$result=curl_exec ($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
var_dump($header,$body);
If I run the code I get the error message. Could not verify the provided CSRF token because your session was not found. What iam missing, i send it with POST to the right endpoint. Have someone please a tip for me?
It looks like their documentation may be slightly off. I was able to get a proper API response by posting to /backstage/oauth/token (no trailing /). With the trailing slash it tries to pass you through to a different non-API URL.
Also, it's necessary to pass the POST array through http_build_query() so that cURL doesn't do a multipart form post from the supplied array. Since it's an API, there's no need to do anything with cookies. I removed a few other unnecessary options as well.
Here is some code to get you started that worked for me:
$post = array(
"client_id" => "secret",
"client_secret" => "secret",
"grant_type" => "client_credentials",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
));
curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
$result=curl_exec ($ch);
$info = curl_getinfo($ch);
$response = json_decode($result, true);
if ($info['http_code'] == 200) {
// okay
$access_token = $response['access_token'];
var_dump($response);
} else {
// error
echo $response['error'] . ': ' . $response['error_description'];
}

Curl to test Sabre REST API Authentication Failing

I'm creating the authentication and getting an access token fine but the problem arises when I try to send a request. I'm creating the headers using PHP
<?php
define("POST", "POST");
**$environment=' https://api-crt.cert.havail.sabre.com';**
$userId='XXXXXXX';
$domain='AA';
$Group='XXXXXXXXXX';
$formatVersion='V1';
$clientSecret=base64_encode('XXXXXXXXXXX');
$client_id=base64_encode($formatVersion.":".$userId.":".$Group.":".$domain);
$bulid_credential=base64_encode($client_id.":".$clientSecret);
######################## Step 1: Get Token #############################
**$ch =curl_init("https://api-crt.cert.havail.sabre.com/v2/auth/token");**
$vars ="grant_type=client_credentials";
$header =array(
'Authorization: Basic '.$bulid_credential,
'Accept: */*',
'Content-Type: application/x-www-form-urlencoded'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res= curl_exec($ch);
$result=json_decode($res);
$token=$result->access_token;
########################## Step 2: Call the REST API###################
**$url="https://api.test.sabre.com/v3.3.0/shop/flights?mode=live";**
$header = array(
'Authorization: Bearer'. $token,
'Content-Type: application/json'
);
$calltype='POST';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $calltype);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonrequest);//Request
array_push($header, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result=curl_exec($ch);
$result1=json_decode($result);
curl_close($ch);
?>
The Sabre Response :
{"status":"Incomplete","type":"Application","errorCode":"ERR.2SG.PROVIDER_ERROR","timeStamp":"2017-10-11T06:02:08.658-05:00","message":"Error occurred while invoking service rest:readMetadata:1.13.7.SNAPSHOT"}
1) Did you ensure that $token is a string and not an object?
I use this:
$result=json_decode($res, TRUE);
$token=$result['access_token'];
Instead of this:
$result=json_decode($res);
$token=$result->access_token;
2) Did you ensure that the content of $jsonrequest is valid?
Maybe it's not the PHP code that is incorrect, but your JSON query.

how to show products json in api

I am stuck to a problem, I am unable to get the products json in magento2? Can any one solve my problem, I get the token successfully but unable to get the products json in php
Here is my following php code
<?php
$userData = ["username" => "admin", "password" => "admin_password"];
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailcontent));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
echo $result;
die;
$result = json_decode($result, 1);
echo '<pre>';print_r($result);
?>
here is what I get the response in json, field name is required
{"message":"%fieldName is a required field.","parameters":{"fieldName":"product"},"trace":"#0 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/framework\/Webapi\/ServiceInputProcessor.php(131): Magento\\Framework\\Webapi\\ServiceInputProcessor->processInputError(Array)\n#1 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/module-webapi\/Controller\/Rest\/InputParamsResolver.php(101): Magento\\Framework\\Webapi\\ServiceInputProcessor->process('Magento\\\\Catalog...', 'save', Array)\n#2 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/module-webapi\/Controller\/Rest.php(299): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver->resolve()\n#3 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/module-webapi\/Controller\/Rest.php(216): Magento\\Webapi\\Controller\\Rest->processApiRequest()\n#4 \/home2\/bhagnani\/public_html\/experian-ccmp\/var\/generation\/Magento\/Webapi\/Controller\/Rest\/Interceptor.php(37): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#5 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/framework\/App\/Http.php(135): Magento\\Webapi\\Controller\\Rest\\Interceptor->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#6 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/framework\/App\/Bootstrap.php(258): Magento\\Framework\\App\\Http->launch()\n#7 \/home2\/bhagnani\/public_html\/experian-ccmp\/index.php(39): Magento\\Framework\\App\\Bootstrap->run(Object(Magento\\Framework\\App\\Http))\n#8 {main}"}
Thanks for the comments in advance
Instead of
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products");
Try this to get all product list
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products?searchCriteria=");
Hope this helps!
Your URL are ok.
Only change:
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // method
to:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); // method
Check: http://devdocs.magento.com/swagger/

cURL in PHP Basecamp API "PUT"

I am trying to edit an existing Basecamp project via the new Basecamp Api. I am receiving this error:
lexical error: malformed number, a digit is required after the minus sign. --------------- ---------------6 (right here) ------^
My Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL, 'https://basecamp.com/****/api/v1/projects/****.json');
curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent : Holy Grail (user#example.com)");
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, array("name" => "from cURL"));
$result = curl_exec($ch);
echo $result;
curl_close($ch);
if ($result == false) {
echo "Fetch failed" ;
}
else {
$obj = json_decode($result, true);
}
//var_dump($obj);
?>
I'm sure I'm just doing something stupid, but any help is appreciated.
Thanks!
UPDATE
What I have now:
$username = 'user';
$password = 'pass';
$data = json_encode(array("name" => "from cURL"));
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL, 'https://basecamp.com/****/api/v1/projects/*****.json');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent : Holy Grail (user#example.com)');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type :application/json',
'Content-Length: ' .strlen($data)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
if ($result == false) {
echo "Fetch failed" ;
}
else {
$obj = json_decode($result, true);
}
//var_dump($obj);
?>
</body>
</html>
BasecampAPI accepts only JSON data, you can see here in -d parameter -
curl -u username:password \
-H 'Content-Type: application/json' \
-H 'User-Agent: MyApp (yourname#example.com)' \
-d '{ "name": "My new project!" }' \
https://basecamp.com/999999999/api/v1/projects.json
So you're not sending JSON data in this line -
curl_setopt($ch, CURLOPT_POSTFIELDS, array("name" => "from cURL"));
Remove the CUSTOMREQUEST option and add CURLOPT_PUT. Modify your code to -
$data_string = json_encode(array("name" => "from cURL"));
...
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_PUT, True);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);

Categories