Android Tutorial Android In-App Billing v3 Tutorial

New version: GooglePlayBilling - In App Purchases

This tutorial covers the new API for in-app billing provided by Google.

The main differences between v3 and the previous version are:
- (v3) Is easier to implement.
- Supports managed products and subscriptions. Unmanaged products are not supported.
- Includes a method to retrieve all purchased items. This means that you do not need to manage the items yourself.
- Allows you to "consume" managed products. For example if the user has bought a game add-on and then used it, the app consumes the product allowing the user to purchase the add-on again.

The official documentation is available here: In-app Billing Version 3 | Android Developers

Implementing in-app billing in your application

The first step is to upload a draft APK to Google developer console. Note that you should use a private signing key to sign the app.

Under Services & APIs you will find your license key. This key is also required for in-app billing:

SS-2013-06-06_17.21.31.png


You should also add at least one item to the "In-app Products" list. The item's type should be Managed Product or Subscription.

Basic4android code

The first step is to initialize a BillingManager3 object:
B4X:
Sub Process_Globals
   Dim manager As BillingManager3
   Private key As String = "MIIBIjANBgkqhkiG9w0BAQEFAA..."
End Sub

Sub Globals


End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      manager.Initialize("manager", key)
      manager.DebugLogging = True
   End If
   ...
End Sub

Sub Manager_BillingSupported (Supported As Boolean, Message As String)
   Log(Supported & ", " & Message)
   Log("Subscriptions supported: " & manager.SubscriptionsSupported)
End Sub

The BillingSupported event will be raised with the result. Note that all of the billing related actions happen in the background and raise events when the action is completed.

Calling manager.GetOwnedProducts will raise the OwnedProducts event. The OwnedProducts event includes a Map that holds the user current purchases. The keys in the map are the products ids (or Skus) and the values are objects of type Purchase. These objects include more information about the purchase and are required for other actions, such as consuming a purchase.

B4X:
Sub manager_OwnedProducts (Success As Boolean, purchases As Map)
   Log(Success)
   If Success Then
      Log(purchases)
      For Each p As Purchase In purchases.Values
         Log(p.ProductId & ", Purchased? " & (p.PurchaseState = p.STATE_PURCHASED))
      Next
   End If
End Sub

Purchasing a product is done by calling: manager.RequestPayment. The user will be asked to approve the payment. The PurchaseCompleted event will be raised when the operation completes.

Note that managed products can only be purchased once. Only after you call ConsumeProduct will the user be able to purchase the same item again.

Consuming purchased products is done by calling manager.ConsumeProduct.
For example:
B4X:
If ownedProducts.ContainsKey("test2") Then
   manager.ConsumeProduct(ownedProducts.Get("test2"))
End If

The ProductConsumed event will be raised.

Tips
- See this tutorial for more information about the possible testing options: Testing In-app Billing | Android Developers
- If you get a "signature verification error" when trying to make a purchase then you should make sure that the licensing key is correct. If it is correct then try to upload a new APK.
- It is recommended to use a process global variable to hold the key. This way it will be obfuscated when you compile in obfuscated mode.
- Only one background request can run at a time.

The library is available here:
http://www.b4x.com/forum/additional.../29998-app-billing-v3-library.html#post174139
 
Last edited:

rafaelbr20

Member
Licensed User
Longtime User
(in reply to your previous post) Add Log(Success). The event should be raised.

Hi Erel,

I Added Log(Success) on "manager_PurchaseCompleted" but nothing was writen on Log Output !

Even when the purchase is complete the event " manager_PurchaseCompleted" never raises.

This event is not raising also when close/cancel the billing operation. To Cancel the billing operation, try to click on BACK BUTTON on billing window appears and then, try to call "manager.RequestPayment()" again.

B4X:
Sub manager_PurchaseCompleted(Success As Boolean, Product As Purchase)
    Log(Success)
    If Success  = True Then
    manager.ConsumeProduct(Product)
    End If
End Sub

My code is inside a class module !

