Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android in-app billing signature verification in php server

I am working on the IAB v3 in my android application. After every succes purchase, I want my app to send back the sign data and signature to my php server for verification by the public key generated by google developer console. I found the following code.

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

Now I have a problem. The public key given by google is in String Base64 Encoded. I do not know how to convert that string key to a ".pem" format.

If I put my Base64 Encoded key to "$pubkeyid" on the above code. A warning will be given.

Warning: openssl_verify() [function.openssl-verify]: supplied key param cannot be coerced into a public key in myxxx.php.

How can I convert my String Base64 Encoded public key to the php accept format ?

Do anyone have the above experience or solution? Please help. Many thanks.

like image 933
Michael.D.milk Avatar asked Sep 06 '25 23:09

Michael.D.milk


2 Answers

To convert the long base64-encoded public key you get from Google into one that you can use in PHP, try this:

$base64EncodedPublicKeyFromGoogle = "..."; // This is the public key for your app you get from Google.

$openSslFriendlyKey = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($base64EncodedPublicKeyFromGoogle, 64, "\n") .  "-----END PUBLIC KEY-----";

Then you can pass that into openssl_get_publickey().

$publicKeyId = openssl_get_publickey($openSslFriendlyKey);

As you can see, the format from Google is almost the right kind. It just needs to be broken up into 64-character lines, and prepended/appended with the right header/footer.

You can also use the OpenSSL command to convert the public key like this:

openssl enc -base64 -d -in publickey.base64 -A | openssl rsa -inform DER -pubin > publickey.pem

Then you can read in the generated publickey.pem file with PHP and pass its contents to the openssl_get_publickey() function.

like image 160
The Awnry Bear Avatar answered Sep 09 '25 00:09

The Awnry Bear


My problem was fixed by this API.

https://github.com/mgoldsborough/google-play-in-app-billing-verification

like image 40
Michael.D.milk Avatar answered Sep 09 '25 00:09

Michael.D.milk