Signing API requests
General requirements for requests:
- Must use HTTPS.
- Must contain the
apikey
parameter. To learn more, see API Key. - Must be signed, with the signature added to the
X-YaCourier-Signature
header. - The
user_agent
used to form the signature must be passed in theheaders
.
Signature calculation algorithm
The signature is calculated using a 32-character secret (obtained from the client manager or support) and the SHA-256 algorithm. Once calculated, the signature is converted to HEX format.
Warning
The secret is not a signature but it's used for its calculation.
Forming a signature involves:
- User agent
- POST and GET request methods
- Request-URI (starts with
/
, no host specified) - Message body
General description of the algorithm:
items_to_sign = { user_agent, method, " ", uri, body }
signature = HMAC(<secret>)
for item in items_to_sign:
signature = HMAC(signature, item)
headers['X-YaCourier-Signature'] = hex_encode(signature)
Sample (based on the randomly generated cb6628c7407fd3c570bebbd7c36731f1
secret):
python2
python3
php
import hashlib
import hmac
KEY = "cb6628c7407fd3c570bebbd7c36731f1"
USER_AGENT = "TestUserAgent"
URI = "/test/uri"
BODY = "TestBody"
def gen_signature(key, parts):
HMAC = hmac.new(key.decode('hex'), None, digestmod=hashlib.sha256)
for part in parts:
HMAC.update(part)
return HMAC.hexdigest()
print gen_signature(KEY, [USER_AGENT, "POST", " ", URI, BODY])
import hashlib
import hmac
KEY = "cb6628c7407fd3c570bebbd7c36731f1"
USER_AGENT = "TestUserAgent"
URI = "/test/uri"
BODY = "TestBody"
def gen_signature(key, parts):
HMAC = hmac.new(bytes.fromhex(key), None, digestmod=hashlib.sha256)
for part in parts:
HMAC.update(part.encode('utf-8'))
return HMAC.hexdigest()
print(gen_signature(KEY, [USER_AGENT, "POST", " ", URI, BODY]))
$KEY = 'cb6628c7407fd3c570bebbd7c36731f1';
$USER_AGENT = 'TestUserAgent';
$URI = '/test/uri';
$BODY = 'TestBody';
function genSignature($secret, array $parts): string {
$ctx = hash_init('sha256', HASH_HMAC, hex2bin($secret));
foreach ($parts as $part) {
hash_update($ctx, $part);
}
return hash_final($ctx);
}
echo genSignature($KEY, array($USER_AGENT, 'POST', ' ', $URI, $BODY));
Result:
47abf7284eab22da90f591ff981bc0c4630a8e3a38c9e1cf8d881eb952c22333