Server side Google Play In App Billing receipt validation and testing
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.
- Google generate a receipt for the transaction
- Then take the SHA1 digest of that string
- Encrypt the digest using your account’s private key
- Return the receipt as plain text and the encrypted digest
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;
- Decrypt the digest with your public key
- Validate the digest matches the digest of the receipt string
- Validate the details of 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;
- Generating a token or nonce and persisting this server side, passing it to Google Play and then finally validating it is present in the developerPayload field in the receipt.
- Storing the purchaseToken for the transaction and ensure that the same purchaseToken is not used more than once.
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.