B4X:
'Class module
Sub Class_Globals
    Dim manager As BillingManager3
      Private key As String = "MIIBIjANBgkqh...."
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
     manager.Initialize("manager", key)
      manager.DebugLogging = True
End Sub

Sub Manager_BillingSupported (Supported As Boolean, Message As String)
   Log(Supported & ", " & Message)
   Log("Subscriptions supported: " & manager.SubscriptionsSupported)
   If Supported Then
    buscarProdutosComprados
   End If
End Sub

Sub manager_OwnedProducts (Success As Boolean, purchases As Map)
   baseMod.atualizaBdComprasUsuario(Success,purchases)
End Sub

Sub buscarProdutosComprados
    manager.GetOwnedProducts ' Ao Executar este método, o resultado será o evento "manager_OwnedProducts(Success As Boolean, purchases As Map)"
End Sub

Sub manager_PurchaseCompleted(Success As Boolean, Product As Purchase)
    'Após concluir a compra, atualizar o banco de dados e o MAP com as compras do usuário
    Log(Success)
    If Success  = True Then
    manager.ConsumeProduct(Product)
    End If
End Sub

Sub efetuarCompraProduto(skuProduto As String)
    manager.RequestPayment(skuProduto,"inapp",skuProduto)
End Sub

I see that billing window is like a new application right ? When i check the apps that is open, i see 2 , one is mine and other one is Play Store Window. If i close it , some process is still running and i can´t check when it occurs or kill that window. See the images attached !

Please EREL, take a quickly look on those links, they are saying that has some bug but they have a update to fix it. They are having the same problem as mine.

http://stackoverflow.com/questions/...-launchpurchaseflow-because-launchpurchaseflo

http://stackoverflow.com/questions/...-v3-example-hit-buy-back-button-and-buy-again

http://stackoverflow.com/questions/16860586/android-billing-error-you-own-this-item

Thanks Again Erel !!
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
I've just made the following test:
B4X:
Sub Process_Globals
  Dim manager As BillingManager3
  Private key As String = "MIIBIjAN..."
   
End Sub

Sub Globals


End Sub

Sub Activity_Create(FirstTime As Boolean)
  If FirstTime Then
  manager.Initialize("manager", key)
  manager.DebugLogging = True
  End If
End Sub

Sub Manager_BillingSupported (Supported As Boolean, Message As String)
  Log(Supported & ", " & Message)
  Log("Subscriptions supported: " & manager.SubscriptionsSupported)
End Sub

Sub Activity_Click
   manager.RequestPayment("test1", "inapp", "aaa")
End Sub

Sub manager_PurchaseCompleted (Success As Boolean, Product As Purchase)
   Log(Success)
End Sub

The PurchaseCompleted event is fired when I press on the back key. I can then request a new payment.

SS-2014-05-08_16.04.52.png
 

rafaelbr20

Member
Licensed User
Longtime User
Hi Erel,

The code was on a CLASS MODULE, and i changed now to a CODE MODULE and it works. I don´t know why , but it´s working now.

I Use Modules because all methods will be called by many activities, and i want to reuse code.

Thanks so much for your help !!

Rafael
 

JOTHA

Well-Known Member
Licensed User
Longtime User
Hi Erel,
The first step is to upload a draft APK to Google developer console.
What do you mean with draft APK?
I made the upload as a "draft" (translatet to german: "Entwurf"), but there is no way to connect to Google.
Do I have to upload the APK in alpha- or beta-modus? ... or as a release?

In the Log-file there is also nothing to see ... :(
 

JOTHA

Well-Known Member
Licensed User
Longtime User
Start with uploading the app without publishing it. Though if it doesn't work then publish it and then deactivate the app.
Thank you Erel.
Without publishing it doesn't work. I published it now ... and have to wait some time until it is available.
Then I try it again ... and send my feedback. ;)
 

JOTHA

Well-Known Member
Licensed User
Longtime User
Hello Erel and community,

after I published the app, the first problem was
  1. ... that the publisher (myself) couldn't make an In-App-Billing.
  2. I used another tablet with another google-account and I made the In-App-Billing (I had to pay in real money).
  3. In the 3rd step I deactivated the app on Google Play
  4. After deactivation, it is not possible to make the In-App-Billing.
