In app purchase android tutorial

11 Nov

In app purchase android tutorial

In app purchase integration in android can be done very easily. First you need to create in app product in your app store.
To create in app product open the

https://play.google.com/apps/publish

And then goto Store Presence > In-app Products > Managed Products.

Enter a unique code,  title, short description and price of the product and then
active the product and save it.

In your AndroidManifest.xml add the billing permission.
<uses-permission android:name=”com.android.vending.BILLING” />

Now add below line in your dependencies section of build.gradle file.

implementation 'com.android.billingclient:billing:2.0.3'

Start a new activity or in you existing activity implements PurchasesUpdatedListener.

Like this.

public class AddActivity extends AppCompatActivity implements PurchasesUpdatedListener {

When you will implements PurchasesUpdatedListener you have add this method in the activity.

@Override
public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<com.android.billingclient.api.Purchase> purchases) {


}

You can add it blank for now. This method is called after payment complete with this method you can get the result of payment that if payment has success or failed.

And you can do necessary changes according to this. Here we will set user preference for successful payment.

We create a button in activity for payment.


<Button
android:layout_margin="20dp"
android:padding="15dp"
android:id="@+id/btn_remove_add"
android:text="Remove Add"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

and in your activity add onclick listener for this button

btn_remove_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {


}
})

On the clicking of the button first we will fetch all products from google play store that we have already created..

Then we will launch payment process.

Below is the complete example


import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.api.Response;
import com.google.firebase.messaging.FirebaseMessaging;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class AddActivity extends AppCompatActivity implements PurchasesUpdatedListener {

Button btn_remove_add;
BillingClient billing_client;

Activity activity;
Context mContext;
private BillingClient billingClient;

AppSettings app_settings;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);

mContext = getApplicationContext();
activity = this;

app_settings = new AppSettings();
app_settings.set_local(activity);

billingClient = BillingClient.newBuilder(activity).enablePendingPurchases().setListener(this).build();

btn_remove_add = (Button) findViewById(R.id.btn_remove_add);
AppSettings app = new AppSettings();
String purchased = app.getMiscData(“purchased”, “no”);
if(purchased.matches(“yes”) == true) {
btn_remove_add.setVisibility(View.INVISIBLE);
}

btn_remove_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

billingClient.startConnection(new BillingClientStateListener() {

@Override
public void onBillingSetupFinished(BillingResult billingResult) {

if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
List<String> skuList = new ArrayList<> ();
skuList.add(“xyzxx123”);
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(INAPP);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(0))
.build();
billingClient.launchBillingFlow(activity,flowParams);
}
});
}
}
@Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}

});
}
});

}

@Override
public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<com.android.billingclient.api.Purchase> purchases) {

//Handle the responseCode for the purchase
//If response code is OK, handle the purchase
//If user already owns the item, then indicate in the shared prefs that item is owned
//If cancelled/other code, log the error
AppSettings app = new AppSettings();

if (billingResult.getResponseCode() == BillingResponseCode.OK && purchases != null) {

for (Purchase purchase : purchases) {

//on success payment we are setting purchase variable to yes
SharedPreferences shared_pref;
shared_pref = getContext().getSharedPreferences(“test”, MODE_PRIVATE);
SharedPreferences.Editor toEdit;
toEdit = shared_pref.edit();
toEdit.putString(“purcahse”, “yes);
toEdit.commit();

}

Intent refresh = new Intent(AddActivity.this, MainActivity.class);
startActivity(refresh);
finish();

} else if (billingResult.getResponseCode() == BillingResponseCode.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
Log.v(“xxx purchase”,”failed”);
Intent refresh = new Intent(AddActivity.this, Main2Activity.class);
startActivity(refresh);
finish();

} else {
// Handle any other error codes.
}
}
}


This is a complete activity code. we are fetching  our product with sku  “xyzxx123” after getting the product we are launching payment process.
when payment process get completed  it comes in onPurchasesUpdated method.
we check success payment with the condition if (billingResult.getResponseCode() == BillingResponseCode.OK && purchases != null) {

We are setting a SharedPreferences variable purchase to yes. we can check this variable in other activity to provide new paid feature to our app users.

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × 3 =