50% Off/-

50% Off/-

Php

50% Off/-

50% Off/-

Web

50% Off/-

50% Off/-

Android Inappbilling Simple Usage

21-01-2019

MainActivity

public class MainActivity extends AppCompatActivity implements IabBroadcastReceiver.IabBroadcastListener {
    private  InAppBillingHelper inappbillingHelper;
    private static final int IN_APP_BILLING_REQUEST_CODE = 10001;
    private static final String SKU_TEST = "android.test.purchased";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initInappBillingHelper();
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inappbillingHelper.launchPurchase(SKU_TEST);
            }
        });
    }
    
    private void initInappBillingHelper() {
        inappbillingHelper= new InAppBillingHelper(this,IN_APP_BILLING_REQUEST_CODE, new InAppBillingHelperResponse() {
            @Override
            public void success(Purchase purchase) {
                appBillingSuccess(purchase);
            }
            
            @Override
            public void fail() {
                appBillingFail();
            }
            
            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                MainActivity.super.onActivityResult(requestCode,resultCode,data);
            }
        });
    }
    
    private void appBillingSuccess(Purchase purchase) {
        Toast.makeText(getApplicationContext(), "Satın alma başarılı", Toast.LENGTH_LONG).show();
    }
    private void appBillingFail() {
        Toast.makeText(getApplicationContext(), "Satın alma başarısız", Toast.LENGTH_LONG).show();
    }
    public void onResume() {
        super.onResume();
        inAppBillingHelper.registerReceiver();
    }
    @Override
    public void onPause() {
        super.onPause();
        inAppBillingHelper.unregisterReceiver();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IN_APP_BILLING_REQUEST_CODE)
        inappbillingHelper.onActivityResult(requestCode, resultCode, data);
        else super.onActivityResult(requestCode,resultCode,data);
    }
    @Override
    public void receivedBroadcast() {
        inappbillingHelper.receivedBroadcast();
    }
}

InAppBillingHelper

package com.dinibilgiyarismasiapp.Utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.dinibilgiyarismasiapp.MainActivity;
import com.dinibilgiyarismasiapp.R;
import com.dinibilgiyarismasiapp.inappbilling.IabBroadcastReceiver;
import com.dinibilgiyarismasiapp.inappbilling.IabHelper;
import com.dinibilgiyarismasiapp.inappbilling.IabResult;
import com.dinibilgiyarismasiapp.inappbilling.Inventory;
import com.dinibilgiyarismasiapp.inappbilling.Purchase;

import java.util.Date;
import java.util.UUID;

public class InAppBillingHelper {
    private static final String TAG = "InAppBilling";
    private static final String SKU_TEST = "android.test.purchased";
    private IabBroadcastReceiver mBroadcastReceiver;
    private IabHelper mHelper;
    private AppCompatActivity appCompatActivity;
    private InAppBillingHelperResponse inappbillingHelperResponse;
    private int requestCode;
    public InAppBillingHelper(AppCompatActivity appCompatActivity, int requestCode, InAppBillingHelperResponse inappbillingHelperResponse) {
        this.appCompatActivity = appCompatActivity;
        this.inappbillingHelperResponse = inappbillingHelperResponse;
        this.requestCode=requestCode;
        initIabHelper();
    }

    public void launchPurchase(String skuType) {
        try {
            mHelper.launchPurchaseFlow(this.appCompatActivity, skuType, this.requestCode,
                    mPurchaseFinishedListener, UUID.randomUUID().toString());
        } catch (Exception e) {
            complain(e.getMessage());
        }
    }

