Post Json through API using curl, no results - php

I am fairly new to this so hopefully its not something silly i am missing out on. I am trying to create an order for someone using API.
I have searched for hours how to do this on stackoverflow and all the post have been great help. But now I have hit a brick wall. This code does not seem to throw any errors when visiting the PHP page nor does it take the item away from stock on like its meant to.
Am i missing something really simple, also is there a way to check if its working?
<?php
$today = date("D M j Y G:i:s T");
$data = array(
"order" => [
"order_number" => "",
"company_id" => 690094,
"billing_address_id" => 1018327,
"shipping_address_id" => 1018327,
"stock_location_id" => 16377,
"ship_at" => $today,
"issued_at" => $today,
"tax_type" => "exclusive",
"payment_status" => "unpaid",
"fulfillment_status" => "shipped",
"email" => null,
"reference_number" => 7784,
"status" => "fulfilled",
"order_line_items" => [
"quantity" => 1, "discount" => null, "price" => 1,
"tax_rate_override" => null, "freeform" => false,
"variant_id" => 6983077
],
],
);
$url ="https://api.tradegecko.com/orders/";
$str_data = json_encode($data);
function sendPostData($url, $str_data){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'http' => array(
'header' => "Authorization: Bearer 872ed5e72dfc7e4e0adaa7c663cab7d81415078fdbe4f486d085b718c93b3eb3")
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$str_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo sendPostData($url, $str_data);
?>

Setting the Authorization header is not done in the right way. It should be done as in:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer 872ed5e72dfc7e4e0adaa7c663cab7d81415078fdbe4f486d085b718c93b3eb3')
);
For debugging purposes it is helpful to add:
curl_setopt($ch, CURLOPT_VERBOSE, 1);
Finally, you should create a new access token for this service since yours is public now.

Related

How to prevent wp_remote_post to add backslashes

To publish a plugin I must change my code to use the Wordpress HTTP Api.
Therefore, I have translate my code.
Before.
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$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);
After
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$result = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json'),
'body' => wp_json_encode($data_string),
'method' => 'POST',
'timeout' => 60, // added
'redirection' => 5, // added
'blocking' => true, // added
'httpversion' => '1.0',
'sslverify' => false,
));
But with the function wp_remote_post I have this problem.
When JSON data is sended to remote host, the data has the backslashes inside.
Example:
{\"Param1\":\"ValueParam1\","Param2\":\"ValueParam2\"}
What is wrong?
Have I wrong something in translate the origin code?
I need some help to send JSON data without these escaping characters.
Thanks.
Pass JSON_HEX_QUOT as a second parameter to wp_json_encode to escape the double quotes without a slash. See: https://developer.wordpress.org/reference/functions/wp_json_encode/ and https://www.php.net/manual/en/json.constants.php for more details.

PHP curl POST for Watson Video Enrichment

Am trying to use PHP 7.2 to submit a new job to the Watson Video Enrichment API.
Here's my code:
//set some vars for all tasks
$apiUrl = 'https://api-dal.watsonmedia.ibm.com/video-enrichment/v2';
$apiKey = 'xxxxxxxx';
//vars for this task
$path = '/jobs';
$name = 'Test1';
$notification_url = 'https://example.com/notification.php';
$url = 'https://example.com/video.mp4';
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => "simple.custom-model",
"upload" => array(
"url" => $url
)
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL, $apiUrl.$path );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: APIKey '.$apiKey
));
$result = curl_exec($ch);
echo $result;
But I can't get it to work, even with varying CURLOPTs, like:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
I keep getting the response: Bad Request.
Here's the API docs.
Am I setting up the POST CURL all wrong? Is my $data array wrong? Any idea how to fix this?
Reading their API documentation, it looks like the field preset is not of type string. Rather it has a schema defined here. This appears similar to how you are using the upload schema.
You should change your data array to look like this:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"video_url" => "https://example.com/path/to/your/video"
),
"upload" => array(
"url" => $url
)
);
Ok, I figured it out. Thanks to #TheGentleman for pointing the way.
My data array should look like:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"simple.custom-model" => array(
"video_url" => $url,
"language" => "en-US"
)
),
"upload" => array(
"url" => $url
)
);

synapse PHP API sandbox mode showing error "None is not of type 'string'"

I am working with synapse and having issue while uploading user doc attachment, actually same thing is working on our live server but not working with test server in sandbox mode
If any one can help :)
Reference URL: https://docs.synapsepay.com/v3/docs/attach-document
API URL: https://sandbox.synapsepay.com/api/3/user/doc/attachments/add
Response: Array ( [error] => Array ( [en] => None is not of type 'string' ) [error_code] => 200 [http_code] => 400 [success] => )
Code as Below:
$url = "https://sandbox.synapsepay.com/api/v3/user/doc/attachments/add";
// KYC Documentation
$payload = array(
"login" => array(
//Oauth_key of the user to add KYC doc
"oauth_key" => "hTUCH4kO89qGZDpyEdoq55ODYugwwRsd57ti8ohZ"
),
"user" => array(
//doc data
"doc" => array(
'attachment'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AuMDAsLEJhbmsgQWNjb3VudCwxNDI5Nzc1MzY0LFNldHRsZWQNCjQzMTIsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjk3NzUyNTAsU2V0dGxlZA0KNDMxMSxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyOTc3NTAxMyxTZXR0bGVkDQo0MjM1LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI5MzMxODA2LFNldHRsZWQNCjQxMzYsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjg4OTA4NjMsU2V0dGxlZA0KNDAzMCxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyODIxNTM5NixTZXR0bGVkDQo0MDE0LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI4MTI1MzgwLENhbmNsZWQNCjM4MzIsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0MjcxMDc0NzAsU2V0dGxlZA0KMzgyNixTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyNzAzNTM5MixTZXR0bGVkDQozODI1LFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI3MDMyOTM3LFNldHRsZWQNCg=='
),
"fingerprint" => "suasusau21324redakufejfjsf",
)
);
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $payload ),
'header' => "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$data_string = json_encode($payload);
curlIT($url, $data_string);
function curlIT($url, $fields){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json')
);
$result = curl_exec($ch);
print_r($result);
}
exit;
?>
Synapse api changed you need to send auth key and client id in headers
Take a look of new document
https://docs.synapsepay.com/docs/adding-documents

