I'm developing a restful API with laravel. Authorization is done using a SECRET_KEY & PUBLIC_KEY as shown in the sample request code below.
How do i retrieve the Authorization header key value from the Request?
I would also appreciate links to any resources that would guide me through better implementation & best practice in creating a Restful API with Laravel.
$curl = curl_init();
$url = "http://api.example.com/v1/users";
$secretKey = env('SECRET_KEY');
$publicKey = env('PUBLIC_KEY');
$firstName = "John";
$lastName = "Doe";
$email = "example#gmail.com";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"firstName\": \"$firstName\",\r\n \"lastName\": \"$lastName\",\r\n \"email\": \"$email\",\r\n \"secretKey\": \"$secretKey\",\r\n}",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
'Authorization: Bearer ' . $publicKey,
),
));
$response = curl_exec($curl);
curl_close($curl);
The request() helper contains everything from the request.
Just dd(request()->header()) to see the full list of the request headers.
You can check the official documentaion : https://laravel.com/docs/7.x/eloquent-resources#introduction
Also you might want to use a tool like Postman to test your API easily.
Related
I am attempting to do an API call to the following: https://learn.microsoft.com/en-us/partner-center/develop/get-a-price-sheet To get a price sheet for a given market and view. But i can not make it work.
I got a token using https://login.microsoftonline.com/x/oauth2/token
But when I try to call the following API: https://api.partner.microsoft.com/v1.0/sales/pricesheets(Market='be',PricesheetView='updatedlicensebased')/$value
I get a
401, "Unauthorized: Invalid Authorization header"
Can someone give me some advice to what could be the problem? Thanks.
in your POST request to https://login.microsoftonline.com/x/oauth2/token you should use a 'resource' => 'https://api.partner.microsoft.com'.
This PHP code works for me:
public static function getTokenFromCode($code){
$data = array(
'resource' => 'https://api.partner.microsoft.com',
'client_id' => $appId,
'code' => $code,
'redirect_uri' => $redirectURL,
'grant_type' => 'authorization_code',
'client_secret' => $appKey
);
$header = array(
'Accept: application/json',
'return-client-request-id: true',
'Expect: 100-continue'
);
$token = self::callApi("POST", 'https://login.microsoftonline.com/'.$accountId."/oauth2/token", $header, $data);
return $token;
}
public static function getNcePriceList($timeline = "current"){
$header = array(
'Authorization: Bearer '.$token['access_token'],
'Host: api.partner.microsoft.com',
);
return self::callApi("GET", "https://api.partner.microsoft.com/v1.0/sales/pricesheets(Market='DE',PricesheetView='updatedlicensebased')/\$value?timeline=".$timeline, $header);
}
We are getting the following error when executing this:
[description] => Authentication values are missing [code] => 1001
Can anyone see what I am doing wrong.
I tried removing the base64_encode function but this didn't have any impact.
I got the integration key and password from opayo (sagepay) - the test environment.
My php code follows:
$key = base64_encode("My Integration Key");
$password = "My Integration Password";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/merchant-session-keys",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{ "vendorName": "MY VENDOR" }',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $key:$password",
"Cache-Control: no-cache",
"Content-Type: application/json"
)
));
$response = curl_exec($curl);
$response = json_decode($response, true);
$err = curl_error($curl);
curl_close($curl);
Tia for any help
Both the key and password had to be base 64 encoded.
ie $key = base64_encode("My Integration Key:My Integration Password");
and then fed in to the curl http header as
"Authorization: Basic $key",
I had the same issue, so created a NuGet package for this API-client code: https://github.com/joeratzer/opayo-admin-and-reporting-api-client.
You can find the NuGet package here:
https://www.nuget.org/packages/Joe.Opayo.Admin.Api.Client/1.1.0
The client app allows code like this:
var client = new OpayoAdminApiClient();
var isTest = true;
var request = new OpayoApiRequest(ApiCommandType.GetTransactionDetail, "password", isTest, "user-name", "vendor-name");
var commandSpecificXml = "<vendortxcode>01Jan2010Transaction12345</vendortxcode>";
return await client.ProcessApiCommandAsync<TransactionDetail>(request, commandSpecificXml);
Please I need to send daily a group of data from my LARAVEL application using Sendinblue API [this how the external server API looks like ( api.sendinblue.com/v3/contacts/identifier ) ], I've managed to used Sendinblue PHP code to send one contact on the time.
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.sendinblue.com/v3/contacts/identifier",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\"attributes\":{\"newKey\":\"New Value\"}}",
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Content-Type: application/json",
"api-key: My API"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
My question there is a way to send all data at once and daily in an automatic way?
Should I use a For each in the controller or there is another ways?
Thank you in advance.
Yes, you can do it with Laravel scheduler.
Read More about scheduler
I am having issues in accessing contact from Xero. I keep getting an error - AuthorizationUnsuccessful
Below please find the code I am using to send my request as well as the response I am getting:
'scopes' => (
'openid',
'email',
'profile',
'offline_access',
'accounting.settings',
'accounting.contacts'
)
in my xero config file
Request passing in Postman
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.xero.com/api.xro/2.0/Contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer eyJh.......N6mbaw",
"cache-control: no-cache",
"postman-token: 51048d11-4f31-ba27-16c7-48739f14c6f0",
"xero-tenant-id: e8672ad4-ea92-4698-87aa-a69f5b049265"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
Response:
{
"Type": null,
"Title": "Unauthorized",
"Status": 401,
"Detail": "AuthorizationUnsuccessful",
"Instance": "14ae9993-dc1b-4d8d-a4c0-15b2c343f337",
"Extensions": {}
}
Your assistance would be greatly appreciated.
In your headers, I don't think there is no need for postman-token, so it should look like,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Authorization: Bearer eyJh.......N6mbaw",
"Cache-control: no-cache",
"Xero-tenant-id: e8672ad4-ea92-4698-87aa-a69f5b049265"
)
Note the capital first letters.
The other option, easier & more organised one is to use guzzle, as you are using laravel(if > 5.1), you have guzzle already in laravel or can use HTTP Client even.
Using Guzzle
You can use Guzzle to handle curl requests,
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
public function yourFunction()
{
try {
$client = new Client();
$guzzleResponse = $client->get(
'https://api.xero.com/api.xro/2.0/Contacts', [
'headers' => [
"Accept" => "application/json",
"Authorization" => "Bearer eyJh.......N6mbaw",
"Cache-control" => "no-cache",
"Xero-tenant-id" => "e8672ad4-ea92-4698-87aa-a69f5b049265"
],
'allow_redirects' => [
'max' => 10,
],
'connect_timeout' => 30
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
}
} catch (RequestException $e) {
// you can catch here 400 response errors and 500 response errors
// see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600
} catch(Exception $e){
//other errors
}
}
You can refer more about guzzle from guzzle docs
I want to create a label in gmail account using goggle admin sdk api.
I am sending a Http Post Request to
https://apps-apis.google.com/a/feeds/emailsettings/2.0/{domain}/{username}/label/
But i get this response :-
Invalid domain.
Error 403
Following is the code for this task :-
$domain = explode('#',$user->email);
$headers = array(
"X-HTTP-Method-Override: POST",
"Authorization: {$obj->token_type} "." {$obj->access_token}",
"Content-type: application/atom+xml",
);
$options = array(CURLOPT_URL => "https://apps-apis.google.com/a/feeds/emailsettings/2.0/$domain[1]/$domain[0]/label",
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => 1,
// CURLOPT_USERAGENT => '',
CURLOPT_FOLLOWLOCATION => 1,
// CURLOPT_VERBOSE => 1,
// CURLOPT_POST => true
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
echo "<pre>";print_r($result);echo"</pre>";
If you actually trying to access labels on your gmail.com account from your domain's admin account, it will not work. The email setting API works only on Premier and Edu Google Apps domains administrators.