Een token voor Logic4 authenticatie kan met verschillende programmeertalen worden gemaakt. Deze token moet aan de autorisatieheader worden toegevoegd bij elke API request.
Deze pagina bevat voorbeelden voor C#, PHP, PowerShell en Javascript.
In dit voorbeeld wordt een token aangemaakt en toegevoegd aan HttpClient
, waarmee vervolgens een request wordt gedaan. Let op, in dit voorbeeld is er geen UserBearer toegevoegd.
public class Logic4ApiClient
{
public void GetProducts()
{
var values = new ApiSettings
{
AdminstrationId = "1",
CompanyKey = "xxx",
PublicKey = "xxxxxxxxxxxxxxxxx",
SecretKey = "xxxxxxxxxxxxxxxxx",
ApiURL = "https://api-v2.logic4.nl/",
Userid = 2000000
};
var task = GetProductsJson(GetHttpClient(values, "POST"));
var responseFromApi = task.Result;
}
public class ApiSettings
{
//Publickey verkregen via Logic4
public string PublicKey { get; set; }
//CompanyKey verkregen via Logic4
public string CompanyKey { get; set; }
//SecretKey verkregen via Logic4
public string SecretKey { get; set; }
//Vul hier het administratieId in, standaard is dit 1
public string AdminstrationId { get; set; }
//User bearer is optioneel, wordt gebruikt voor bepaalde API requests
public string UserBearer { get; set; }
//Vul hier de API URL in, vb: "https://api-v2.logic4.nl/"
public string ApiURL { get; set; }
//Logic4 gebruikersId
public int UserId { get; set; }
}
public HttpClient GetHttpClient(ApiSettings values, string requestMethod = "GET")
{
//Gebruik van IHttpFactory is aanbevolen, maar voor eenvoud een instantiatie
var client = new HttpClient();
//Als de beareraanwezig is toevoegen aan de headers
if (!string.IsNullOrEmpty(values.UserBearer))
{
client.DefaultRequestHeaders.Add("x-Logic4-userbearer", values.UserBearer);
}
DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - epochStart;
string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();
//create random nonce for each request
string nonce = Guid.NewGuid().ToString("N");
//Creating the raw signature string
string signatureRawData = $"{values.PublicKey}{values.CompanyKey}{requestMethod}{requestTimeStamp}{nonce}";
var secretKeyByteArray = Convert.FromBase64String(_values.SecretKey);
byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);
using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray))
{
byte[] signatureBytes = hmac.ComputeHash(signature);
string requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-LOGIC4-Authorization",
$"{values.PublicKey}:{values.CompanyKey}:{requestSignatureBase64String}:{nonce}:{requestTimeStamp}:{values.AdminstrationId}:{values.UserId}");
client.DefaultRequestHeaders.Date = DateTime.UtcNow;
}
return client;
}
public async Task GetProductsJson(HttpClient client)
{
var filter = new ProductFilter
{
ProductCode = "testartikel"
};
string ags = JsonConvert.SerializeObject(filter);
var response = await client.PostAsync(
"https://api-v2.logic4.nl/Product/GetProducts",
new StringContent(ags, Encoding.UTF8, "application/json"));
var content = await response.Content.ReadAsStringAsync();
return content;
}
public class ProductFilter
{
public string ProductCode { get; set; }
}
}
Voorbeeldscript met PHP:
function GetAuthToken() {
$public_key = 'xxx';
$private_key = 'xxx';
$company_key = 'xxx';
$administration = 1;
$user_id = 2000000;
$timestamp = time();
$secret_key_byte_array = base64_decode($private_key);
$nonce = base64_encode($private_key.$timestamp);
$hashedstring = $public_key.$company_key.'GET'.$timestamp.$nonce;
$hash = base64_encode(hash_hmac('sha256', $hashedstring, $secret_key_byte_array, true));
$authToken = "{$public_key}:{$company_key}:{$hash}:{$nonce}:{$timestamp}:{$administration}:{$user_id}";
return $authToken;
}
function GetWebShopUserTypes() {
$client = new GuzzleHttp\Client([
'headers'=> [
'X-LOGIC4-Authorization' => GetAuthToken()
]
]);
$response = $client->request('GET', 'https://api-v2.logic4.nl/Webshop/GetWebShopUserTypes');
var_dump((string)$response->getBody());
}
GetWebShopUserTypes();
Voorbeeldscript om een token aan te maken met Powershell:
$timestamp = [int64](([datetime]::UtcNow)-(get-date "1/1/1970")).TotalSeconds
$public_key = 'xxx';
$private_key = 'xxx';
$company_key = 'xxx';
$administration = 1;
$user_id = 2000000;
$nonceString = [System.Text.Encoding]::UTF8.GetBytes($private_key + $timestamp)
$nonce = [System.Convert]::ToBase64String($nonceString)
$hashedstring = $public_key + $company_key + "GET" + $timestamp + $nonce;
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [System.Convert]::FromBase64String($private_key)
$hash = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($hashedstring))
$hash = [System.Convert]::ToBase64String($hash)
$authToken = "$($public_key):$($company_key):$($hash):$($nonce):$($timestamp):$($administration):$($user_id)";
Write-Output($authToken)
In Postman kan met Javascript een token worden aangemaakt:
pm.environment.unset("auth_token");
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
var uuid = parseInt(uuidv4(), 30).toString();
var timestamp = Math.floor(Date.now() / 1000);
timestamp = ''.concat(timestamp, uuid.substr(uuid.length - 4));
var nonce = btoa(''.concat(pm.environment.get('private_key'), timestamp));
var hashed_string = ''.concat(pm.environment.get('public_key'),
pm.environment.get('company_key'), pm.request.method, timestamp, nonce);
var secret_key_byte_array = CryptoJS.enc.Base64.parse(pm.environment.get('private_key'));
var sha256digest = CryptoJS.HmacSHA256(hashed_string, secret_key_byte_array);
var hash_string = CryptoJS.enc.Base64.stringify(sha256digest);
var auth_token = ''.concat(pm.environment.get('public_key'), ':',
pm.environment.get('company_key'), ':',
hash_string, ':',
nonce, ':',
timestamp, ':',
pm.environment.get('database'), ':',
pm.environment.get('user_id'));
pm.environment.set('auth_token', auth_token);