John Davidson

python - API Authentication printify

0 comments
Message:


I trying to make printify API auth in PHP. I have example in python, but I not getting right result. Can you explain me what I doing wrong ?


Code in python


 import os
import hmac

def sha256hash(request):
hash = hmac.new(os.environ['SECRET_TOKEN'].encode('utf-8'),
request.data.encode('utf-8'),
'sha256')
return 'sha256=' + hash.hexdigest()


def secure_compare(a, b):
return hmac.compare_digest(a, b)


print('%r' % secure_compare(request.headers['x-pfy-signature'],
sha256hash(request)))

This is my current php code:


public function onCreated(Request $request) {
$secured_token = $request->header('X-Pfy-Signature');
if(!$this->checkAuth(utf8_encode($request), $secured_token)){
$secured_token = "test";
}
}

protected function checkAuth($data, $hashFromPrintify) {
$private_key = utf8_encode(config('printifywebhook.token'));
$hash = hash_hmac( "sha256" , $data , $private_key);
$hash = "sha256=".md5($hash);
if($hash == $hashFromPrintify) {
return true;
}
return false;
}

Where I made mistake ?



My Answer:
public function onCreated(Request $request) {
$secured_token = hash_hmac('sha256', $request->getContent(), getenv('SECRET_TOKEN'));
$x_pfy_signature = $request->header('x-pfy-signature');

if (hash_equals($x_pfy_signature, $secured_token)) {
echo "Signatures match";
} else {
echo "Signatures do not match";
}
}

In your PHP code, you can use the hash_hmac function to generate the HMAC hash using the 'sha256' algorithm and compare it with the x-pfy-signature header from the request using the hash_equals function. This should give you the correct result for API authentication in PHP.

Rate this post

5 of 5 based on 1904 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us