Suppose i have an api key and by this api key i want to fetch data this is my code.
$apiKey = 'admin#123';
$headers = array(
'Content-Type:application/json',
'Authorization: '.$apiKey
);
$payload = array(
'id' => 1,
);
$process =
curl_init('http://localhost/codeigniterapi/api/example/user_fetch');
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payload);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
print_r($return);
But it shows an error charset=utf-8 {"status":false,"error":"Invalid API key "} but this api work perfectly on postman using same key
Sending the authorization header with the request requires you to add a bearer and a token.
If you used postman to test the request, you prolly entered the username and password in the "Authorization" tab inside postman. You will also have chosen a type for the authorization.
On the second tab, the Headers tab, you can now see that Postman has added your crendentials from the first tab as an authorization header. The key will be "Authorization" and you can steal the Value from this table. As you can see, this contains both the bearer (for Basic Auth, this will be "Basic") and the token itself.
If you want to send the token in the authorization header, it would look like this:
$headers = array(
'Content-Type:application/json',
'Authorization: Basic abcdefghijklmnop'
);
If you don't want to set the header yourself, you can use
You can set the CURLOPT_USERPWD if you want to use the user and password (example for basicauth):
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "$username:$password");
To set the curloption for username and password.
Related
i have curl command provided by some developer, i need to know how to call it in php.
Command is :
curl -H "x-api-key:Â xxxxxxxxxxxxxxxxxxxxxx"
"https://api.civicengine.com/office-
holders?address=1060+W+Addison+Chicago+IL"
i have written this
$data['api-key']='xxxxxxxxxxxxxxxxxxxxx';
/*$data['host']='https://api.civicengine.com';*/
$url='https://api.civicengine.com/office-holders?address=1060+W+Addison+Chicago+IL';
$ch = curl_init();
// set basic auth
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// set header accept
$headers = array('Accept:application/json', 'Accept-Language:en_US',"Authorization: Bearear xxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// set mode to POST
curl_setopt($ch, CURLOPT_POST, 1);
// add post fields (1)
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
print_r($result = json_decode(curl_exec($ch)));die;
i expect result but its giving
stdClass Object ( [message] => Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=FLUdjGvxuJ9liutivB0Ll5LW2t2xmv31lvK2guQi )
you forgot to add the x-api-key header to your php curl_ code. also your php code is altering the Accept Accept-Language, and Authorization header, your curl invocation proves that's not needed, and they may be incorrect to boot (idk), get rid of them while debugging (and once everything is working, you may add them back and check that they don't break anything..)
Follow this method to send api_key in header of API REQUEST
// Collection object
$ch = curl_init($url);
$headers = array(
"APIKEY: PUT_HERE_API_KEY",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlreq);
$result = curl_exec($ch); // execute
$result;
//show response
curl_close($ch);
To authenticate API calls, you must first generate a session to get a token. Then you must send the session token as the value of the X-Auth-Token header to authenticate API calls.
To create a session you first need to manually generate an API Key. This is a key/value pair that can be generated in the API Access page. When you click Generate New API Key, a popup will be displayed with the API Key Value and in the table of Active Keys you can find the API Key ID. This is then sent via Basic Authentication in a POST call to the sessions route.
I followed this Api Documentation of deepcrawl already but what am I doing wrong?
I have X-Auth-Token and API KEY ID where should I put this?
$deephead = "X-Auth-Token: asdjasiojqoieuqiouwqpofoqwojeq";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.deepcrawl.com/sessions");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $deephead);
// Get the response
$response = curl_exec($ch);
// Close cURL connection
curl_close($ch);
// Decode the response (Transform it to an Array)
$result = json_decode($response);
//debug the response
dd($result);
The I can't even get to CURLOPT_GET cause at my post I only get null value. Any idea/thoughts how can I fix this. Thank you in advance.
DeepCrawl API
It looks like you are trying to generate a token, which it looks like you already have.
To authenticate API calls, you must first generate a session to get a
token. Then you must send the session token as the value of the
X-Auth-Token header to authenticate API calls.
To create a session you first need to manually generate an API Key.
This is a key/value pair that can be generated in the API Access page.
When you click Generate New API Key, a popup will be displayed with
the API Key Value and in the table of Active Keys you can find the API
Key ID. This is then sent via Basic Authentication in a POST call to
the sessions route.
curl -X POST -u '123:abcdef' https://api.deepcrawl.com/sessions {
"token":"abcdef123", "_user_href":"/users/example-user", ... }
Not the clearest, but it's right there.
$headers = [
'Content-Type: application/x-www-form-urlencoded',
'accept: text/html'
];
$username='yourusername';
$password='supersecret';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.deepcrawl.com/sessions");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "root=1");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Get the response
$response = curl_exec($ch);
// Close cURL connection
curl_close($ch);
// Decode the response (Transform it to an Array)
return json_decode($response);
That will return something like
{
"token":"abcdef123",
"_user_href":"/users/example-user",
...
}
Since you already have the token, you don't need ot hit session. you can just make your calls.
$headers = [
'X-AUTH-TOKEN: your-api-key',
'accept: text/html'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.deepcrawl.com/system_statuses");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Get the response
$response = curl_exec($ch);
// Close cURL connection
curl_close($ch);
// Decode the response (Transform it to an Array)
return json_decode($response);
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
I have built a prototype calendar synching system using the Google calendar API and it works well, except refreshing access tokens. These are the steps I have gone through:
1) Authorised my API and received an authorisation code.
2) Exchanged the authorisation code for Access Token and a RefreshToken.
3) Used the Calendar API until the Access Token expires.
At this point I try to use the Refresh Token to gain another Access Token, so my users don't have to keep granting access because the diary sync happens when they are offline.
Here's the PHP code, I'm using curl requests throughout the system.
$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = array("grant_type" => "refresh_token",
"client_id" => $clientID,
"client_secret" => $clientSecret,
"refresh_token" => $refreshToken);
$headers[0] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);
The response i'm getting is:
[error] => invalid_request
[error_description] => Required parameter is missing: grant_type
No curl errors are reported.
I've tried header content-type: application/x-www-form-urlencoded, and many other things, with the same result.
I suspect it's something obvious in my curl settings or headers as every parameter mentioned in the Google documentation for this request is set. However, I'm going around in circles so would appreciate any help, including pointing out any obvious errors I've overlooked.
your request should not post JSON data but rather query form encoded data, as in:
$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = "grant_type=refresh_token&client_id=$clientID&client_secret=$clientSecret&refresh_token=$refreshToken";
$headers[0] = 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);
Not being able to authenticate Google Spreadsheet API.
I'm using this code stolen from here,
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "MY_EMAIL#GOOGLE.COM",
"Passwd" => "MY_EMAIL_PASS",
"service" => "writely",
"source" => "MY_APPLICATION_NAME"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute
$response = curl_exec($curl);
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth; //this worked!
So this works and now I have a key But actually using it...with the bellow code gives me a user not authenticated error:
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$key = 'MY_KEY';
// Make the request
curl_setopt($curl, CURLOPT_URL, 'https://spreadsheets.google.com/tq?tqx=version:0.6;out:json&key='.$key);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
$response = curl_exec($curl);
curl_close($curl);
var_dump ($response);
this gives me
string(272) "google.visualization.Query.setResponse({version:'0.6',status:'error',errors:[{reason:'user_not_authenticated',message:'User not signed in',detailed_message:'\u003ca target=\u0022_blank\u0022 href=\u0022http://spreadsheets.google.com/\u0022\u003eSign in\u003c/a\u003e'}]});"
So apparently it is not able to use the authentication key for the Google Visualization Query Language.. what am I doing wrong?
Thank you so much!
I would try the following modifications in the code that uses google authentication string:
add urlencode
$headers = array(
"Authorization: GoogleLogin auth=" . urlencode($auth),
"GData-Version: 3.0",
);
and skip verifying SSL sertificates:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
I've described my experience implementing authentication with CURL in this post. There you'll find some tips on debugging CURL requests.