Код: Выделить всё
def verify_hmac(params, secret):
# Extract the HMAC
received_hmac = params.get('hmac')
if not received_hmac:
print("Received HMAC is empty.")
return False
# Sort the parameters and exclude the 'hmac'
sorted_params = {key: params[key][0] for key in sorted(params) if key != 'hmac'}
# Rebuild the message string for HMAC verification
message = "&".join([f"{quote_plus(key)}={quote_plus(value)}" for key, value in sorted_params.items()])
# Calculate the HMAC
calculated_hmac = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
print("Received HMAC:", received_hmac)
print("Calculated HMAC:", calculated_hmac)
# Compare the received HMAC with the calculated HMAC
return hmac.compare_digest(received_hmac, calculated_hmac)
Код: Выделить всё
def callback(request):
# Log all received parameters
print("Received parameters:", request.GET)
shop = request.GET.get('shop')
code = request.GET.get('code')
if not shop or not code:
return HttpResponse("Missing shop or code in callback", status=400)
# Setup the Shopify API
api_key = os.getenv('SHOPIFY_API_KEY')
secret = os.getenv('SHOPIFY_API_SECRET')
# Debug output to check if API Key and Secret are loaded
print("API Key:", api_key)
print("Secret:", secret)
# Verify HMAC with try-except for error handling
try:
if not verify_hmac(request.GET, secret):
return HttpResponse("HMAC verification failed", status=403)
except Exception as e:
print("Error during HMAC verification:", str(e))
return HttpResponse("Internal server error", status=500)
# Proceed to request token if HMAC verification is successful
return HttpResponse("HMAC verification passed.")
Полученные параметры:
Ключ API: **************** ***************
Секрет: ********************** **********
Получено HMAC: 72958cddad5aff5b9109be7ab13c88cb9d9ed09fe01367a189214f518b171041
Рассчитано HMAC: 61d44f23aac3fc4b6ece0eea6a8d9685e 2aa315b468eadc7db0c91f8316b7f95
В браузере отображается
- Проверка HMAC не удалась
Подробнее здесь: https://stackoverflow.com/questions/790 ... hopify-app