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 

16 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 : Alfred-Escher Strasse 66, 8002 Zurich

    Phone : +41 44 280 29 29

    After many years of dreaming to have this first barbershop, it has finally come true. We are proud to announce that “The Good Barbers” has opened its doors for the first time at Alfred-Escher Strasse 66, 8002 Zürich, and this marks the beginning of our story.

    This dream involved many conversations, research and experience gained by working in some of the best barbershops located in Madrid, London and Zurich. We come from a family of entrepreneurs and have always had in mind that we should be taking risks whilst carefully deciding what the best business concept should be for this city that we call home.

    We were clear that this business should be built with the following core foundations:

    - Tailored experience

    - Special care for the hygiene

    - Relaxing environment

    - Quality service, products and infrastructure


    With that in mind, one of the most important next steps was to find the first location for our business, we wanted it to be in the city, with good light and in a vibrant area. This search was found to be very challenging as we were not able to offer to the landlords any past record of us being successful as a company, and therefore it was the step that took us the longest to achieve. Thankfully, our chance arrived, and we were able to find a dream location for our business, it had everything we were looking for and more! Two stories, corner location, business hub, floor to ceiling windows…

    Once we were told we got this property, it was time to celebrate! But most importantly, it was time to start bringing to life all these concepts we had been discussing, creating, and modifying throughout these years. Thanks to all the preparation work we did; it was clear what the next steps were and how to execute them.

    Not to bore you with many details, but just to name a few of the concepts we had to now bring to life: furniture, company creation, suppliers, point of sale, software, webpage, talent… It took us many hours of thinking and execution, but we had a goal in mind all along, and it was to open our doors on March 1st, 2022. With project management skills, help from our loved ones and huge amounts of effort, we finally made it! And what a joyful moment it was to see the first client going into the barbershop the first day…


    We would like to take this opportunity, in our first blog post, to thank all of you who have supported us through this journey and also to all our clients who have been coming in or are planning to do so, and therefore giving us a chance. We know it’s challenging to trust a barbershop that has just opened with your hair, beard and facial needs and therefore why we are especially thankful to all of you.

    For any new customers, there is a ongoing offer of 15% discount in your first booking when done online. This offer lasts until 15th April 2022 and includes all services we offer. Definitely an offer not to miss out and that hopefully will bring an extra incentive to you for trying us out. We will do our best to give you a unique service experience in the best barbershop environment you will find in town.

    This is just the beginning of our dream, and we would love to continue sharing it with you all via our 1:1 appointments, social media (Instagram: the_good_barbers / Facebook: thegoodbarbersag) and through this blog.

    Your barbershop of reference in Zürich,

    The Good Barbers.

    Hair Products for men

    ReplyDelete
  7. 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
  8. 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
  9. Address : Currys Post Road, Nottingham Road, KwaZulu-Natal, 3280 South Africa

    Phone : +27 83 391 5505

    CONGRATULATIONS ON YOUR ENGAGEMENT!
    You’re engaged, high on love and feeling excited!
    Then the mind starts: Everyone wants to know everything – from the wedding date to the bridesmaid dress color.
    It’s easy to feel a little overwhelmed at this stage, but we are glad to see that you have taken the first step and started your venue search!
    There is no mistake that our paths have crossed. You wanted something special? You found it.

    The Gallery Wedding Venue


    Combining a premium boutique Bed and Breakfast with a magnificent three tiered country wedding venue – you are not simply hiring a wedding venue,
    but partnering with us to create a series of memorable moments resulting in a remarkable experience to be remembered.

    THREE MAGNIFICENT INTERCONNECTED VENUES
    Our venue rental includes the exclusive use of three magnificent venues which dovetail together to create the perfect wedding day.

    The Ceremony, Reception and After Party are all interconnected separate spaces – each space holding it’s own majestic look and feel creating multiple wonderful experiences for your family and loved ones throughout your special day.

    ReplyDelete
  10. Address : Room B8, 1/F, Block B, East Sun Industrial Building,16 Shing Yip St, Kwun Tong, Kowloon, Hong Kong

    Phone : +852 5448 6841

    We first started just as a lattice shop in Hong Kong. If you don't know what that is, it simply refers to a small area divided from the shelf , and we owned one of them.


    We were small, but we were serious about finding reliable suppliers.


    It wasn't plain sailing. Spammers, overpriced or expired products, inauthentic items, orders that took forever to ship, irresponsible outsourcing partners, dubious companies... you name it, we have experienced them all.

    Beauty Retailer & Wholesaler


    So we thought, why don't we build our own trustworthy one-stop beauty platform? Not only for our retail customers but also those businessmen who are serious about finding reliable wholesalers as we did.


    And here we are, Carsha.

    Our Mission
    We aspire to build an all-in-one beauty marketplace for our retail customers by gathering together a diverse range of products, from global-leading brands to indie beauty brands. Towards our B2B customers, we aim to become their most transparent, accessible, best-price and supportive beauty wholesaler.

    Our Vision
    Our goal is to provide our customers with a personalized, informative, and supportive shopping and purchasing experience. We also empower people, including our employees and companies of all sizes, to achieve beauty, confidence, and success. Finally, we hope that Carsha can evolve alongside the rest of the world.

    Our Promise
    We guarantee that we treat you just like how we treat ourselves - that means that all our products will be 100% authentic. On top of that, our collections will expand from day to day to assure you to be able to find the most suitable cosmetics, skincare products, or fragrances for you and your business. Last but not least, our customer service will remain the best all the time.

    Our Impact
    Over 1500 customers were able to save money thanks to our beauty deals. Over 100 businesses benefited from our products and were inspired by our one-of-a-kind and personalized business strategies. More than 20 employees benefited from our environment and learned from us. In the future, we hope to give back to society by focusing on orphanages, homelessness, and mental illness.

    ReplyDelete
  11. 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
  12. Address : 429 S. Evergreen St., Bensenville, IL 60106

    Phone : +1 630-616-9999

    Fax : +1 630-616-5509

    We manufacture our own kitchen cabinets under the brand name “American Wood Cabinets.”

    quartz countertops

    Factory Plaza has earned a solid reputation for providing excellent quality and customer service.

    We are committed to the communities in which we operate making every effort to bring quality and affordability to each and every household. Here, at Factory Plaza, our customers are our neighbors, our friends, and our business partners.

    Our best assets include our experienced and knowledgeable employees, craftsmanship, and unparalleled customer service.

    ReplyDelete
  13. 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
  14. Hello, I read Your Article. This is very Helpful for me. Thanks. Please try
    SMM Panel

    ReplyDelete