5/09/2018

Verifying a Playstore in-app purchase with PHP

Of course you can verify an IAB purchase in your Android app, but that means you have to have your API key somewhere in the app. In the worst case, hackers can get your key, at the very least it is easy to tamper with your verification code through reverse-engineering of the app.

This is why Google recommend checking purchases on the server. Here is how to do this in PHP.

First of all, you have to get your key from the Play Console:



Save the key to a text file. The following code assumes the file is in the same directory as the PHP script and is named "Publishing-API-Key":

function verifyPurchaseSignature($data, $signature)
{
    $key = file_get_contents("Publishing-API-Key");
    $key = openssl_get_publickey($key);

    if(null === $key)
    {
        reportError("Cannot verify purchase: invalid API key!");
        exit();
    }

    $result = openssl_verify($data, base64_decode($signature), $key, OPENSSL_ALGO_SHA1);

    if(0 === $result)
    {
        return false;
    }
    else
    {
        return true;
    }
}

The data parameter contains the JSON data from the play store purchase (do not re-format or add newlines).
The signature parameter contains the signature from the play store purchase. which is a Base64 string.

If you host this code on a web server, make sure that the file containing your API key is not externally accessible!

No comments:

adaxas Web Directory