You must log in before using this part of Bugzilla, code:410

I am able to get the GET request working but having issues related to authentication in POST and PUT request. I am getting the error "You must log in before using this part of Bugzilla". I have provided the correct username and password. I have tried CURLAUTH_ANY as well as CURLAUTH_BASIC. I have tried both PUT and POST request. Any help is appreciated.
$url ="http://localhost:8080/bugzilla/rest/bug/2";
$apikey = "IZC4rs2gstCal0jEZosFjDBRV9AQv2gF0udh4hgq";
$data = array(
"product" => "TestProduct",
"component" => "TestComponent",
"version" => "unspecified",
"summary" => "This is a test bug - please disregard",
"alias" => "SomeAlias",
"op_sys" => "All",
"priority" => "P1",
"rep_platform" => "All"
);
$str_data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$str_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-Type: application/json", "Accept: application/json"));
$username = 'ashish.sureka#in.abb.com';
$password = 'abbincrc';
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo $result
Following code solved my problem. I have written a blog on it which might be useful to others encountering the same problem.
<?php
$url = 'http://localhost:8080//bugzilla/xmlrpc.cgi';
$ch = curl_init();
$header = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: text/xml', 'charset=utf-8' )
);
curl_setopt_array($ch, $header);
$bugreport = array(
'login' => 'ashish.sureka#in.abb.com',
'password' => 'abbincrc',
'product' => "TestProduct",
'component' => "TestComponent",
'summary' => "Bug Title : A One Line Summary",
'assigned_to' => "ashish.sureka#in.abb.com",
'version' => "unspecified",
'description' => "Bug Description : A Detailed Problem Description",
'op_sys' => "All",
'platform' => "All",
'priority' => "Normal",
'severity' => "Trivial"
);
$request = xmlrpc_encode_request("Bug.create", $bugreport);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_exec($ch)
?>

Paypal API, Curl not returning any output

I'm trying to figure out the paypal API, and I have the following code, which should make a call, get an access token, and then make the API call. The first part works(up until the $accesstoken line), and returns the access token properly, but the second part doesn't return anything. The code this is supposed to mimic can be found here: Make Your First Call
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$headers = array(
'Accept' => 'application/json',
'Accept-Language' => 'en_US',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $clientID . ':' . $clientSecret);
$curl = curl_exec($ch);
$x = json_decode($curl, TRUE);
print_r($x);
$accesstoken = $x['access_token'];
$headers2 = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer' . $accesstoken
);
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => "http://example.com/your_redirect_url/",
"cancel_url" => "http://example.com/your_cancel_url/"
),
"payer" => array(
"payment_method" => "paypal"
),
"transactions" => array(
"transactions" => array(
"total" => ".99",
"currency" => "USD"
)
)
);
$saleurl = "https://api.sandbox.paypal.com/v1/payments/payment";
$sale = curl_init();
curl_setopt($sale, CURLOPT_URL, $saleurl);
curl_setopt($sale, CURLOPT_VERBOSE, TRUE);
curl_setopt($sale, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($sale, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($sale, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($sale, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($sale, CURLOPT_HTTPHEADER, $headers2);
$finalsale = curl_exec($sale);
$verb = json_decode($finalsale, TRUE);
print_r($verb);
Curl doesn't make complete sense to me, any help would be appreciated.
UPDATE:
I changed the format of the headers to:
$headers2 = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accesstoken
);
as per one of the answers. Now it is displaying:
[name] => MALFORMED_REQUEST
[message] => Incoming JSON request does not map to API request
[information_link] => https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST
[debug_id] => f53a882702a04
You are not setting your headers correctly ...
$headers = array(
'Accept: application/json',
'Accept-Language: en_US'
);
and
$headers2 = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accesstoken
);
Is the correct format.
Also note the (space) after Bearer inbetween your $accesstoken
Edit: Update for your JSON ( i think this is right but echo it out and check it against the reference, I might have one to many array()
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => "http://example.com/your_redirect_url/",
"cancel_url" => "http://example.com/your_cancel_url/"
),
"payer" => array(
"payment_method" => "paypal"
),
"transactions" => array(array(
"amount" => array(
"total" => ".99",
"currency" => "USD"
)
)
)
);
You need a space here
$headers2 = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $accesstoken // Added a space after Bearer
);
See if it works now
Change
curl_setopt($sale, CURLOPT_POSTFIELDS, json_encode($data));
to
curl_setopt($sale, CURLOPT_POSTFIELDS, $data);
The json encode function breaks it

Categories