Recherche…


Achats in-app consommables

Les produits gérés par consommables sont des produits qui peuvent être achetés plusieurs fois, tels que la monnaie du jeu, les vies de jeu, les bonus, etc.

Dans cet exemple, nous allons implémenter 4 produits gérés consommables différents "item1", "item2", "item3", "item4" .

Étapes en résumé:

  1. Ajoutez la bibliothèque de facturation intégrée à votre projet (fichier AIDL).
  2. Ajoutez l'autorisation requise dans le fichier AndroidManifest.xml .
  3. Déployez un fichier apk signé sur Google Developers Console.
  4. Définissez vos produits.
  5. Implémentez le code.
  6. Test de la facturation intégrée (facultatif).

Étape 1:

Tout d'abord, nous devrons ajouter le fichier AIDL à votre projet, comme l'explique clairement la documentation Google ici .

IInAppBillingService.aidl est un fichier AIDL (Android Interface Definition Language) qui définit l'interface avec le service In-App Billing Version 3. Vous utiliserez cette interface pour effectuer des demandes de facturation en appelant des appels de méthode IPC.

Étape 2:

Après avoir ajouté le fichier AIDL, ajoutez l'autorisation AndroidManifest.xml dans AndroidManifest.xml :

<!-- Required permission for implementing In-app Billing -->
<uses-permission android:name="com.android.vending.BILLING" />

Étape 3:

Générez un fichier apk signé et téléchargez-le sur Google Developers Console. Ceci est nécessaire pour que nous puissions commencer à définir nos produits intégrés.

Étape 4:

Définissez tous vos produits avec différents productID et fixez un prix à chacun d’entre eux. Il existe 2 types de produits (produits gérés et abonnements). Comme nous l'avons déjà dit, nous allons mettre en œuvre 4 différents produits gérés consommables "item1", "item2", "item3", "item4" .

Étape 5:

Après avoir effectué toutes les étapes ci-dessus, vous êtes maintenant prêt à commencer à implémenter le code lui-même dans votre propre activité.

Activité principale:

public class MainActivity extends Activity {

    IInAppBillingService inAppBillingService;
    ServiceConnection serviceConnection;

    // productID for each item. You should define them in the Google Developers Console.
    final String item1 = "item1";
    final String item2 = "item2";
    final String item3 = "item3";
    final String item4 = "item4";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate the views according to your layout file.
        final Button buy1 = (Button) findViewById(R.id.buy1);
        final Button buy2 = (Button) findViewById(R.id.buy2);
        final Button buy3 = (Button) findViewById(R.id.buy3);
        final Button buy4 = (Button) findViewById(R.id.buy4);