Is there another way to test the In-App-Billing, because I dont like to pay money for every testing on Google Play? o_O
 

LeeM

Member
Licensed User
Longtime User
Hello Erel and community,

after I published the app, the first problem was
  1. ... that the publisher (myself) couldn't make an In-App-Billing.
  2. I used another tablet with another google-account and I made the In-App-Billing (I had to pay in real money).
  3. In the 3rd step I deactivated the app on Google Play
  4. After deactivation, it is not possible to make the In-App-Billing.
Is there another way to test the In-App-Billing, because I dont like to pay money for every testing on Google Play? o_O

I hope I've remembered all this correctly:
In the developer console click on Settings.
There's a section for Licence Testing. Fill in the gmail addresses of any testers and they can make purchases without paying real money (I think). I don't think you can use your developer email address (because the developer can't purchase their own apps) so set up some other gmail addresses and test with those (maybe use the google account on your other tablet).
 

JOTHA

Well-Known Member
Licensed User
Longtime User
Hello LeeM,

thank you for your tips!

I'm not shure if this works, because I think you mean licensing, but I mean In-App-Billing.
I've tested your way over the license testing, but there is no result ...
 

JOTHA

Well-Known Member
Licensed User
Longtime User
Hello LeeM,
I've tested your way over the license testing, but there is no result ...
I tried it again ... an now I got the result !!!

You' right ... it works now !! :)
Maybe it took some time at google play to activate this function.

Tanks again! ;)
 

LeeM

Member
Licensed User
Longtime User
Hello LeeM,

I tried it again ... an now I got the result !!!

You' right ... it works now !! :)
Maybe it took some time at google play to activate this function.

Tanks again! ;)

Yes sometimes it takes a while for your changes to take effect.
Glad to help :D
 

Alberto Vilades

Member
Licensed User
Longtime User
Hi,

but "manager_PurchaseCompleted" only triggers when you buy a product, no with "ConsumeProduct" or when I cancel transaction in "Wallet Merchant Center". Correct?

How can I know in real time when the state is CANCELEDE or REFUNDED?

thanks
 

tcgoh

Active Member
Licensed User
Longtime User
Hi,

I have gone through the tutorial but still don't quite understand. I'm trying to have inapp billing in my App. When starting my APP which is free, only pay button (button1) should be visible.
Once button1 is click and purchase done, then label 1 and button 2 will be shown.

what's wrong with my codes
Sub Process_Globals

Dim manager As BillingManager3
Private key As String = "MIIBIjAN.........."

End Sub

Sub Globals
Dim button1, button2 As Button
Dim label1 As Label
Dim ImageView1 As ImageView
End Sub

Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
manager.Initialize("manager", key)
manager.DebugLogging = True
End If

Activity.LoadLayout("Main")'
End Sub

Sub Manager_BillingSupported (Supported As Boolean, Message As String)
Log(Supported & ", " & Message)
Log("Subscriptions supported: " & manager.SubscriptionsSupported)
If Supported Then
manager.GetOwnedProducts
End If
End Sub

Sub manager_OwnedProducts (Success As Boolean, purchases As Map)
Log(Success)
If Success Then
Log(purchases)
For Each p As Purchase In purchases.Values
Log(p.ProductId & ", Purchased? " & (p.PurchaseState = p.STATE_PURCHASED))
Next

label1.Visible = True
button2.Visible = True
'do my paid program
End If
End Sub

Sub button1_click
manager.RequestPayment("testbill", "inapp", "buyapp")
End Sub

Sub button2_click
ImageView1.Visible = True
End Sub

Thank for any help
 

tcgoh

Active Member
Licensed User
Longtime User
Hi Erel,

Thanks for the response. The code is working when I uploaded to play store, but if I used the posted code, all user will be able to see button2 even without making a InAPP purchase? (button2.visible = false in Designer)

How do I only make button1 visible (button2 hidden until making an InApp purchase) ?

Thanks
 
Top