Skip to main content
Añadiendo usar la libreria https://github.com/anjlab/android-inapp-billing-v3
Origen Enlace
Codelaby
  • 11.2k
  • 15
  • 73
  • 154

Update

Usando librería Android In-App Billing v3 Library

Recomiendo la librería In-App Billing v3 Library que facilita todo el proceso de preparativos y hace que usar los pagos sea de lo más intuitivo, agilizando comprobaciones etc...

Update

Usando librería Android In-App Billing v3 Library

Recomiendo la librería In-App Billing v3 Library que facilita todo el proceso de preparativos y hace que usar los pagos sea de lo más intuitivo, agilizando comprobaciones etc...

se añadieron 175 caracteres en el cuerpo
Origen Enlace
Codelaby
  • 11.2k
  • 15
  • 73
  • 154
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()) {
                if (result.getResponse() == 7) {
                    complain("Ya tiene el producto ");
                } else {
                    complain("Error purchasing: " + result);
                }
            return;
        }
        if (!verifyDeveloperPayload(purchase)) {
            complain("Error purchasing. Authenticity verification failed.");
            return;
        }

        Log.w(TAG, "Purchase successful.");

        if (purchase.getSku().equals(SKU_PREMIUM)) {
            // bought the premium upgrade!
            Log.w(TAG, "Purchase is premium upgrade. Congratulating user.");
            alert("Thank you for upgrading to premium!");
            mIsPremium = true;
        }
    }
};
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("Error purchasing: " + result);
            return;
        }
        if (!verifyDeveloperPayload(purchase)) {
            complain("Error purchasing. Authenticity verification failed.");
            return;
        }

        Log.w(TAG, "Purchase successful.");

        if (purchase.getSku().equals(SKU_PREMIUM)) {
            // bought the premium upgrade!
            Log.w(TAG, "Purchase is premium upgrade. Congratulating user.");
            alert("Thank you for upgrading to premium!");
            mIsPremium = true;
        }
    }
};
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()) {
                if (result.getResponse() == 7) {
                    complain("Ya tiene el producto ");
                } else {
                    complain("Error purchasing: " + result);
                }
            return;
        }
        if (!verifyDeveloperPayload(purchase)) {
            complain("Error purchasing. Authenticity verification failed.");
            return;
        }

        Log.w(TAG, "Purchase successful.");

        if (purchase.getSku().equals(SKU_PREMIUM)) {
            // bought the premium upgrade!
            Log.w(TAG, "Purchase is premium upgrade. Congratulating user.");
            alert("Thank you for upgrading to premium!");
            mIsPremium = true;
        }
    }
};
se añadieron 5683 caracteres en el cuerpo
Origen Enlace
Codelaby
  • 11.2k
  • 15
  • 73
  • 154

El sistema del ejemplo es obtener la versión PREMIUM, a partir de la gratuita.

Se debe especificar la compra integrada con un identificador, en este caso premium eso se hace en el Google Play Developer Console siguiendo Administrar la facturación integrada

PREREQUISITOS

private IabHelper mHelper;
private IabBroadcastReceiver mBroadcastReceiver;
private IabHelper.QueryInventoryFinishedListener mGotInventoryListener;
boolean mIsPremium = false;
static final String SKU_PREMIUM = "premium";
static final int RC_REQUEST = 10001;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;

La actividad añadir la implementación IabBroadcastReceiver.IabBroadcastListener

Al onCreate iniciar las compras integradas.

String base64EncodedPublicKey = "TU_CLAVE_APP"
mHelper = new IabHelper(this, base64EncodedPublicKey);

Habilitar el sistema de depuración

mHelper.enableDebugLogging(true); //quitarlo si es modo release

Iniciar el sistema de pagos integrados

Se inicia el servicio, para obtener las compras integradas, para luego obtener el listado de items comprados con otro listener mGotInventoryListener

    Log.d(TAG, "Starting setup.");
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        @Override
        public void onIabSetupFinished(IabResult result) {
            Log.d(TAG, "Setup finished.");

            if (!result.isSuccess()) {
                Log.e(TAG, "In-app Billing setup failed: " + result);
            } else {
                Log.d(TAG, "In-app Billing is set up OK");
            }

            if (mHelper == null) return;

            mBroadcastReceiver = new IabBroadcastReceiver((IabBroadcastReceiver.IabBroadcastListener) MainActivity.this);
            IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
            registerReceiver(mBroadcastReceiver, broadcastFilter);

            // 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.");
            }
        }
    });

Obtener el inventario

