How to verify purchase for android app in server side (google play in app billing v3)

It sounds what you're looking for is a way to check if the user has premium features enabled on their account, so this is where I would start;

Ensure there is a flag of some sort on your database indicating if the user has premium features and include that in the API response payload when requesting account info. This flag will be your primary authority for "premium features".

When a user makes an in-app purchase, cache the details (token, order id, and product id) locally on the client (i.e the app) then send it to your API.

Your API should then send the purchaseToken to the Google Play Developer API for validation.

A few things might happen from here:

  1. The receipt is valid, your API responds to the client with a 200 Ok status code
  2. The receipt is invalid, your API responds to the client with a 400 Bad Request status code
  3. Google Play API is down, your API responds with a 502 Bad Gateway status code

In the case of 1. or 2. (2xx or 4xx status codes) your client clears the cache of purchase details because it doesn't need it anymore because the API has indicated that it has been received.

Upon a successful validation (case 1.), you should set the premium flag to true for the user.

In the case of 3. (5xx status code) or a network timeout the client should keep trying until it receives a 2xx or 4xx status code from your API.

Depending on your requirements, you could make it wait a few seconds before sending again or just send the details to your API when ever the app is launched again or comes out of background if the purchase details are present on the app cache.

This approach should take care of network timeouts, servers being unavailable, etc.

There are now a few questions you need to consider:

What should happen immediately after a purchase? Should the app wait until validation is successful before providing premium content or should it tentatively grant access and take it away if the validation fails?

Granting tentative access to premium features smooths the process for a majority of your users, but you will be granting access to a number of fraudulent users too while your API validates the purchaseToken.

To put this in another way: Purchase is valid until proven fraudulent or; fraudulent until proven valid?

In order to identify if the user still has a valid subscription when their subscription period comes up for renewal, you will need to schedule a re-validation on the purchaseToken to run at the expiryTimeMillis that was returned in the result.

If the expiryTimeMillis is in the past, you can set the premium flag to false. If it's in the future, re-schedule it again for the new expiryTimeMillis.

Lastly, to ensure the user has premium access (or not), your app should query your API for the users details on app launch or when it comes out of background.


The documentation on this is confusing and weirdly verbose with the things that are almost inconsequential while leaving the actually important documentation almost unlinked and super hard to find. This should work great on most popular server platform that can run the google api client libraries, including Java, Python, .Net, and NodeJS, among others. Note: I've tested only the Python api client as shown below.

Necessary steps:

  1. Make an API project, from the API Access link in your Google Play console

  2. Make a new service account, save the JSON private key that gets generated. You'll need to take this file to your server.

  3. Press Done in the Play console's service account section to refresh and then grant access to the service account

  4. Go get a google api client library for your server platform from https://developers.google.com/api-client-library

  5. Use your particular platform's client library to build a service interface and directly read the result of your purchase verification.

You do not need to bother with authorization scopes, making custom requests calls, refreshing access tokens, etc. the api client library takes care of everything. Here's a python library usage example to verify a subscription:

First, install the google api client in your pipenv like this:

$ pipenv install google-api-python-client

Then you can set up api client credentials using the private key json file for authenticating the service account.

credentials = service_account.Credentials.from_service_account_file("service_account.json")

Now you can verify subscription purchases or product purchases using the library, directly.

#Build the "service" interface to the API you want
service = googleapiclient.discovery.build("androidpublisher", "v3", credentials=credentials)

#Use the token your API got from the app to verify the purchase
result = service.purchases().subscriptions().get(packageName="your.app.package.id", subscriptionId="sku.name", token="token-from-app").execute()
#result is a python object that looks like this ->
# {'kind': 'androidpublisher#subscriptionPurchase', 'startTimeMillis': '1534326259450', 'expiryTimeMillis': '1534328356187', 'autoRenewing': False, 'priceCurrencyCode': 'INR', 'priceAmountMicros': '70000000', 'countryCode': 'IN', 'developerPayload': '', 'cancelReason': 1, 'orderId': 'GPA.1234-4567-1234-1234..5', 'purchaseType': 0}

The documentation for the platform service interface for the play developer API is not linked in an easy to find way, for some it is downright hard to find. Here are the links for the popular platforms that I found:

Python | Java | .NET | PHP | NodeJS (Github TS) | Go (Github JSON)


Complete example of using Google API Client Library for PHP:

  1. Setup your Google Project and access to Google Play for your service account as described in Marc's answer here https://stackoverflow.com/a/35138885/1046909.

  2. Install the library: https://developers.google.com/api-client-library/php/start/installation.

  3. Now you are able to verify your receipt the following way:

    $client = new \Google_Client();
    $client->setAuthConfig('/path/to/service/account/credentials.json');
    $client->addScope('https://www.googleapis.com/auth/androidpublisher');
    $service = new \Google_Service_AndroidPublisher($client);
    $purchase = $service->purchases_subscriptions->get($packageName, $productId, $token);
    

    After that $purchase is instance of Google_Service_AndroidPublisher_SubscriptionPurchase

    $purchase->getAutoRenewing();
    $purchase->getCancelReason();
    ...