A Comprehensive Guide to Android In-App Purchases (IAPs)

In-app purchases (IAPs) have become vital for monetizing mobile applications. They allow users to buy virtual goods, subscriptions, or premium features within the app. In this blog, we will explore how to handle in-app purchases specifically for Android, focusing on subscriptions and how to manage these on the backend server.

Role of the Backend in Handling Android Subscriptions

The backend plays a critical role in managing Android subscriptions. It stores subscription data, verifies purchases, and listens for real-time notifications from Google to handle events like subscription renewals, cancellations, or expirations. These tasks ensure that the subscription details remain up-to-date and secure.

Flow of In-App Purchases in Android

The in-app purchase flow in Android involves multiple steps to ensure security and proper functioning:

  1. User Initiates Payment: The user selects a subscription plan, and Google handles the payment process, verifying the purchase. Upon successful verification, Google returns a receipt with a purchase token and status.
  2. Mobile App Calls Backend: After the purchase is completed, the mobile app sends the purchase token, along with other details, to the backend server through an API call. The backend stores this information securely.
  3. Backend Verifies Purchase: The backend verifies the purchase with Google’s API using the purchase token and other data. If the purchase is valid, it maps the token to the user and stores subscription data.
  4. Handling Real-Time Notifications (RTDN): The backend listens to Google Play’s Real-Time Developer Notifications (RTDN) for any subscription events such as renewals, expirations, or plan changes. When a notification is received, the backend decodes the data, uses the purchase token to identify the user, and updates the subscription information accordingly.

Related read: Implementing In-app Purchase In React Native

Setting Up Your App on Google Play Console

To implement in-app purchases, you must first set up your app on the Google Play Console:

  1. Create a Developer Account: If you don’t have a Google Play Developer account, create one here. This account will allow you to publish apps, manage subscriptions, and access APIs.
  2. Create Your App: Once logged in, create a new application on the Play Console. You will configure various aspects of your app, such as product details, descriptions, and prices.

Creating Subscription Plans

After setting up the app, you need to create subscription plans:

  1. Go to the Subscriptions Tab: In your app’s dashboard, navigate to “Monetize” > “Products” > “Subscriptions.”
  2. Add a New Subscription: Define the subscription plans you want to offer. This includes selecting the billing cycle (monthly or yearly), pricing, and trial periods.
  3. Save Subscription Details: Ensure all the information is correct, as this data will be linked to your app’s subscription plans.

Setting Up Real-Time Notifications Using Google Cloud Pub/Sub

To handle real-time notifications, such as subscription renewals, cancellations, or changes in an Android app, you need to set up Google Cloud Pub/Sub for your project. Google sends notifications to your backend through Pub/Sub, enabling real-time updates of user subscription statuses. Here’s how to set it up:

  1. Create a Google Cloud Project:
    🔺If you don’t have a Google Cloud project yet, navigate to the Google Cloud Console and create a new project.
  2. Create a Pub/Sub Topic:
    🔺Go to Pub/Sub in the Google Cloud Console.
    🔺Click on Create Topic.
    🔺Provide a name for the topic (e.g., subscription-notifications) and create it. This topic will receive real-time notifications from Google Play.
  3. Set Up a Subscription for the Topic:
    🔺Once the topic is created, you need to set up a subscription to allow your backend to listen to these messages.
    🔺Under the created topic, click on Create Subscription.
    🔺Choose Push as the subscription type if you want Google to push notifications directly to your backend’s endpoint.
    🔺Enter the URL where your backend is configured to receive these notifications (this is the same webhook URL where you handle notifications).
  4. Link Your Play Console with Google Cloud Pub/Sub:
    🔺Go to your Google Play Console and navigate to Monetization setup under Monetize.
    🔺Scroll down to Real-time developer notifications.
    🔺Enter the Pub/Sub topic name (e.g., projects/YOUR_PROJECT_ID/topics/subscription-notifications) you created earlier in Google Cloud.
    🔺Click Save. This will link your Play Console to the Pub/Sub topic, allowing Google Play to send notifications for subscription events like renewals, cancellations, or expirations.

Related read: Gmail Watch and Stop Request on Mailbox Using Google Pub/Sub with Django

Unlock App Potential: Master Android IAP Integration

Setting Up a Service Account

Next, you’ll need a service account to authenticate API calls:

Create a Service Account: In the Google Cloud Console, go to “IAM & Admin” > “Service Accounts” and create a new account. Assign the role “Editor” and download the JSON key, which will be used for authentication.

This JSON key will be used by Google API client libraries to generate access tokens and use it to call Google Play developer API’s

Handling Various Scenarios Based on Notification Type

Google Play sends Real-Time Notifications (RTDN) to notify the backend of subscription changes. These notifications contain a notificationType that indicates the type of event. The backend must handle different scenarios based on this value:

  1. SUBSCRIPTION_RECOVERED: The user has restored a canceled subscription. The backend should activate the user’s subscription again.
  2. SUBSCRIPTION_RENEWED: The subscription has been renewed. The backend should update the subscription’s end date and ensure continued access to premium features.
  3. SUBSCRIPTION_CANCELED: The user or Google has canceled the subscription. The backend should deactivate the subscription and remove access to premium features.
  4. SUBSCRIPTION_EXPIRED: The subscription has expired. The backend should mark the subscription as expired and prevent further access.
  5. SUBSCRIPTION_PURCHASED: The subscription has been purchased for the first time. The backend should map the purchase token to the user and activate the subscription.
  6. SUBSCRIPTION_REPLACED: The user has changed their subscription plan. The backend should handle the change by canceling the old subscription and activating the new one.

Handling Real-Time Notifications (RTDN)

When the Google Play Developer API sends a notification to the backend, the following steps occur:

  1. Receive Notification:
    🔺The notification is sent to your webhook, which decodes the data from base64 format. The decoded payload contains details like purchaseToken, subscriptionId, and notificationType.
  2. Verify Purchase:
    🔺The backend verifies the purchase using Google’s subscription verification API. This step ensures that the data is accurate and has not been tampered with. This is the link for verifying the purchase endpoint.
  3. Identify the User:
    🔺When a user first subscribes, you store this purchaseToken in your database alongside the user’s information. This ID remains constant for the lifetime of the subscription.
    🔺On receiving a renewal or other event, use the purchaseToken to look up the user in your database and retrieve their associated subscription data.
  4. Update Subscription Data:
    🔺Based on the notification type, the backend updates the subscription status in the database, ensuring that the correct details (like start and end dates) are saved.
  5. Acknowledge Notifications:
    🔺After processing the data, it is essential to acknowledge the notification to Google. This step ensures that Google knows the notification has been handled successfully.
    🔺These are the links for acknowledge product and subscription endpoints.
coma

Conclusion

Handling in-app purchases in Android involves managing subscriptions through Google Play, integrating the Google Play Developer API, and setting up real-time notifications to ensure users’ subscriptions are updated accordingly. The backend plays a critical role in storing and verifying subscription data, as well as handling various subscription lifecycle events.

By following these steps, you can effectively manage in-app subscriptions for your Android app, ensuring a smooth and reliable experience for your users.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?