        // setOnClickListener() for each button.
        // buyItem() here is the method that we will implement to launch the PurchaseFlow.
        buy1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buyItem(item1);
            }
        });

        buy2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buyItem(item2);
            }
        });

        buy3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buyItem(item3);
            }
        });

        buy4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buyItem(item4);
            }
        });

        // Attach the service connection.
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceDisconnected(ComponentName name) {
                inAppBillingService = null;
            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                inAppBillingService = IInAppBillingService.Stub.asInterface(service);
            }
        };

        // Bind the service.
        Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);

        // Get the price of each product, and set the price as text to
        // each button so that the user knows the price of each item.
        if (inAppBillingService != null) {
            // Attention: You need to create a new thread here because
            // getSkuDetails() triggers a network request, which can
            // cause lag to your app if it was called from the main thread.
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    ArrayList<String> skuList = new ArrayList<>();
                    skuList.add(item1);
                    skuList.add(item2);
                    skuList.add(item3);
                    skuList.add(item4);
                    Bundle querySkus = new Bundle();
                    querySkus.putStringArrayList("ITEM_ID_LIST", skuList);

                    try {
                        Bundle skuDetails = inAppBillingService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
                        int response = skuDetails.getInt("RESPONSE_CODE");

                        if (response == 0) {
                            ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");

                            for (String thisResponse : responseList) {
                                JSONObject object = new JSONObject(thisResponse);
                                String sku = object.getString("productId");
                                String price = object.getString("price");

                                switch (sku) {
                                    case item1:
                                        buy1.setText(price);
                                        break;
                                    case item2:
                                        buy2.setText(price);
                                        break;
                                    case item3:
                                        buy3.setText(price);
                                        break;
                                    case item4:
                                        buy4.setText(price);
                                        break;
                                }
                            }
                        }
                    } catch (RemoteException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }

    // Launch the PurchaseFlow passing the productID of the item the user wants to buy as a parameter.
    private void buyItem(String productID) {
        if (inAppBillingService != null) {
            try {
                Bundle buyIntentBundle = inAppBillingService.getBuyIntent(3, getPackageName(), productID, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
                PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                startIntentSenderForResult(pendingIntent.getIntentSender(), 1003, new Intent(), 0, 0, 0);
            } catch (RemoteException | IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
    }

    // Unbind the service in onDestroy(). If you don’t unbind, the open
    // service connection could cause your device’s performance to degrade.
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (inAppBillingService != null) {
            unbindService(serviceConnection);
        }
    }

    // Check here if the in-app purchase was successful or not. If it was successful,
    // then consume the product, and let the app make the required changes.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1003 && resultCode == RESULT_OK) {

            final String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

            // Attention: You need to create a new thread here because
            // consumePurchase() triggers a network request, which can
            // cause lag to your app if it was called from the main thread.
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jo = new JSONObject(purchaseData);
                        // Get the productID of the purchased item.
                        String sku = jo.getString("productId");
                        String productName = null;

                        // increaseCoins() here is a method used as an example in a game to
                        // increase the in-game currency if the purchase was successful.
                        // You should implement your own code here, and let the app apply
                        // the required changes after the purchase was successful.
                        switch (sku) {
                            case item1:
                                productName = "Item 1";
                                increaseCoins(2000);
                                break;
                            case item2:
                                productName = "Item 2";
                                increaseCoins(8000);
                                break;
                            case item3:
                                productName = "Item 3";
                                increaseCoins(18000);
                                break;
                            case item4:
                                productName = "Item 4";
                                increaseCoins(30000);
                                break;
                        }

                        // Consume the purchase so that the user is able to purchase the same product again.
                        inAppBillingService.consumePurchase(3, getPackageName(), jo.getString("purchaseToken"));
                        Toast.makeText(MainActivity.this, productName + " is successfully purchased. Excellent choice, master!", Toast.LENGTH_LONG).show();
                    } catch (JSONException | RemoteException e) {
                        Toast.makeText(MainActivity.this, "Failed to parse purchase data.", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }
}

Étape 6:

Après avoir implémenté le code, vous pouvez le tester en déployant votre apk sur le canal bêta / alpha, et laissez les autres utilisateurs tester le code pour vous. Cependant, les véritables achats intégrés ne peuvent pas être effectués en mode de test. Vous devez d'abord publier votre application / jeu sur Play Store pour que tous les produits soient entièrement activés.

Plus d'informations sur les tests La facturation intégrée aux applications est disponible ici .

(Tierce partie) Bibliothèque In-App v3

Étape 1: Tout d'abord, suivez ces deux étapes pour ajouter des fonctionnalités d'application:

1. Ajoutez la bibliothèque en utilisant:

 repositories {
            mavenCentral()
        }
        dependencies {
           compile 'com.anjlab.android.iab.v3:library:1.0.+'
        }

2. Ajoutez une autorisation dans le fichier manifeste.

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

Étape 2: Initialisez votre processeur de facturation:

BillingProcessor bp = new BillingProcessor(this, "YOUR LICENSE KEY FROM GOOGLE PLAY CONSOLE HERE", this);

et implémenter le gestionnaire de facturation: BillingProcessor.IBillingHandler qui contient 4 méthodes: a. onBillingInitialized (); b. onProductPurchased (String productId, détails TransactionDetails): vous devez gérer les actions à effectuer après un achat réussi c. onBillingError (int errorCode, erreur pouvant être lancée): Gère toute erreur survenue lors du processus d'achat d. onPurchaseHistoryRestored (): pour restaurer des achats dans l'application

Étape 3: Comment acheter un produit.

Pour acheter un produit géré:

bp.purchase(YOUR_ACTIVITY, "YOUR PRODUCT ID FROM GOOGLE PLAY CONSOLE HERE");

Et pour acheter un abonnement:

bp.subscribe(YOUR_ACTIVITY, "YOUR SUBSCRIPTION ID FROM GOOGLE PLAY CONSOLE HERE");

Étape 4: Consommer un produit.

Pour consommer un produit, appelez simplement la méthode consumePurchase.

bp.consumePurchase ("VOTRE IDENTIFIANT DE CONSOLE GOOGLE PLAY ICI");

Pour d'autres méthodes liées à l'application, visitez github



Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow