Rapid Subscribe Android App

Rapid Subscribe Android App
Rapid Subscriber

Recent Posts

Create an In-App Purchases in Android

Create an In-App Purchases in Android

In this post, we will learn about how to create In-App Purchases in the Android app.




We will create an In-App Purchases in Android with Google Play Billing Library 

Note: For In-App Purchases you have to upload a signed APK to Alpha, Beta, or Publish section in Google Play Console (Drafts are not supported). Also, create a Tester in that Alpha release to test your account with a Test Purchase.

In this post, we learn about 
  • Creating In-App Purchases in the Android app.
  • Managed and UnManaged Product
  • Consume a Managed Product (so that you can buy again the same product with the same account).
  • Acknowledge a product.
  • Give Data to the user after purchase successfully.
  • Generate a Signed app and upload it to Alpha Testing.
  • Add Testers for Alpha Testing.
  • Update Billing library to 4.0
  • Purchase multiple quantity products at a time.
  • Purchase preview with test card and update user data.

Firstly, we create an In-App Purchase in Android and in that we cover remaining topics.

For that, create a Managed Product in Google Play Console.


  • Open Google Play Console
  • Click on Store Presence
  • Click on In-App Products
  • Click on Managed Product
In-App Purchases in Google Play Console
In-App Purchases in Google Play Console

  • Create a Managed Product
  • Fill your Product_id, Product_name, Product_Description, and change to Active and then set a price for your product.
Create a Managed Product
Create a Managed Product

Make In-App product active and Set price
Make In-App product active and Set price

When you successfully create a Managed product then  

Open your Android Studio project and add Google Play Billing Library.

app-level build.gradle
 implementation 'com.android.billingclient:billing:4.0.0'  

Then add permissions in AndroidManifest.xml
 <uses-permission android:name="android.permission.INTERNET" />  
 <uses-permission android:name="com.android.vending.BILLING" />  

Then Create a Billing activity in your project and add below code in it.

Billing.java
 import androidx.annotation.Nullable;  
 import androidx.appcompat.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 import com.android.billingclient.api.BillingClient;  
 import com.android.billingclient.api.BillingClientStateListener;  
 import com.android.billingclient.api.BillingFlowParams;  
 import com.android.billingclient.api.BillingResult;  
 import com.android.billingclient.api.ConsumeParams;  
 import com.android.billingclient.api.ConsumeResponseListener;  
 import com.android.billingclient.api.Purchase;  
 import com.android.billingclient.api.PurchasesUpdatedListener;  
 import com.android.billingclient.api.SkuDetails;  
 import com.android.billingclient.api.SkuDetailsParams;  
 import com.android.billingclient.api.SkuDetailsResponseListener;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class Billing extends AppCompatActivity implements PurchasesUpdatedListener {  
   Button buy_btn;  
   TextView tv;  
   BillingClient billingClient;  
   List<String> skulist = new ArrayList<>();  
   String product = "my_test_product_12";  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_billing);  
     buy_btn = findViewById(R.id.buy_button_1);  
     tv = findViewById(R.id.tv);  
     billingClient = BillingClient.newBuilder(Billing.this).enablePendingPurchases().setListener(new PurchasesUpdatedListener() {  
       @Override  
       //This method starts when user buys a product  
       public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> list) {  
         if(list != null && billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)  
         {  
           for(Purchase purchase : list)  
           {  
             handlepurchase(purchase);  
           }  
         }  
         else  
         {  
           if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED)  
           {  
             Toast.makeText(Billing.this, "Try Purchasing Again", Toast.LENGTH_SHORT).show();  
           }  
           else  
           {  
             if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED)  
             {  
               Toast.makeText(Billing.this, "Already Purchased", Toast.LENGTH_SHORT).show();  
               //We recover that method by consuming a purchase so that user can buy a product again from same account.  
             }  
           }  
         }  
       }  
     }).build();  
     billingClient.startConnection(new BillingClientStateListener() {  
       @Override  
       public void onBillingSetupFinished(BillingResult billingResult) {  
         if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)  
         {  
           Toast.makeText(Billing.this, "Successfully connected to Billing client", Toast.LENGTH_SHORT).show();  
         }  
         else  
         {  
           Toast.makeText(Billing.this, "Failed to connect", Toast.LENGTH_SHORT).show();  
         }  
       }  
       @Override  
       public void onBillingServiceDisconnected() {  
         Toast.makeText(Billing.this, "Disconnected from the Client", Toast.LENGTH_SHORT).show();  
       }  
     });  
     skulist.add(product);  
     final SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();  
     params.setSkusList(skulist).setType(BillingClient.SkuType.INAPP);  //Skutype.subs for Subscription  
     buy_btn.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View view) {  
         billingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() {  
           @Override  
           public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {  
             if(list != null && billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)  
             {  
               for(final SkuDetails skuDetails : list)  
               {  
                 String sku = skuDetails.getSku(); // your Product id  
                 String price = skuDetails.getPrice(); // your product price  
                 String description = skuDetails.getDescription(); // product description  
 //method opens Popup for billing purchase  
                 BillingFlowParams flowParams = BillingFlowParams.newBuilder()  
                     .setSkuDetails(skuDetails)  
                     .build();  
                 BillingResult responsecode = billingClient.launchBillingFlow(Billing.this,flowParams);  
               }  
             }  
           }  
         });  
       }  
     });  
   }  
   private void handlepurchase(Purchase purchase) {  
     try {  
       if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {  
         if (purchase.getSkus().get(0).equals(product)) {  //purchase.getskus is an arraylist which contains your itemname
           ConsumeParams consumeParams = ConsumeParams.newBuilder()  
               .setPurchaseToken(purchase.getPurchaseToken())  
               .build();  
           ConsumeResponseListener consumeResponseListener = new ConsumeResponseListener() {  
             @Override  
             public void onConsumeResponse(BillingResult billingResult, String s) {  
               Toast.makeText(Billing.this, "Purchase Acknowledged", Toast.LENGTH_SHORT).show();  
             }  
           };  
           billingClient.consumeAsync(consumeParams, consumeResponseListener); 
           int quantity = purchase.getQuantity(); // when you create a purchase item in play console then you can set quantity of purchase that how much pack a user can purchase at a time. give coins to user mltiply with that quantity.
           
           int value = 600;
           
           //now you can purchase same product again and again  
           //Here we give coins to user.  
           //Here we purchase 5 quantity quan: 5 , 600*5 = 3000 coins to user..  
           tv.setText("Purchase Successful: quan: "+quantity+" , "+value*quantity);
           
           Toast.makeText(this, "Purchase Successful", Toast.LENGTH_SHORT).show();  
         }  
       }  
     }  
     catch (Exception e)  
     {  
       Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();  
     }  
   }  
   @Override  
   public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> list) {  
     Toast.makeText(this, "onPurchases Updated", Toast.LENGTH_SHORT).show();  
   }  
 }  

In this, we create an In-App Purchases and then Consume a purchase and then give coins to users.

activitybilling.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical"  
   tools:context=".Billing">  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Buy"  
     android:padding="10dp"  
     android:id="@+id/buy_button_1"/>  
   <TextView  
     android:padding="10dp"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Purchase"  
     android:id="@+id/tv"  
     android:textSize="18sp"/>  
 </LinearLayout>  

After that, we generate a Signed Bundle and upload it to Google Play Console under Alpha Testing Mode.

For that, In Android studio, Click on Build -> Generate Signed Bundle and create a bundle or APK.


Generate Signed Bundle From Android Studio
Generate Signed Bundle From Android Studio


Then open Google Play Console 

  • Open your App or create one.
  • Click on Release Management from the left menu.
  • Then click on App releases
App Releases in Google Play Console
App Releases in Google Play Console
  • Then Click on Alpha Testing
Alpha Testing in Google Play Console
Alpha Testing in Google Play Console

  • Click on Create release
  • Upload your Apk and save and review.
  • Click on Manage testers and add your email id.
After Your App successfully uploaded to Google Play console then install your app from Play Store from your Test Account and then click on the Buy button and then purchase your product with test card.

Thanks


 
Follow us for more posts like this, 
Subscribe to Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

12 comments:

  1. Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work. facebook ads

    ReplyDelete
  2. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. 0dotlive

    ReplyDelete
  3. Malware authors effectively make applications that are basically the same as the famous ones so ensure that you require some investment to check that the application engineer, name and distributer are right before you do ahead. AFK Arena Codes

    ReplyDelete
  4. Android tablets enjoy an upper hand over different tablets accessible on the lookout. These tablets are controlled with quite possibly the most impressive and versatile working system accessible today for example Android itself. These are profoundly adjustable too. walkie talkie app

    ReplyDelete
  5. What is an SMM panel?
    An SMM panel is an online shop that offers SMM services at affordable prices.smm panel Provider

    What kinds of SMM services do you provide here?
    There are many types of SMM services available on our panel: likes, followers, views, etc.

    Are SMM services on this panel safe to buy?
    Our SMM services are totally safe to use, you won't lose your accounts.

    A mass order — how does it work?
    You can place multiple orders with different links at once using the mass order feature

    What is Drip-feed?
    Grow your accounts as fast as you want with the help of Drip-feed. How it works: let's say you want 2000 likes on your post. Instead of getting all 2000 at once, you can get 200 each day for 10 days.

    ReplyDelete
  6. Address : 109 W 39 St #Concourse 1, New York, NY 10018

    Phone : +1 (646) 781-7070

    Avail Unparalleled Locksmith And Security Services In NYC NYC Security Systems Company
    Established in 2010, Top Notch Locksmith & Security in NYC is a well-reputed family-owned business. We pride ourselves on offering a wide array of locksmith and security services solutions to both residential and commercial clients throughout the New York City area, including Manhattan, Brooklyn, Queens, and The Bronx. Our vast list of services includes all locks and lock systems, intercom installation and repair, buzzer systems, access control systems installation, closed-circuit TV installation, and so much more. Regardless of the service you choose, our well-trained staff is sure to give you the best service experience you have ever had in the locksmith and security industry.

    At Top Notch Locksmith & Security Services, we strive to be industry leaders in our domain. Our core focus lies on providing professional, reliable, and efficient locksmith and security services under one roof. We offer a vast portfolio of services, catering to different problems, to make sure that the diverse needs of our customers are met. At Top Notch Locksmith & Security, we have spent the last decade working tirelessly to associate our name with quality service and high levels of customer fulfillment. From residential locksmith and security issues to large-scale commercial services, we value each project equally and prioritize results and customer satisfaction over everything else. Dedication to our valued customers, commitment to premium workmanship, and an unrelenting passion for pursuing the newest technology trends are what make Top Notch Locksmith & Security stand out from the competition.

    ReplyDelete
  7. Address : 260 Madison Ave 8th Floor #8001, New York, NY 10016

    Phone : +1 718-213-8508

    Medebound HEALTH Medebound HEALTH is an international healthcare company that is incorporated and headquartered in New York, and has its operations in North America, and Asia Pacific. It is dedicated to assisting patients across the globe to gain easy access to top medical experts and advanced treatment methods when they encounter frustrating and devastating conditions. Medebound HEALTH has contracted with the world’s largest insurance firms (global Fortune 500 companies) and has successfully acquired worldwide members touching over two million lives, bringing new hope to patients who would otherwise have to travel abroad for care.


    Business Email : support@medebound.com

    Follow on :

    Linkedin : https://www.linkedin.com/company/medebound-llc/

    ReplyDelete
  8. Address : 20120 Paseo Del Prado, Walnut, CA 91789

    Phone : +1 401-261-2809

    Pets are waggy-tailed, yappy-or-purry, love-you-unconditionally, furry family members. They chew, poop, shed on the couch, and leave pawprints on your heart. Pets enrich our lives and bring us infinite joy – so they deserve to be spoiled with stylish, superior quality products!

    As pet owners ourselves, Ultra Joys Pets we want only the best for our beloved fur babies. We love to make our dogs and cats look fancy with cute accessories! But we also know that safety is important when our pets are out exploring the world. If you share your life with a dog or cat, you’ll understand our dilemma and have probably been seeking a solution.

    So we poured our passion into creating fun, functional pet products that keep animal companions safe and stylish. In 2018, we established Ultra Joys Pets, to give pets and their devoted owners the quality they deserve. From modern collars and leashes to personalized pet ID tags, our products are handmade with love and customized in Southern California.

    Naturally, we’re here to please you as well as your pet! We take care to process orders quickly and pride ourselves on delivering 100% customer satisfaction. Buy from Ultra Joys Pets and both you and your fur baby will benefit!


    Hours: Mon-Fri 9am - 5pm PST.

    Established: 2018

    Keywords : dog tags, dog collar, ultra joys pets


    Follow on :

    Facebook : https://www.facebook.com/ultrajoyspets

    Instagram : https://www.instagram.com/ultrajoyspets/

    Youtube : https://www.youtube.com/channel/UCo3heDWJsJprXkdhb3zmocg

    Pinterest : https://www.pinterest.com/ultrajoyspets/

    ReplyDelete
  9. Factory Plaza specializes in Granite, marble and Quartz countertops fabrication and installation. granite countertops Are you looking for custom kitchen counters, bathroom tops and other stone projects, visit FactoryPlaza.com

    ReplyDelete
  10. I search example in very other sites and your example is only it work. Simple and efficient.

    ReplyDelete