I am trying to create the proper signature for the Ascentis API. There documentation is http://www.ascentis.com/API/Ascentis_API_Documentation.pdf. Page 4 describes the Signature format.
Here is my PHP code. Am I doing something wrong? I get a "not authorized error".
$url='https://selfservice2.ascentis.com/mycompany/api/v1.1/employees';
$timestamp=gmdate('Y-m-d\TH:i:s\Z');
$path=strtolower(str_replace('https://selfservice2.ascentis.com','',$url));
$signature_string="GET {$path} {$timestamp}";
$signature=hash_hmac("sha1",$signature_string,$secret_key);
$authorization=encodeUrl($client_key).':'.encodeUrl($signature);
Here's a more complete example. Props to #Steve Lloyd for getting me in the right direction.
$codes['secret_key'] = 'my_secret';
$client_key = 'my_key';
$url = 'https://selfservice.ascentis.com/my_company/api/v1.1/employees?lastname=%s';
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
$path = strtolower(str_replace('https://selfservice.ascentis.com', '', $url));
$signature_string = "GET {$path} {$timestamp}";
$signature = base64_encode(hash_hmac("sha1", $signature_string, $codes['secret_key'], TRUE));
$authorization = urlencode($client_key) . ':' . urlencode($signature);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: " . $authorization,
"Accept: application/xml",
"Timestamp: " . $timestamp,
]);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$data = curl_exec($ch);
$info = curl_getinfo($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "Received $httpcode from $url\n";
echo "Key: $client_key\n";
echo "Signature: $signature\n";
echo "authorization: $authorization\n";
echo "request info:" . var_export($info, TRUE) . "\n";
echo "data:\n";
var_export($data, TRUE)
After playing the trial and error game I was able to get this working. It turns out that you have to set hash_hmac to raw_output. Here is the working code:
$url='https://selfservice2.ascentis.com/mycompany/api/v1.1/employees';
$timestamp=gmdate('Y-m-d\TH:i:s\Z');
$path=strtolower(str_replace('https://selfservice2.ascentis.com','',$url));
$signature_string="GET {$path} {$timestamp}";
$signature=base64_encode(hash_hmac("sha1",$signature_string,$codes['secret_key'],true));
$authorization=encodeUrl($client_key).':'.encodeUrl($signature);
Related
I'm trying to learn the shopify api for a project. Tried a few pasted codes on their forum, adapting my code to theirs.
The documentation says to do the authentication this way, by providing the following:
https://{username}:{password}#{shop}.myshopify.com/admin/api/{api-version}/{resource}.json
{username} — The API key that you generated
{password} — The API password
{shop} - The name that you entered for your development store
{api-version} — The supported API version you want to use
{resource} — A resource endpoint from the REST admin API
I'm trying to do a GET request on all the orders made on the store.
/ info
$API_KEY = '75c89bf******ea919ce****7702';
$PASSWORD = '2061******82d2802**f***9403';
$STORE_URL = '*****-na-***-c***.myshopify.com';
$AUTHORIZATION = base64_encode($API_KEY . ':' . $PASSWORD);
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . '/admin/api/2020-01/orders.json';
$header = array();
$header[] = 'Accept: application/json';
$header[] = 'Content-Type: application/json';
$header[] = 'Authorization: Basic ' . $AUTHORIZATION;
$session = curl_init();
//options
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_HTTPHEADER, $header);
curl_setopt($session, CURLOPT_GET, 1);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//exec
$response = curl_exec($session);
curl_close($session);
print_r($response);
// error
if($response === false)
{
print_r('Curl error: ');
}
The code doesn't work at all, without any error code, completly blank, with only the first project echo showing.
I verified my API keys and they are working, I can insert them manually into chrome.
You don't need the header for authorization. Your code should like:
$API_KEY = '75c89bf******ea919ce****7702';
$PASSWORD = '2061******82d2802ff***9403';
$STORE_URL = 'porcao-na-sua-casa.myshopify.com';
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . '/admin/api/2020-01/orders.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE) //can check status code, requst successfully processed if return 200
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Found the problem when I ran in terminal, did not install php-curl on this machine.
#Kshitij solution worked, just like mine, when curl was properly installed.
// Provide the required parameters like store url , endpoint etc.
function shopifyApiCall($STORE_URL ,$query = [], $endpoint, $API_KEY, $PASSWORD){
//API_Key : your API key, you can get it from your APP setup.
//Password : Your Access Token
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($query));
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error_number = curl_errno($ch);
$error_message = curl_error($ch);
curl_close($ch);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
//return array('headers' => $headers, 'response' => $response[1]);changed headers
return array('headers' => $header_data, 'response' => $response[1]);
}
}
I'm trying to POST an image on Mastodon (specifically on Humblr) but I cannot get the media_id, the response is null, but I'm not sure where the problem is.
I can publish text, no problem, so the authentication part is fine, I only have the problem with the image, the only difference I can see in the documentation is that "Media file encoded using multipart/form-data".
Here's my code so far...
$headers = ['Authorization: Bearer '.$settings['access_token'] , 'Content-Type: multipart/form-data'];
$mime_type = mime_content_type($urlImage);
$cf = curl_file_create($urlImage,$mime_type,'file');
$media_data = array( "file" => $cf);
$ch_status = curl_init();
curl_setopt($ch_status, CURLOPT_URL, "https://humblr.social/api/v1/media");
curl_setopt($ch_status, CURLOPT_POST, 1);
curl_setopt($ch_status, CURLOPT_POSTFIELDS, $media_data);
curl_setopt($ch_status, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_status, CURLOPT_HTTPHEADER, $headers);
$media_status = json_decode(curl_exec($ch_status));
echo "Response: ".json_encode($media_status);
From this I want to extract the $media_status-> media_id
I don't really know much about 'multipart/form-data' to be honest.
Am I missing something?
This took some trial and error for me as well. Here's what worked for me (PHP 7.3):
$curl_file = curl_file_create('/path/to/file.jpg','image/jpg','file.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://instanceurl.com/api/v1/media');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer YOUR_TOKEN_HERE',
'Content-Type: multipart/form-data'
]);
$body = [
'file' => $curl_file
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$response = curl_exec($ch);
if (!$response) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
echo 'Response Body: ' . $response . PHP_EOL;
curl_close($ch);
why some url with json content return null on php function get page content?
i used these ways :
file_get_content
curl
http_get
but return null . but when page open with browser json content show on browser ?? anyone can help me?
$url = 'https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/?access_token=9IaRpdmQzFppJMabLHbHyzBaQnm8bM';
$result = file_get_content($url);
return null but in browser show
{"error_description": "Access token has expired.", "error": "invalid_credentials"}
It returns the following:
failed to open stream: HTTP request failed! HTTP/1.1 401 UNAUTHORIZED
So, you have to be authorized.
You ca play with this code snippet (I can't test since token expired again):
<?php
$access_token = "s9spZax2Xrj5g5bFZMJZShbMrEVjIo"; // use your actual token
$url = "https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/";
// Solution with file_get_contents
// $content = file_get_contents($url . "?access_token=" . $access_token);
// echo $content;
// Solution with CURL
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Basic " . $access_token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url); // . $params - if you need some params
curl_setopt($ch, CURLOPT_POST, false);
// curl_setopt($ch, CURLOPT_USERPWD, $userPwd);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($ch_error) {
throw new Exception("cURL Error: " . $ch_error);
}
if ($info["http_code"] !== 200) {
throw new Exception("HTTP/1.1 " . $info["http_code"]);
}
echo $result;
i have to add interswitch payment methods in my web application but i am receiving error
following is my code
function billersCategories()
{
$nonce=$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 60);
$date = new DateTime();
$timestamp=$date->getTimestamp();
// Signature
$httpMethod = "GET";
$url='https://sandbox.interswitchng.com/api/v2/quickteller/categorys';
$clientId = "IKIA9D98ABCDEFGHIFAKEID1E09104959B9755C41E1";
$clientSecretKey = "d5uAr+U8QhSv8vQtKPDIUI62327Fsfsfsf65=";
$signatureCipher = $httpMethod."&".$url."&".$timestamp."&".$nonce."&".$clientId."&".$clientSecretKey;
$signature = base64_encode($signatureCipher);
$data = array("TerminalID" => "9APY556261");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Authorization:InterswitchAuth SUtJQTUyNTBERkY1NkU5MzM2OUM0RkRBRjMxQTQ3QTg1RkNDODYyRTRDOUU=',
'Signature:'.$signature,
'Nonce:'.$nonce,
'Timestamp:'.$timestamp,
'SignatureMethod:SHA512'
));
$result = curl_exec($ch);
echo curl_getinfo($ch) . '<br/>';
echo curl_errno($ch) . '<br/>';
echo curl_error($ch) . '<br/>';
var_dump($result);
}
But i am receiving following error
"The HTTP method is not supported for this resource", i tried http method POST but same error, i am new on API can someone please help me to solve this .
Use this instead, fill the following
In the variable
- $clientId
- $clientSecretKey
At the header
- TerminalID
<?php
$nonce=$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 60);
$date = new DateTime();
$timestamp=$date->getTimestamp();
$httpMethod = "GET";
$clientId = "YOUR_OWN_ID";
$clientSecretKey = "YOUR_OWN_CLIENT_SECRET_KEY";
$resourceUrl='https://sandbox.interswitchng.com/api/v2/quickteller/categorys';
$resourceUrl = strtolower($resourceUrl);
$resourceUrl = str_replace('http://', 'https://', $resourceUrl);
$encodedUrl = urlencode($resourceUrl);
$transactionParams = "1";
$httpMethod = "GET";
$signatureCipher = $httpMethod . '&' . $encodedUrl . '&' . $timestamp . '&' . $nonce . '&' . $clientId . '&' . $clientSecretKey;
if (!empty($transactionParams) && is_array($transactionParams)) {
$parameters = implode("&", $transactionParams);
$signatureCipher = $signatureCipher . $parameters;
}
$signature = base64_encode(sha1($signatureCipher, true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$resourceUrl);
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type:application/json',
'Authorization:InterswitchAuth SUtJQTAzREM3RDY5NUREMzZFQURFNTQxNEE2Nzg1MUJCMUZFQ0Y5MUIxRjg=',
'Signature:'.$signature,
'Nonce:'.$nonce,
'Timestamp:'.$timestamp,
'SignatureMethod:SHA1',
'TerminalID:YOUR_ASSIGNED_TERMINAL_ID'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
echo $server_output;
?>
This worked for me, hope it help someone in future
I have a sand box account in fortnox and i am trying to get the access token using following code, but i keep getting same error:
$requestMethod = "GET";
$ch = curl_init();
$options = array(
'Authorization-Code: '. AUTHORIZATION_CODE .'',
'Client-Secret: '. CLIENT_SECRET .'',
'Content-Type: '. CONTENT_TYPE .'',
'Accept: '. ACCEPTS .''
);
curl_setopt ($ch, CURLOPT_CAINFO, "/xampp/htdocs/cacert.pem");
curl_setopt($ch, CURLOPT_URL, "https://api.fortnox.se/3/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $options);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod);
$curlResponse = curl_exec($ch);
$info = curl_getinfo($ch);
//echo 'Took ' . $info['total_time'] . ' seconds for url ' . $info['url'];
echo $curlResponse;
if ($curlResponse === FALSE) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
Error: PHP / 4.5.37 Can not sign in , access tokens , or client- secret missing ( 2000311 ) .
I get the Access-Token using the following code which is very close to your code. It worked fine for me.
Your error is described on the Errors page, but it adds nothing new to the text you already shown.
Please note that you can retrive the Access-Token only once, check Authentication section in the Fortnox documentation.
An Access-Token can only be retrieved once with every Authorization-Code, multiple requests with the same Authorization-Code will make both the Authorization-Code and the Access-Token invalid.
public function actionRetrieveAccessToken($authCode, $clientSecret)
{
$headers = [
'Authorization-Code: ' . $authCode,
'Client-Secret: ' . $clientSecret,
'Content-Type: application/json',
'Accept: application/json',
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.fortnox.se/3/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$responseText = curl_exec($curl);
$response = json_decode($responseText, true);
if (isset($response['ErrorInformation'])) {
echo 'Request failed with error messages:' . PHP_EOL;
echo $response['ErrorInformation']['Error'] . ': ';
echo $response['ErrorInformation']['Message'];
echo ' (' . $response['ErrorInformation']['Code'] . ')' . PHP_EOL;
} else {
echo 'Access Token: ' . $response['Authorization']['AccessToken'] . PHP_EOL;
}
}
$content_type = 'application/json';
$api_url="api url here";
$curl = curl_init();
$headers = array(
'Content-Type: '.$content_type.'',
'Authorization : '.'Bearer ' . $this->access_token
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($data))
{
$data = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($curl);
logthis($response,"utils");
curl_close($curl);