Server side Google Play In App Billing receipt validation and testing

#Android, #Programming, #Ruby

If you are building a Google Android application and plan to implement the In App Billing service, it is best to validate receipts using your own server if possible, certainly if you are serving non-consumable items to the app based on the receipt validation.

How it works

The flow is quite simple, after client side interaction with In App Billing you receive a json object as a receipt, this contains the product purchased, etc and a signature; here’s where the fun starts. So, receipt validation is based on a tried and trusted mechanism using asymmetric encryption, public and private key pairs and digests.

You can then verify that a) the receipt is from your application b) has receipt not been tampered with c) receipt signed with your private key by performing the following steps to validate the receipt;

How to test (fake) it

If you need to test your server side code do you need real Google Play receipts and signatures? No. You can test your code by generating your own receipts and creating your own signatures signed with your own public and private keys, then testing validation using these.

These are a series of things you can do to generate and validate the receipts and signatures, all using standard OpenSSL commands and libraries.

Here are some commands, assuming you have a public and private key ready, to generate the signature and then verify it with OpenSSL and Ruby. Simply translate the Ruby code to whatever platform you’re using.

So, when a user makes a purchase, Google is performing steps 2 and 3 - they create the receipt.json and store it whilst taking the digest and signing with your private key and again storing it before returning both bits to your application.

Here is an example receipt; probably want to remove all line breaks before generating signature.

Here is some sample Ruby code to validate the signature.

Finally in the real world, you also really should be doing the following;

Side note; as of Google I/O 2013 Google In App Billing now supports proper testing scenarios using test accounts, no need to test fake product IDs, refunds, etc. At last they have caught up with Apple.