Search code examples
phpurlencodehmac

PHP Function Generating Invalid HMAC Signature


I'm working on integrating MoonPay with my website but there is something I can't figure out. Their default PHP code posted here: https://dev.moonpay.com/docs/ramps-sdk-url-signing#how-to-generate-signatures

$host = 'https://buy-sandbox.moonpay.com';
$query = '?apiKey=pk_test_key&currencyCode=eth&walletAddress=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae';

$signature  = base64_encode(hash_hmac('sha256', $query, 'sk_test_key', true));

echo $host . $query . "&signature=" . urlencode($signature);

When I test this default code on my server it produce invalid signature also the generated URL contains some weird characters like this

¤

So for example a code like this

<?php
$host = 'https://buy.moonpay.com'; // Use the live endpoint
$query = '?apiKey=pk_live_000000000000000000000&currencyCode=eth&walletAddress=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae';

$signature = base64_encode(hash_hmac('sha256', $query, 'sk_live_00000000000000000000000000', true));

echo $host . $query . "&signature=" . urlencode($signature);
?>

Generate a url like this with invalid signature:

https://buy.moonpay.com?apiKey=pk_live_00000000000¤cyCode=eth&walletAddress=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae&signature=kPp00000000000000000000%3D

I've replaced my keys with zeros as I don't want to post my live keys here.

My server is LAMP Ubuntu running Wordpress/WooCommerce I can't figure out if the problem in their example code or my server?


Solution

  • The reason is &curren is entity code for the currency symbol in php.

    You can build your solution like below:

    <?php
    $host = 'https://buy-sandbox.moonpay.com';
    $query = urlencode('?apiKey=pk_test_key&currencyCode=eth&walletAddress=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae');
    
    $signature  = base64_encode(hash_hmac('sha256', $query, 'sk_test_key', true));
    
    echo $host . $query . urlencode("&signature=") . urlencode($signature);
    

    Please refer to answer in previously asked question at PHP "&curren" string turns into weird symbol