I am trying to integrate my application with a payment gateway.
Their API is based on REST API and uses JSON to transport data. They have this sample code
$ curl -X POST -H "Content-Type: application/json" \
-u APIKEYEXAMPLEAPIKEYEXAMPLE:APIKEYEXAMPLEAPIKEYEXAMPLE \
https://api.netbanx.com/hosted/v1/orders \
-d '{
"merchantRefNum" : "ABCDE12345",
"currencyCode" : "USD",
"totalAmount" : 1234
}'
And I am trying to use this to develop a php code for the same. So far my code is like this, I took in the answer provided below and modified a bit and here is my code.
<?php
//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'merchantRefNum' => '89983483',
'currencyCode' => 'USD',
'totalAmount' => '1234'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//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'));
//Set the header authorization
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'Authorization: Basic ZGV2Y2VudHJlNDYxNzpCLXFhMi0wLTU0OGEwM2RkLTMwMmQwMjE1MDA4M2VhZTUwYjQxYzQ0ZDIwMTE4OGM3ZmY4Yjc0ZDIxMzUwY2NiMjdiMDIxNDYwMDc4MGFlMTRkM2E2MTEzY2RmMmJkODc5MjJmZjU3MWQwMGY0ZWU=');
//Execute the request
$result = curl_exec($ch);
?>
My testing API Key devcentre4617:B-qa2-0-548a03dd-302d02150083eae50b41c44d201188c7ff8b74d21350ccb27b0214600780ae14d3a6113cdf2bd87922ff571d00f4ee
As told in their docs, I converted the API Key to base64 added the word Basic gave a whitespace and got the HTTP Authorizatoin code as Basic ZGV2Y2VudHJlNDYxNzpCLXFhMi0wLTU0OGEwM2RkLTMwMmQwMjE1MDA4M2VhZTUwYjQxYzQ0ZDIwMTE4OGM3ZmY4Yjc0ZDIxMzUwY2NiMjdiMDIxNDYwMDc4MGFlMTRkM2E2MTEzY2RmMmJkODc5MjJmZjU3MWQwMGY0ZWU=
On execution I keep getting
{"error":{"code":401,"message":"Not authorised"}}
Is something wrong with my code? Or is the issues elsewhere?
UPDATE!!!
This is the working code, the issue was with the API DOCs the testing api is https://api.test.netbanx.com/hosted/v1/orders
<?php
//API Url
$url = 'https://api.test.netbanx.com/hosted/v1/orders';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'merchantRefNum' => '89983483',
'currencyCode' => 'USD',
'totalAmount' => '1234'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//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 and HTTP Authorization code
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("devcentre4617:B-qa2-0-548a03dd-302d02150083eae50b41c44d201188c7ff8b74d21350ccb27b0214600780ae14d3a6113cdf2bd87922ff571d00f4ee") //Base 64 encoding and appending Authorization: Basic
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Execute the request
$result = curl_exec($ch);
?>
You need to add your username and password like this:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, 'APIKEYEXAMPLEAPIKEYEXAMPLE:APIKEYEXAMPLEAPIKEYEXAMPLE');
Good luck :)
Related
I'm trying to use Application Only Authentication, as described here:
https://developer.twitter.com/en/docs/basics/authentication/overview/application-only
I'm using the following PHP code to do so.
if(empty($_COOKIE['twitter_auth'])) {
require '../../social_audit_config/twitter_config.php';
$encoded_key = urlencode($api_key);
$encoded_secret = urlencode($api_secret);
$credentials = $encoded_key.":".$encoded_secret;
$encoded_credentials = base64_encode($credentials);
$request_headers = array(
'Host: api.twitter.com',
'User-Agent: BF Sharing Report',
'Authorization: Basic '.$encoded_credentials,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'Content-Length: 29',
'Accept-Encoding: gzip'
);
print_r($request_headers);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$attempt_auth = curl_exec($ch);
print_r($attempt_auth);
}
It should return JSON with the token in it, but instead it returns gobbledygook, as seen in the image below:
I'm sure I'm missing some very simple step, where am I going wrong?
If I send the curl request without the headers, it returns an error in JSON format as expected, so is there something wrong with my headers?
You have few options here. Instead of setting header directly, use below
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
If you set header directly then you should use
print_r(gzdecode($attempt_auth));
See below thread as well
Decode gzipped web page retrieved via cURL in PHP
php - Get compressed contents using cURL
everyone, i am requesting data from some other website but I am unable to request through curl it shows error 500 but when I do the same request through chrome RESTED extension it shows me output
$url = "XXXXXXXXXXX";
// what post fields?
$fields = array(
'roll_number' => '123456',
'full_name' => 'aaaaaa',
'mother_name' => 'bbbbbbb',
'_token' => 'xxxxxxxxxxxxxxxx'
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Request should be by post method and data should be JSON encoded or URL encoded I have tried both but none of them worked
Not sure if this is the cause, but shouldn't your HTTPHEADER be application/json? Also, you're not encoding the data as JSON - you might need to change $postvars = http_build_query($fields); to $postvars = json_encode($fields);
I'd also take a look at https://lornajane.net/posts/2011/posting-json-data-with-php-curl
I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal
curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST
Same thing I have tried with php But it is giving the following error
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}
The following one I have tried
$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'name'=>'NEW USER',
'is_platform_access_only'=>'true',
));
//Adding Header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$developer_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.
I have rise the same question in Perl tag with Perl code. There I got answer by user #melpomene.
We should encode the data as JSON. It is working,
Then the final code is
$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);
Here is my code for trying to delete a file a file via the api
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/<MY-ZONE-ID>/purge_cache");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = [
'X-Auth-Email: MYEMAIL',
'X-Auth-Key: MY-AUTH-KEY',
'Content-Type: application/json'
];
$data = json_encode(array("files" => "https://example.com/file/".$filename));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
The response i get is as follows
{
"success":false,
"errors":[
{
"code":1012,
"message":"Request must contain one of \"purge_everything\" or \"files\", or \"tags"
}
],
"messages":[
],
"result":null
}
Documentation says tag is optional so it should work
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
-H "X-Auth-Email: user#example.com" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"files":["http://www.example.com/css/styles.css"],"tags":["some-tag","another-tag"]}'
What am In doing wrong here ?
I maybe because your files property is not an array.
Try
$data = json_encode(array("files" => array("https://example.com/file/".$filename)));
This is a bit confusing. Post Data is usually sent in key value pairs.
Also when the post data is an array curl changes the content type to multipart/form-data
When post data is sent as a query string, it's in the format of key1=value1&key2=value2
It appears the json is the value with no key.
I would try it both as an array and string and look at the request header.
In the request header look at the content-type and the data.
To get the request header in the curl return add this option:
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
You may need to add:
curl_setopt($ch, CURLOPT_POST, true);
$data[] = json_encode(array('files'=>"https://example.com/file/$filename"));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$data = json_encode(array('files'=>"https://example.com/file/$filename"));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
PS: You do not need to use the . concatenation when using double quotes for $filename
I have a working command line curl command
curl -v -d '{"auth": {"passwordCredentials": {"username": "myusername", "password": "mypassword"}}}' -H 'Content-type: application/json' myurl
I am trying to write equivalent PHP curl command -
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, myurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array('json' => '{auth: {passwordCredentials : {username : myusername, password : mypassword }}}');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
echo $output;
I am having different response for both the calls.
I have doubt about setting the json data correctly.
Along with your curl request, also send the HTTP header. For example:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
And the post data should be:
$post_data = '{auth: {passwordCredentials : {username : myusername, password : mypassword }}}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
You can use the json_encode function to make sure that things are properly encoded.
See for example https://stackoverflow.com/a/4271654/1967396 .
In your case, it might look like this:
$authData = array(auth => array(passwordCredentials => array( username => floris, password => secret )));
and then you create the POST data with
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json'=>json_encode($authData)));
If you do
print json_encode($authData);
you get
{"auth":{"passwordCredentials":{"username":"floris","password":"secret"}}}
Presumably you could do this manually, without the json_encode function.