Con el listener QueryInventoryFinishedListener se puede recuperar los objetos del inventario de compra, así poder activar el flag mIsPremium de la app para que tenga toda las funcionalidades.

    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;
            }

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


            // Do we have the premium upgrade?
            Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
            mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
            Log.d("PREMIUM =","User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
            alert("User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));

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

Realizar compra PREMIUM

Con launchPurchaseFlow se lanzará el cuadro de dialogo donde el usuario puede ver el precio del item y escoger su forma de pago.

String payload = "mypurchasetoken";

try {
    mHelper.launchPurchaseFlow(MainActivity.this, SKU_PREMIUM, RC_REQUEST,
            mPurchaseFinishedListener, payload);
} catch (IabHelper.IabAsyncInProgressException e) {
    e.printStackTrace();
}

Capturando el evento de Compra

La compra puede retornar diferentes errores:

  • cancelación parte de usuario
  • pago rechazado
  • compra realizada

Para capturar el evento de compra se usa 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("Error purchasing: " + result);
            return;
        }
        if (!verifyDeveloperPayload(purchase)) {
            complain("Error purchasing. Authenticity verification failed.");
            return;
        }

        Log.w(TAG, "Purchase successful.");

        if (purchase.getSku().equals(SKU_PREMIUM)) {
            // bought the premium upgrade!
            Log.w(TAG, "Purchase is premium upgrade. Congratulating user.");
            alert("Thank you for upgrading to premium!");
            mIsPremium = true;
        }
    }
};

El sistema del ejemplo es obtener la versión PREMIUM, a partir de la gratuita.

Se debe especificar la compra integrada con un identificador, en este caso premium eso se hace en el Google Play Developer Console siguiendo Administrar la facturación integrada

PREREQUISITOS

private IabHelper mHelper;
private IabBroadcastReceiver mBroadcastReceiver;
private IabHelper.QueryInventoryFinishedListener mGotInventoryListener;
boolean mIsPremium = false;
static final String SKU_PREMIUM = "premium";
static final int RC_REQUEST = 10001;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;

La actividad añadir la implementación IabBroadcastReceiver.IabBroadcastListener

Al onCreate iniciar las compras integradas.

String base64EncodedPublicKey = "TU_CLAVE_APP"
mHelper = new IabHelper(this, base64EncodedPublicKey);

Habilitar el sistema de depuración

mHelper.enableDebugLogging(true); //quitarlo si es modo release

Iniciar el sistema de pagos integrados

Se inicia el servicio, para obtener las compras integradas, para luego obtener el listado de items comprados con otro listener mGotInventoryListener

    Log.d(TAG, "Starting setup.");
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        @Override
        public void onIabSetupFinished(IabResult result) {
            Log.d(TAG, "Setup finished.");

            if (!result.isSuccess()) {
                Log.e(TAG, "In-app Billing setup failed: " + result);
            } else {
                Log.d(TAG, "In-app Billing is set up OK");
            }

            if (mHelper == null) return;

            mBroadcastReceiver = new IabBroadcastReceiver((IabBroadcastReceiver.IabBroadcastListener) MainActivity.this);
            IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
            registerReceiver(mBroadcastReceiver, broadcastFilter);

            // 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.");
            }
        }
    });

Obtener el inventario

Con el listener QueryInventoryFinishedListener se puede recuperar los objetos del inventario de compra, así poder activar el flag mIsPremium de la app para que tenga toda las funcionalidades.

    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;
            }

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


            // Do we have the premium upgrade?
            Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
            mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
            Log.d("PREMIUM =","User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
            alert("User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));

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

Realizar compra PREMIUM

Con launchPurchaseFlow se lanzará el cuadro de dialogo donde el usuario puede ver el precio del item y escoger su forma de pago.

String payload = "mypurchasetoken";

try {
    mHelper.launchPurchaseFlow(MainActivity.this, SKU_PREMIUM, RC_REQUEST,
            mPurchaseFinishedListener, payload);
} catch (IabHelper.IabAsyncInProgressException e) {
    e.printStackTrace();
}

Capturando el evento de Compra

La compra puede retornar diferentes errores:

  • cancelación parte de usuario
  • pago rechazado
  • compra realizada

Para capturar el evento de compra se usa 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("Error purchasing: " + result);
            return;
        }
        if (!verifyDeveloperPayload(purchase)) {
            complain("Error purchasing. Authenticity verification failed.");
            return;
        }

        Log.w(TAG, "Purchase successful.");

        if (purchase.getSku().equals(SKU_PREMIUM)) {
            // bought the premium upgrade!
            Log.w(TAG, "Purchase is premium upgrade. Congratulating user.");
            alert("Thank you for upgrading to premium!");
            mIsPremium = true;
        }
    }
};
Origen Enlace
Codelaby
  • 11.2k
  • 15
  • 73
  • 154
Loading