I have done little with cURL so far, so bear with me.
This is the api that I am currently dealing with:
CentralPlannerAPI
I have a token, I can call it via the bash shell and all is fine, except for the part where PHP comes into play. I constantly get authentication errors. The last one would be a 500.
This one works:
curl "https://centralplanner.net/api/contacts" -H 'Authorization: Token token="my-api-token"'
This one does not work:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://centralplanner.net/api/contacts/count" );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Authorization: Token token='myToken'" ) );
curl_exec( $ch );
curl_close( $ch );
Why does the PHP part not work?
What am I not getting here. Yes, there is currently not much to it and later one it will only be slightly more than this, at least from the current perspective; no it will not run on a server; yes, I will add some validation on and yes, it will a proper class construct and so and so forth.
PS:
Before someone refers me to other SO sites, I looked at them ... did not help.
Please try this code:
$ch = curl_init("https://centralplanner.net/api/contacts/count");
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => "Authorization: Token token=\"myToken\""
];
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
Related
I would like to create new categories in CS-Cart through its API.
So far I have this code (running it through browser, just for testing):
$cfg = get_config(); //connection to DB
$product_data = array();
$product_data["category"] = "Category Test API";
$product_data["company_id"] = 1;
$product_data["status"] = "A";
//CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD, 'USER EMAIL'.":".'YOUR API:KEY');
curl_setopt($ch, CURLOPT_URL, $cfg["cscart_store_url"]."api/categories/");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($product_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
if( !curl_error($ch) ) {
echo "no error";
curl_close($ch);
return json_decode($server_output, TRUE);
}
else {
echo "error found!!!";
print_r("Error: ".curl_error($ch));
return 0;
}
There is a documentation here: https://docs.cs-cart.com/latest/developer_guide/api/entities/categories.html.
But I still couldn't make it work although I did not get any errors from curl_exec.
Your json is well encoded, your header have the Content-Type, i think your problem is your cscart_store_url who have a wrong url or your USERPWD isn't good (I believe you didnt put USER EMAIL in your auth
As long as I understood, cs-cart API has some required values in order to make an INSERT API call. Thus, the categories should be already be created inside cs-cart dashboard and match them somehow in the PHP script
On the other hand, if you want to UPDAtE a product for example, you could UPDAte only the specified values you send to API call, without the need of sending all the required API values.
Last but not least, there are more than one Authorizations methods to make the call. I used CURL in order to do the API call and there is a parameter CURLOPT_HTTPHEADER which I have added the below code:
...
CURLOPT_HTTPHEADER => array(
"Authorization: Basic XXXxxxxXXXXxxxXXXlzLmNvbS5ncjpKejMXXXxxxxXN0Y2MDQxenprbEXXXxxXXXE3Mg==",
"Content-Type: application/json",
"cache-control: no-cache"
),
...
Where Authorization is: Basic base64(user#example.com:API_KEY_taken_from_cscart)
Applying all the above the code and the API worked!
thanks everyone for the help and comments
I am new to Livecode and I have tried couple of things to convert this php http post request code to Livecode but not working. Will need it either with cURL or without cURL.
$receive_momo_request = array(
'CustomerName' => 'Customer Name',
'CustomerMsisdn'=> '054XXXX',
'CustomerEmail'=> 'customer#gmail.com',
'Channel'=> 'mtn-gh',
'Amount'=> 0.8,
'PrimaryCallbackUrl'=> 'http://requestb.in/1minotz1',
'Description'=> 'T Shirt',
);
//API Keys
$clientId = 'xxxxxxx';
$clientSecret = 'xxxxxxx';
$basic_auth_key = 'Basic ' . base64_encode($clientId . ':' . $clientSecret);
$request_url = 'https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney';
$receive_momo_request = json_encode($receive_momo_request);
$ch = curl_init($request_url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $receive_momo_request);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Authorization: '.$basic_auth_key,
'Cache-Control: no-cache',
'Content-Type: application/json',
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if($err){
echo $err;
}else{
echo $result;
}
This is what I have done so far may be am missing something.
on mouseUp
global gFirstName, gLastName
put gFirstName & " " & gLastName into lFullName
put lFullName into tArray[ "CustomerName"]
put "gPhoneNumber" into tArray["CustomerMsisdn"]
put "gEmail" into tArray["CustomerEmail"]
put "airtel-gh" into tArray["Channel"]
put "0.01" into tArray["Amount"]
put "http://requestb.in/1minotz1" into tArray["PrimaryCallbackUrl"]
put "FBMC Mobile" into tArray["Description"]
put true into tArray ["FeesOnCustomer"]
put ArrayToJSON(tArray) into receive_momo_request
put "ABCD" into clientId
put "1234" into clientSecret
set the httpHeaders to "Content-type: application/json" && "Authorization: Basic " && base64Encode("clientId:clientSecret") && "Cache-Control: no-cache"
post receive_momo_request to url "https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney"
end mouseUp
Your LiveCode code looks good on first glance. I would try two things:
First, URLencode the data you are posting before you post it.
put ArrayToJSON(tArray) into receive_momo_request
put urlEncode(receive_momo_request) into receive_momo_request
Second, after the post command, check the itvariable to see what data was returned by the web server. You can also check the result to see if an error occurred.
post receive_momo_request to url "https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney"
put it into tServerFeedback
answer the result
This should at least tell you what is happening after you issue the post command.
I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
I'm building my first Spotify application and right now I'm tackling the authorization process.
So far I have been successful in retrieving my State and Code from https://accounts.spotify.com/authorize
and now I'm sending a POST request via PHP CURL request to acquire my access token.
Spotify's instructions for this step
I keep getting the following JSON error response indicating that my grant_type is not valid and it offers me three valid options:
{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}bool(true)
If you look at my code below, I believe I have set the correct grant_type of "authorization_code" but I'm getting the error. I have highlighted with '******' the code snippet of what I believe to be the correct line of code.
Can anyone see what I'm doing incorrectly? Here's the code I'm using to send the request:
// Get access tokens
$ch = curl_init();
// Specify the HTTP headers to send.
//Authorization: Basic <base64 encoded client_id:client_secret>
$ClientIDSpotify = "[my spotify app id]";
$ClientSecretSpotify = "[my secret code]";
$authorization = base64_encode ( "{$ClientIDSpotify}:{$ClientSecretSpotify}" );
$http_headers = array(
"Authorization: Basic {$authorization}"
);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_headers );
curl_setopt( $ch, CURLOPT_POST, true);
$spotify_url = "https://accounts.spotify.com/api/token";
curl_setopt( $ch, CURLOPT_URL, $spotify_url );
// *************************************************
// HERE'S WHERE I CORRECTLY SPECIFY THE GRANT TYPE
// *************************************************
$data['grant_type'] = "authorization_code";
$data['code'] = $authorizationCode;
$callbackURL = "[my callback URL]";
$data['redirect_uri'] = $callbackURL;
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response_json = curl_exec( $ch );
curl_close( $ch );
}
Just as a note to the last comment about switching to http_build_query, I had to URLDECODE the data, in order for Spotify to recognize it. Try using this line instead.
curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($data)));
Seems to me like the POST body isn't being formatted correctly, everything else looks good.
My limited understanding of PHP tells me that your POST body looks like
{
"fields" : {
"code" : $authorizationCode,
"grant_type" : "authorization_code",
"redirect_uri" : "http://www.example.com/spotify/callback/index.php"
}
}
Of course, what you'd like to send is just
{
"code" : $authorizationCode,
"grant_type" : "authorization_code",
"redirect_uri" : "http://www.example.com/spotify/callback/index.php"
}
Therefore, try to set the $data object with
$data['grant_type'] = "authorization_code";
$data['code'] = $authorizationCode;
$data['redirect_uri'] = $callbackURL;
or even shorter
$data = array("grant_type" => "authorization_code", "code" => $authorizationCode, "redirect_uri" => $callbackURL);
Hope this helped!
OK, so I dug a little digging and found some code in the PHP CURL manual comments section. The problem with Spotify's documentation is it doesn't specify the format of the POST data to be sent. I assumed since Spotify was sending me JSON data that I should be sending my data in JSON format as well. So I was formatting the POST data as such:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
After reading through some documentation I decided to try this instead:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
I got exactly the results I needed:
{"access_token":"[long access token]","token_type":"Bearer","expires_in":3600,"refresh_token":"[long refresh token]"}
Thank you, Michael, for attempting to assist!
$data = file_get_contents("http://randomword.setgetgo.com/get.php");
var_dump($data);
I keep getting false when sending this get request, anyone have an idea why?
It works just fine with a simple php script I wrote hosted from the same domain, might that be the issue, how do I go about sending a get request to this API if that is the case?
I tried using curl as well with the same result. It works with my test script but not the API.
As noted in the various comments above, the code originally posted works fine for me but not for the OP - most likely due to a restriction placed upon various standard PHP functions by the webhost. As an alternative, cURL should be able to retrieve the content unless a similar restriction has been placed on standard curl functions too.
$url='http://randomword.setgetgo.com/get.php';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_USERAGENT, 'curl-wordfetcher' );
$result = curl_exec( $ch );
if( curl_errno( $ch ) ) echo 'Curl error: ' . curl_error( $ch );
curl_close( $ch );
print_r( $result );