Android billing - how to set up a buy buttons and correctly read whether the user canceled or bought?

StackOverflow https://stackoverflow.com/questions/12092431

  •  28-06-2021
  •  | 
  •  

Question

I am working from the Dungeons example that the Android provides, and it feels like I almost got it correctly, but I can't figure out how to detect if the person pressed the back button and backed out of the purchase. Here is what I have so far:

Button buy = (Button)findViewById(R.id.buy); 
buy.setOnClickListener(new Button.OnClickListener() 
{  
   public void onClick(View v) 
   {                                           
     try
     {
        if (mBillingService.requestPurchase(issueProductId, 
                                                Consts.ITEM_TYPE_INAPP , null)) 
        {
          // Not sure what to do here. Has the person been sent to the buy screen yet or no?
          // There are these strings I need to check for but not entirely certain how:                

          if(mBillingService.checkBillingSupported(Consts.ITEM_TYPE_INAPP))
          { 
                 // OK
          } 
          else 
          {
             // If billing is not supported,  give them the item for free
                 Intent myIntent = new Intent(ExtraHelpActivity.this, PsychologyActivity.class);
                 ExtraHelpActivity.this.startActivity(myIntent);    
          }    

          try
          {   
          if (mBillingService.requestPurchase(issueProductIdPsych, 
                     Consts.ITEM_TYPE_INAPP ,  null)) 
          {
                  // HOW DO I CHECK HERE IF THE USER CANCELED OUT OF THE PURCHASE? 
                  // EVEN ON CANCEL, THEY ARE BEING TAKEN TO THE ITEM THAT THEY NEED TO PAY FOR.  


              // Send them to the screen of the article.
                  Intent myIntent = new Intent(ExtraHelpActivity.this, PsychologyActivity.class);
              ExtraHelpActivity.this.startActivity(myIntent);                         
          } 
        }
     catch ( Exception e )
     {
        // Report exception.
     }  
     });

I added some inline comments where I am confused. I am not certain how to read whether the person purchased the item, or cancelled. If someone could help me with this, that would be great.

Right now this code takes the person to the buy screen, and some people buy, but when people press cancel, they still get taken to the item which they didn't buy. :)

EDIT:

By the way, if users already bought the item and want to come back to it, the purchase request state does not change, right? So what method ends up being triggered? I tested with one purchase and I was able to buy access to one screen with an article, but now can not get to it again since the payment screen keeps telling me I already bought that item, and not taking me to the next page.

Here is how my new onStateChanged method looks like:

@Override
public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) 
{
    if (purchaseState == PurchaseState.PURCHASED) 
    {
        mOwnedItems.add(itemId);

        if ( itemId != null && itemId.trim().equals("3") )
        {
        Intent myIntent = new Intent(ExtraHelpActivity.this, PsychologyActivity.class);
        ExtraHelpActivity.this.startActivity(myIntent);
        }
        if ( itemId != null && itemId.trim().equals("4") )
        {
           Intent myIntent = new Intent(ExtraHelpActivity.this, NumberOfBusinessesActivity.class);
    }                
   }
   else 
   if (purchaseState == PurchaseState.CANCELED) 
   {  
                // purchase canceled
   } 
   else 
   if (purchaseState == PurchaseState.REFUNDED) 
   {
                // user ask for a refund
   }
   else
   {   
                if ( itemId != null && itemId.equals("3") )
                {
                      Intent myIntent = new Intent(ExtraHelpActivity.this, PsychologyActivity.class);
                      ExtraHelpActivity.this.startActivity(myIntent);
                }
                if ( itemId != null && itemId.equals("4") )
                {
                      Intent myIntent = new Intent(ExtraHelpActivity.this, NumberOfBusinessesActivity.class);
                      ExtraHelpActivity.this.startActivity(myIntent);   
                }                   
     }           
}

and when I tested it and bought an article, it did get here to the if (purchaseState == PurchaseState.PURCHASED) but not the individual if cases inside it even though the itemId id is "3" or "4"

EDIT:

and this is how I declare the product ids at the beginning of the Activity:

String issueProductIdWebMarketing = "1";    
    String issueProductIdDonate = "2";  
    String issueProductIdPsych = "3";
    String issueProductIdNumberofBusinesses = "4";

Thanks!!

Was it helpful?

Solution

According to the billing integration guide:

when the requested transaction changes state (for example, the purchase is successfully charged to a credit card or the user cancels the purchase), the Google Play application sends an IN_APP_NOTIFY broadcast intent. This message contains a notification ID, which you can use to retrieve the transaction details for the REQUEST_PURCHASE request.

And the intent com.android.vending.billing.PURCHASE_STATE_CHANGED contains purchaseState

The purchase state of the order. Possible values are 0 (purchased), 1 (canceled), 2 (refunded), or 3 (expired, for subscription purchases only).

source (table 4)


EDIT: In the dungeons sample, there is an inner class extending PurchaseObserver (see Dungeons activity) that does the job, see especially (onPurchaseStateChange)


EDIT2: some pseudo-code

in the activity (Dungeons class in the sdk sample):

Button buy = (Button)findViewById(R.id.buy); 
buy.setEnabled(false);
buy.setOnClickListener(new Button.OnClickListener() {  
    public void onClick(View v) 
    {
        // show purchase dialog and call mBillingService.requestPurchase() on dialog validation
    }
});

// request to see if supported
if (!mBillingService.checkBillingSupported()) {
    // not supported
}

in the observer (DungeonsPurchaseObserver in the sample):

public void onBillingSupported(boolean supported, String type) {
    if (type == null || type.equals(Consts.ITEM_TYPE_INAPP)) {
        if (supported) {
           // billing supported: enable buy button
        } else {
           // billing not supported: disable buy button
        }
    }
}

public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
    int quantity, long purchaseTime, String developerPayload) {
    if (purchaseState == PurchaseState.PURCHASED) {
        // item purchased
    } else if (purchaseState == PurchaseState.CANCELED) {
        // purchase canceled
    } else if (purchaseState == PurchaseState.REFUND) {
        // user ask for a refund
    }
}

OTHER TIPS

The problem is that the call mBillingService.requestPurchase is not synchronous. So you can not check right after if the purchase was successful or not.

I recommend you use the library AndroidBillingLibrary. With it you can easily get all the Google Play's events. For that you can use onRequestPurchaseResponse() and onPurchaseStateChanged() from the helpers AbstractBillingActivity or AbstractBillingFragment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top