Android

How to implement In app Purchase in Android.

Prerequisite:- Before starting to implement the In app billing I assume that you must have knowledge about how to execute simple java and android programmes.
To implementing Google Play In-app Billing the Google Play Billing Library must be installed in the development system.
To check whether or not the library is installed in your system by selecting the Eclipse Window -> Android SDK Manager menu option there will be one Extras section which has Google play Billing Library check either it's checked or not if not check it.

                                                               Fig. 1.0

For checking if google play billing library successfully installed you can check it on this path-
<sdk path>/extras/google/play_billing
contains a file named IInAppBillingService.aidl which require Google Play billing support. 

Now I start to creating the example of In-app Billing Project

Required Permission in Android Manifest File

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.vending.BILLING" />
 

Adding the IInAppBillingService.aidl File to the Project

Create a package in src folder name as < com.android.vending.billing >. Now copy <IInAppBillingService.aidl> file from TrivialDrive sample project and paste inside the package as shown in below figure in red circle.

                                                     Fig. 1.1
 
Note: Now import the TrivialDrive sample project into Eclipse so that the utility classes can be added to your project.
Copy all java file of trivialdrivesample.util package and paste into project inside your package as shown in below in figure in red circle.



Obtaining public license key from Google developer account

Create app in your developer account it is not necessary to upload .apk at this point if you want just for testing purpose.

Then click on Services & APIs tab and below at this page you will find a key get this key and paste into your project.

Create InApp products in Google developer account

Got to your App>>IN APP PRODUCTS
Now click on “Add New Products” copy product id and paste into your project like:
static final String ITEM_SKU_icings = "emobi.icings.purchased";

Add InApp Billing Test Account

You have to add atleast one test account for testing your purchasing. You can purchase the
Product without paying real money using your test account.

Testing  project
When you click on “Confirm Buy” button it will redirect to as shown below-


Click on ok button you will see a new screen as shown below

 Note: When you test your app for inapp billing you have to use signed .apk(you have to export your project using a keystore) Otherwise it will show an error like below

Below is complete code to integrate inapp billing purchase in Android-
Example code:

public class InAppBillingEmobi extends Activity{
   
    Button btnBuy;
    private static final String TAG = "inappbilling";
    IabHelper mHelper;
    String ITEM_SKU;
//product items that you have to insert in your google play account
    static final String ITEM_SKU_icings = "emobi.icings.purchased";
    static final String ITEM_SKU_decoration = "
emobi.decoration.purchased";
    static final String ITEM_SKU_holidays = "
emobi.holidays.purchased";
    static final String ITEM_SKU_toppings = "
emobi.toppings.purchased";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inappbilling);
        btnBuy=(Button) findViewById(R.id.buyButton);
       
        String base64EncodedPublicKey = getResources().getString(R.string.licence_key);
       
        String category=getIntent().getStringExtra("category");
        final String itemsku=checkProduct(category);
        ITEM_SKU=itemsku;
       
        mHelper = new IabHelper(this, base64EncodedPublicKey);
       
   btnBuy.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mHelper.startSetup(new
                        IabHelper.OnIabSetupFinishedListener() {
                                 public void onIabSetupFinished(IabResult result)
                          {
                                if (!result.isSuccess()) {
                                   Log.d(TAG, "In-app Billing setup failed: " +
                                result);
                              } else {            
                                  purchaseRequest(itemsku);
                                      Log.d(TAG, "In-app Billing is set up OK");
                          }
                           }
                        });
                       
               
               
            }
        });
       
    }
    public void purchaseRequest(String itemsku)
    {
        if(itemsku.equalsIgnoreCase(ITEM_SKU_icings))
            mHelper.launchPurchaseFlow(InAppBillingEmobi.this, ITEM_SKU_icings, 10001,  mPurchaseFinishedListener, "");
        else if(itemsku.equalsIgnoreCase(ITEM_SKU_decoration))
            mHelper.launchPurchaseFlow(InAppBilling
Emobi.this, ITEM_SKU_decoration, 10001,  mPurchaseFinishedListener, "");
        else if(itemsku.equalsIgnoreCase(ITEM_SKU_holidays))
            mHelper.launchPurchaseFlow(InAppBilling
Emobi.this, ITEM_SKU_holidays, 10001,  mPurchaseFinishedListener, "");
        else if(itemsku.equalsIgnoreCase(ITEM_SKU_toppings))
            mHelper.launchPurchaseFlow(InAppBilling
Emobi.this, ITEM_SKU_toppings, 10001,  mPurchaseFinishedListener, "");
        else{
            Toast.makeText(InAppBillingNeeraj.this, "No product found", 2000).show();
        }
    }
   
 
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
    = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result,
                    Purchase purchase)
    {
       if (result.isFailure()) {
          // Handle error
          return;
     }     
     else if (purchase.getSku().equals(ITEM_SKU)) {
         consumeItem();
        btnBuy.setEnabled(false);
    }
         
   }
};

protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
   
   
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {    
      super.onActivityResult(requestCode, resultCode, data);
    }
};



public void consumeItem() {
    mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
   
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
   = new IabHelper.QueryInventoryFinishedListener() {
       public void onQueryInventoryFinished(IabResult result,
          Inventory inventory) {

                     
          if (result.isFailure()) {
          // Handle failure
          } else {
                 mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
            mConsumeFinishedListener);
          }
    }
};


IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
 public void onConsumeFinished(Purchase purchase,
       IabResult result) {

if (result.isSuccess()) {   
     Log.d(TAG, "consuming to free owned");
         btnBuy.setEnabled(true);
      // handle what to do after successfull purchase
    
} else {
       // handle error
}
}
};


IabHelper.OnConsumeFinishedListener mConsumeFinishedListener2 =
new IabHelper.OnConsumeFinishedListener() {
 public void onConsumeFinished(Purchase purchase,
       IabResult result) {

if (result.isSuccess()) {   
     Log.d(TAG, "consumed to free owned");
       btnBuy.setEnabled(true);
      returnToWall();
    
} else {
       // handle error
}
}
};





@Override
public void onDestroy() {
    super.onDestroy();
    if (mHelper != null) mHelper.dispose();
    mHelper = null;
}


public void returnToWall()
{
   
   
    setResult(RESULT_OK);
    finish();
}


public String checkProduct(String categoryName)
{
   
    if(categoryName.equalsIgnoreCase("icin"))
        return ITEM_SKU_icings;
    else if(categoryName.equalsIgnoreCase("deco"))
        return ITEM_SKU_decoration;
    else if(categoryName.equalsIgnoreCase("topp"))
        return ITEM_SKU_toppings;
    else if(categoryName.equalsIgnoreCase("holi"))
        return ITEM_SKU_holidays;
    else
        Log.d(TAG, "category not matched "+categoryName);
       
    return null;
   
}

}

XML view :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp"
    tools:context=".InAppBillingActivity">

  <Button
        android:id="@+id/buyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="buyClick"
        android:text="Confirm Buy" />

    </RelativeLayout>

This Topic covered the steps involved to implementing Google Play in-app billing within an Android application.
 


 

 



 

 

 



No comments:

Post a Comment