# preference/form/nc/erp-sync/netvisor/netvisor-hmacsha256-test.py
# see: https://support.netvisor.fi/fi/support/solutions/articles/77000557880-api-autentikointi
import random, time, hmac, hashlib
#Url, where the request is sent
url = "https://isvapi.netvisor.fi/accounting.nv"

#Give variables
sender = "ClientName"
customerId = "Integraatiokayttajan tunnus"
partnerId = "7f94228d149a96b2f25e3edad55096e"
transactionId = "123456" #"TRANSID"+"%0.12d" % random.randint(0,99999999) #Generate random TransactionId, type string
timestamp = "2023-05-04 12:00:00.000" # time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
timestampUnix = "1683147600" #int(time.time())
language="FI"
organisationId="1967543-8" #Netvisor environment's organisation id / business idcustomerKey = "XXX"
partnerKey = "7f94228d149a96b2f25e3edad55096e"
customerKey = "7cd680e89e880553358bc07cd28b0ee2"


#MAC calculation
hmacsha256string1 = url+"&"+sender+"&"+customerId+"&"+timestamp+"&"+language+"&"+organisationId+"&"+transactionId+"&"+str(timestampUnix)+"&"+customerKey+"&"+partnerKey
key1 = customerKey+"&"+partnerKey
hmacsha256string = "https://isvapi.netvisor.fi/accounting.nv&ClientName&Integration user identifier&2023-05-04 12:00:00.000&FI&1967543-8&123456&1683147600&7cd680e89e880553358bc07cd28b0ee2&7f94228d149a96b2f25e3edad55096e"
key = "7cd680e89e880553358bc07cd28b0ee2&7f94228d149a96b2f25e3edad55096e"
print("hmacsha256string 1: " + hmacsha256string1)
print("hmacsha256string 2: " + hmacsha256string)
print("key 1: " + key1)
print("key 2: " + key)
h_mac = hmac.new(bytes(key1, "ISO-8859-1"), bytes(hmacsha256string1, "ISO-8859-1"), hashlib.sha256).hexdigest()
print("HMACSHA256 MAC 1: " + h_mac)
h_mac = hmac.new(bytes(key, "ISO-8859-1"), bytes(hmacsha256string, "ISO-8859-1"), hashlib.sha256).hexdigest()
print("HMACSHA256 MAC 2: " + h_mac)

#HTTP headers
headers = {
    "Content-Type": "text/plain",
    "X-Netvisor-Authentication-Sender": sender,
    "X-Netvisor-Authentication-CustomerId": customerId,
    "X-Netvisor-Authentication-PartnerId": partnerId,
    "X-Netvisor-Authentication-Timestamp": timestamp,
    "X-Netvisor-Authentication-TimestampUnix": str(timestampUnix),
    "X-Netvisor-Authentication-TransactionId": transactionId,
    "X-Netvisor-Interface-Language": language,
    "X-Netvisor-Organisation-Id": organisationId,
    "X-Netvisor-Authentication-MAC": h_mac,
    "X-Netvisor-Authentication-MACHashCalculationAlgorithm": "HMACSHA256"
}
