Implementing in-app purchases requires more than displaying a payment screen. An Android application must also verify purchases, manage subscription changes, and keep its backend synchronized with Google Play.
Google Play Billing Library v7 introduced changes to the billing integration workflow, while Real-time Developer Notifications (RTDN) provide a way for Google Play to notify your backend when purchase-related events occur.
This guide explains how RTDN works, how to connect it to a Node.js backend, and how to build a reliable purchase-processing workflow.
What Is Google Play Billing Library v7?
Google Play Billing Library is used by Android applications to integrate Google Play’s billing system for eligible digital goods and subscriptions.
Version 7 includes API and compatibility changes that developers must account for when upgrading existing billing implementations. Before starting a new project, check the currently supported Billing Library version and Google’s latest migration guidance.
RTDN is a separate server-side notification mechanism. It allows your backend to learn that a purchase or subscription event has occurred, but it does not provide all the information needed to determine the purchase’s final state.
Key principle: Treat RTDN as a signal to verify and refresh purchase information, not as standalone proof that a user should receive premium access.
Why Server-Side Purchase Management Matters
A client-only purchase system can create security and reliability problems. For example, an application may display premium features based on locally stored data even after a subscription has expired or been refunded.
A backend helps you:
- Validate purchase tokens with Google Play.
- Track subscription status and expiration.
- Handle cancellations, refunds, and revocations.
- Synchronize entitlement changes across devices.
- Maintain a consistent purchase history.
- Reduce reliance on untrusted client-side state.
Understanding the RTDN Workflow
A typical implementation follows this sequence:
- A user purchases a digital product or subscription through Google Play Billing.
- Google Play publishes a notification to a configured Cloud Pub/Sub topic.
- Your Node.js service receives the notification.
- The service decodes the message and identifies the purchase token.
- The backend calls the Google Play Developer API to retrieve the authoritative purchase state.
- Your database is updated according to the verified result.
- The backend acknowledges successful message processing.
The application can then request its entitlement status from your backend.
Step 1: Configure Google Cloud Pub/Sub
Create or select a Google Cloud project and configure a Pub/Sub topic for RTDN.
In Play Console, configure the real-time developer notifications settings for the relevant application and specify the topic.
Make sure the appropriate Google Play publishing identity has permission to publish to the topic. Configure the subscription and delivery method for your backend, and protect the receiving endpoint.
The exact permission and service-account configuration should follow Google’s current RTDN setup documentation.
Step 2: Install Node.js Dependencies
For an Express-based webhook receiver, install the required packages:
npm install express googleapis
You will also need the appropriate Google Cloud authentication setup and a secure way to load your credentials.
Use Application Default Credentials or a properly configured service account with the minimum required permissions. Never commit service-account private keys or other secrets to a public repository.
Step 3: Receive and Decode an RTDN Message
A Pub/Sub push subscription delivers a JSON envelope containing a message whose data property is Base64-encoded.
The following example illustrates the basic decoding process:
const express = require("express");
const app = express();
app.use(express.json());
app.post("/google-play/rtdn", async (req, res) => {
try {
const encodedData = req.body?.message?.data;
if (!encodedData) {
return res.status(400).send("Missing Pub/Sub message data");
}
const decoded = Buffer
.from(encodedData, "base64")
.toString("utf8");
const notification = JSON.parse(decoded);
// Validate the delivery, identify the notification type,
// and enqueue the event for verified processing.
console.log("Received RTDN event:", notification);
return res.status(204).send();
} catch (error) {
console.error("RTDN processing error:", error);
return res.status(500).send("Processing failed");
}
});
app.listen(process.env.PORT || 3000);
This is a starting example, not a production-ready verification system. A real endpoint must authenticate the push request, validate the expected project and package, safely handle malformed messages, and ensure that events are processed reliably.
For production workloads, consider placing verified messages in a durable queue before acknowledging delivery.
Step 4: Verify Purchases With the Google Play Developer API
After decoding the message, identify whether it relates to a subscription, a one-time product, a voided purchase, or another supported event.
For subscription purchases, the Google Play Developer API provides subscription status information through the relevant subscriptions endpoint. For one-time purchases, use the appropriate product purchase endpoint and supported API methods.
An illustrative Node.js setup looks like this:
const { google } = require("googleapis");
const auth = new google.auth.GoogleAuth({
scopes: [
"https://www.googleapis.com/auth/androidpublisher"
]
});
const androidPublisher = google.androidpublisher({
version: "v3",
auth
});
The precise verification call depends on the purchase type and the notification received. For example, subscription processing requires the application package name and purchase token.
Do not grant access based only on a notification’s type or the existence of a purchase token. Retrieve the authoritative state from Google Play and validate that it corresponds to the expected application and product.
Step 5: Update Your Database Safely
Store verified purchase information in a database that supports reliable updates.
Useful fields may include:
- Application package name.
- Product or subscription identifier.
- Purchase token.
- User account identifier.
- Purchase state.
- Expiration timestamp, where applicable.
- Acknowledgement status.
- Last verified timestamp.
- Last processed notification identifier or event key.
Treat purchase tokens as sensitive data and restrict access to them.
Your database updates should be idempotent. RTDN events may be delivered more than once, and event processing may occur out of order. Reprocessing the same notification must not create duplicate entitlements or extend subscriptions incorrectly.
When events conflict, refresh the purchase state through the Developer API instead of assuming that the newest-arriving webhook necessarily represents the newest purchase state.
Step 6: Handle Subscription Events Correctly
Subscription notifications can represent different lifecycle events, including renewals, cancellations, grace periods, account holds, expiration, and revocation.
Your backend should map the verified subscription state to an entitlement policy.
For example:
- An active subscription may grant premium access.
- A cancellation may stop future renewal without immediately ending the paid entitlement.
- An expired subscription may require premium access to be removed.
- A grace-period subscription may remain entitled according to its verified state and applicable policy.
- A revoked or refunded purchase may require access to be removed.
The correct outcome depends on the verified purchase state, subscription configuration, and applicable business rules.
Step 7: Acknowledge Purchases When Required
Certain purchases must be acknowledged or consumed within the required timeframe. Failure to acknowledge a purchase can result in an automatic refund.
Implement acknowledgement handling in the appropriate purchase-processing workflow, using the relevant Google Play Developer API method. Make the operation retry-safe and record its result.
Do not confuse acknowledging a purchase with acknowledging a Pub/Sub message. These are two different operations:
- Purchase acknowledgement updates the purchase’s status in Google Play.
- Pub/Sub acknowledgement confirms that your notification-processing system has accepted the message.
Step 8: Secure and Monitor the Integration
A production RTDN implementation should include:
- Authenticated push requests.
- HTTPS and appropriate endpoint protection.
- Least-privilege service-account permissions.
- Durable event processing.
- Idempotent database updates.
- Retry handling and dead-letter processing.
- Monitoring for API failures and expired subscriptions.
- Reconciliation jobs to compare backend entitlements with Google Play.
- Logging that avoids exposing credentials or unnecessary personal information.
Test duplicate notifications, delayed events, invalid tokens, API timeouts, and temporary database failures before launching.
Common RTDN Integration Mistakes
Trusting the notification alone: Always retrieve the authoritative purchase state.
Granting access on the client: Use backend-verified entitlements for sensitive premium features.
Ignoring duplicate events: Make event processing idempotent.
Using incorrect API methods: Choose the verification endpoint based on the purchase type.
Skipping acknowledgement: Implement acknowledgement where required.
Ignoring subscription lifecycle changes: Cancellation, expiration, grace periods, and refunds should be handled distinctly.
Conclusion
Google Play Billing Library and RTDN work together to support a reliable in-app purchase system. Billing Library handles the client-side purchase experience, while RTDN helps the backend react to purchase lifecycle changes.
A secure Node.js implementation should authenticate incoming notifications, verify purchases with the Google Play Developer API, update entitlements safely, and process duplicate or delayed events correctly.
Before implementation, consult the current Google Play Billing and RTDN documentation to confirm the supported API versions, notification types, and purchase verification methods.
Official reference: Google Play Billing documentation and the Real-time Developer Notifications reference guide.