    private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper
            .OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase);

            // if we were disposed of in the meantime, quit.
            if (mHelper == null) return;

            if (result.isFailure()) {

                complain("Satın alma hatası: " + result);
                setWaitScreen(false);
                return;
            }
            if (!verifyDeveloperPayload(purchase)) {
                complain("Satın alma hatası. Authenticity verification failed.");
                setWaitScreen(false);
                return;
            }

            Log.d(TAG, "Purchase successful.");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                complain("Another async operation in progress.");
                setWaitScreen(false);
            }
        }
    };
    private IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper
            .OnConsumeFinishedListener() {
        public void onConsumeFinished(Purchase purchase, IabResult result) {
            Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result);

            // if we were disposed of in the meantime, quit.
            if (mHelper == null) return;

            // We know this is the "gas" sku because it's the only one we consume,
            // so we don't check which sku was consumed. If you have more than one
            // sku, you probably should check...
            if (result.isSuccess()) {
                // successfully consumed, so we apply the effects of the item in our
                // game world's logic, which in our case means filling the gas tank a bit
                Log.d(TAG, "Consumption successful. Provisioning.");
                paymentSuccess(purchase);
                //mTank = mTank == TANK_MAX ? TANK_MAX : mTank + 1;
                // saveData();
                //  alert("You filled 1/4 tank. Your tank is now " + String.valueOf(mTank) + "/4
                // full!");
            } else {
                complain("Error while consuming: " + result);
                paymentFail();
            }
            //updateUi();
            setWaitScreen(false);
            Log.d(TAG, "End consumption flow.");
        }
    };

    private void paymentSuccess(Purchase purchase) {
        this.inappbillingHelperResponse.success(purchase);
        alert("Payment success. " + purchase.getOrderId());
        if (SKU_TEST.equals(purchase.getSku())) {
            SharedPreferencesUtil.writeLong(appCompatActivity, "REKLAM_KADIRMA_ZAMANI",
                    new Date().getTime());
        }
    }

    private void paymentFail() {
        alert("Payment fail");
        this.inappbillingHelperResponse.fail();
    }

    private void initIabHelper() {
        mHelper = new IabHelper(appCompatActivity, this.appCompatActivity.getString(R.string.api_key));
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                Log.d(TAG, "Setup finished.");

                if (!result.isSuccess()) {
                    // Oh noes, there was a problem.
                    complain("Problem setting up in-app billing: " + result);
                    return;
                }

                // Have we been disposed of in the meantime? If so, quit.
                if (mHelper == null) return;

                // IAB is fully set up. Now, let's get an inventory of stuff we own.
                Log.d(TAG, "Setup successful. Querying inventory.");
                try {
                    mHelper.queryInventoryAsync(mGotInventoryListener);
                } catch (IabHelper.IabAsyncInProgressException e) {
                    complain("Error querying inventory. Another async operation in progress.");
                }
            }
        });
    }

    private IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper
            .QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            Log.d(TAG, "Query inventory finished.");

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null) return;

            // Is it a failure?
            if (result.isFailure()) {
                complain("Failed to query inventory: " + result);
                return; //todo comment out return
            }

            Log.d(TAG, "Query inventory was successful.");

            /*
             * Check for items we own. Notice that for each purchase, we check
             * the developer payload to see if it's correct! See
             * verifyDeveloperPayload().
             */

            // Do we have the premium upgrade?
            Purchase testPurchase = inventory.getPurchase(SKU_TEST);
            boolean isTest = (testPurchase != null && verifyDeveloperPayload(testPurchase));

            // Check for gas delivery -- if we own gas, we should fill up the tank immediately

            if (isTest) {
                Log.d(TAG, "We have gas. Consuming it.");
                try {
                    mHelper.consumeAsync(inventory.getPurchase(SKU_TEST), mConsumeFinishedListener);
                } catch (IabHelper.IabAsyncInProgressException e) {
                    complain("Error consuming gas. Another async operation in progress.");
                }
                return;
            }

            setWaitScreen(false);
            Log.d(TAG, "Initial inventory query finished; enabling main UI.");
        }
    };

    boolean verifyDeveloperPayload(Purchase p) {
        String payload = p.getDeveloperPayload();

        /*
         * TODO: verify that the developer payload of the purchase is correct. It will be
         * the same one that you sent when initiating the purchase.
         *
         * WARNING: Locally generating a random string when starting a purchase and
         * verifying it here might seem like a good approach, but this will fail in the
         * case where the user purchases an item on one device and then uses your app on
         * a different device, because on the other device you will not have access to the
         * random string you originally generated.
         *
         * So a good developer payload has these characteristics:
         *
         * 1. If two different users purchase an item, the payload is different between them,
         *    so that one user's purchase can't be replayed to another user.
         *
         * 2. The payload must be such that you can verify it even when the app wasn't the
         *    one who initiated the purchase flow (so that items purchased by the user on
         *    one device work on other devices owned by the user).
         *
         * Using your own server to store and verify developer payloads across app
         * installations is recommended.
         */

        return true;
    }

    void setWaitScreen(boolean set) {
        //  findViewById(R.id.screen_main).setVisibility(set ? View.GONE : View.VISIBLE);
        //findViewById(R.id.screen_wait).setVisibility(set ? View.VISIBLE : View.GONE);
    }

    void complain(String message) {
        Log.e(TAG, "**** TrivialDrive Error: " + message);
        alert("Error: " + message);
    }

    void alert(String message) {
        AlertDialog.Builder bld = new AlertDialog.Builder(appCompatActivity);
        bld.setMessage(message);
        bld.setNeutralButton("Tamam", null);
        Log.d(TAG, "Showing alert dialog: " + message);
        bld.create().show();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
        if (mHelper == null) return;

        // Pass on the activity result to the helper for handling
        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            // not handled, so handle it ourselves (here's where you'd
            // perform any handling of activity results not related to in-app
            // billing...
            inappbillingHelperResponse.onActivityResult(requestCode, resultCode, data);
        } else {
            Log.d(TAG, "onActivityResult handled by IABUtil.");
        }
    }

    public void receivedBroadcast() {
        Log.d(TAG, "Received broadcast notification. Querying inventory.");
        try {
            mHelper.queryInventoryAsync(mGotInventoryListener);
        } catch (IabHelper.IabAsyncInProgressException e) {
            complain("Error querying inventory. Another async operation in progress.");
        }
    }
    public void registerReceiver(){
        mBroadcastReceiver = new IabBroadcastReceiver((IabBroadcastReceiver.IabBroadcastListener) appCompatActivity);
        IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
        appCompatActivity.registerReceiver(mBroadcastReceiver,broadcastFilter);
    }
    public void unregisterReceiver(){
        appCompatActivity.unregisterReceiver(mBroadcastReceiver);
    }
}

InAppBilllingHelperResponse

package com.dinibilgiyarismasiapp.Utils;

import android.content.Intent;

import com.dinibilgiyarismasiapp.inappbilling.Purchase;

public interface InAppBillingHelperResponse {
    void success(Purchase purchase);
    void fail();
    void onActivityResult(int requestCode, int resultCode, Intent data);
}

© 2019 Tüm Hakları Saklıdır. Codesenior.COM