Maison  >  Article  >  Android Studio Java – Erreurs/problèmes d'achat dans l'application

Android Studio Java – Erreurs/problèmes d'achat dans l'application

王林
王林avant
2024-02-08 22:45:32598parcourir

L'éditeur php Baicao vous propose des méthodes pour résoudre les erreurs et les problèmes d'achat dans l'application Android Studio Java. Les achats intégrés sont une fonctionnalité courante lors du développement d'applications, mais de nombreux développeurs peuvent rencontrer divers problèmes lors de leur mise en œuvre. Cet article partagera des méthodes efficaces pour résoudre les erreurs et les problèmes d’achat via l’application afin de vous aider à mener à bien le développement et la sortie de votre application. Que vous rencontriez des problèmes tels que des produits indisponibles à l'achat, une interruption du processus d'achat ou un échec de vérification du paiement, nous vous fournirons des solutions détaillées pour vous aider à résoudre rapidement le problème et à améliorer l'expérience utilisateur de l'application.

Contenu des questions

Dans mon application, j'utilise cette bibliothèque pour ajouter des achats intégrés.

Voici mon code d'activité :

public class InfoController extends AppCompatActivity {

    private static final String PREFS_NAME = "TEST_MyPrefsFile";

    private static final String FIRST_TIME_KEY = "TEST_isFirstLaunch";

    private static final String IS_PRO_KEY = "TEST_isPro";
    private boolean isPro() {
        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return preferences.getBoolean(IS_PRO_KEY, false);
    }

    private void setProUser(boolean isPro) {
        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(IS_PRO_KEY, isPro);
        editor.apply();
    }

    private Button upgradeButton;

    String base64String = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    private BillingConnector billingConnector;

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

        upgradeButton = findViewById(R.id.upgradeButton);

        if (!isPro()) {
            upgradeButton.setText("Click here to upgrade to Pro");
            initializeBillingClient();
        } else {
            upgradeButton.setEnabled(false);
            upgradeButton.setText("User is Pro");
        }
    }


    private void initializeBillingClient() {
        List<String> nonConsumableIds = new ArrayList<>();
        nonConsumableIds.add("com.xxxx.pro");  // Replace with your actual non-consumable product ID

        billingConnector = new BillingConnector(this, base64String)
                .setNonConsumableIds(nonConsumableIds)
                .autoAcknowledge()
                .enableLogging()
                .connect();

        billingConnector.setBillingEventListener(new BillingEventListener() {
            @Override
            public void onProductsFetched(@NonNull List<ProductInfo> productDetails) {

            }

            //this IS the listener in which we can restore previous purchases.
            // Code will execute on InfoController.java appear. If pro is already purchased, unlock pro features.
            @Override
            public void onPurchasedProductsFetched(@NonNull ProductType productType, @NonNull List<PurchaseInfo> purchases) {
                String purchasedProduct;
                boolean isAcknowledged;

                for (PurchaseInfo purchaseInfo : purchases) {
                    purchasedProduct = purchaseInfo.getProduct();
                    isAcknowledged = purchaseInfo.isAcknowledged();

                    if (!isPro()) {
                        if (purchasedProduct.equalsIgnoreCase("com.xxxx.pro")) {
                            if (isAcknowledged) {

                                // CustomToast.makeText(InfoController.this, "The previous purchase was successfully restored.", Toast.LENGTH_SHORT).show();

                                // setProUser(true);

                                Toast.makeText(InfoController.this, "isAcknowledged", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            }

            //this IS NOT the listener in which we'll give user entitlement for purchases (see ReadMe.md why)
            @Override
            public void onProductsPurchased(@NonNull List<PurchaseInfo> purchases) {

            }

            //this IS the listener in which we'll give user entitlement for purchases (the ReadMe.md explains why)
            @Override
            public void onPurchaseAcknowledged(@NonNull PurchaseInfo purchase) {
                String acknowledgedProduct = purchase.getProduct();

                if (acknowledgedProduct.equalsIgnoreCase("com.xxxx.pro")) {

                    Toast.makeText(InfoController.this, "The purchase was successfully made.", Toast.LENGTH_SHORT).show();

                    setProUser(true);

                    upgradeButton.setEnabled(false);
                    upgradeButton.setText("User is Pro");
                }
            }

            @Override
            public void onPurchaseConsumed(@NonNull PurchaseInfo purchase) {

            }

            @Override
            public void onBillingError(@NonNull BillingConnector billingConnector, @NonNull BillingResponse response) {
                switch (response.getErrorType()) {
                    case ACKNOWLEDGE_WARNING:
                        //this response will be triggered when the purchase is still PENDING
                        CustomToast.makeText(InfoController.this, "The transaction is still pending. Please come back later to receive the purchase!", Toast.LENGTH_SHORT).show();
                        break;
                    case BILLING_UNAVAILABLE:
                    case SERVICE_UNAVAILABLE:
                        CustomToast.makeText(InfoController.this, "Billing is unavailable at the moment. Check your internet connection!", Toast.LENGTH_SHORT).show();
                        break;
                    case ERROR:
                        CustomToast.makeText(InfoController.this, "Something happened, the transaction was canceled!", Toast.LENGTH_SHORT).show();
                        break;
                    case ITEM_ALREADY_OWNED:
                        Toast.makeText(InfoController.this, "The purchase has already been made.", Toast.LENGTH_SHORT).show();
                        setProUser(true);
                        upgradeButton.setEnabled(false);
                        upgradeButton.setText("User is Pro");
                            break;
                    case ITEM_NOT_OWNED:
                        //TODO - failure to consume since item is not owned
                        break;
                }
            }
        });
    }

    public void onUpgradeButtonClick(View view) {
        billingConnector.purchase(InfoController.this, "com.xxxx.pro");
    }
}

Lorsque je testais les achats in-app, j'utilisais des codes promo (car je n'avais pas de carte connectée à mon compte).

Donc, lorsque j'ouvre cette activité, rien ne s'affiche. J'appuie sur upgradebutton,弹出升级提示,我选择促销代码并输入促销代码,单击下一步,它告诉我价格为0,我按确认。此后,购买提示窗口将关闭,没有任何反应。没有显示 toast 消息,升级按钮文本仍然显示:click here to upgrade to pro.

Si je ferme maintenant l'application, la rouvre et vais sur l'infocontroller (cette activité), le message toast s'affiche isacknowledged.

Ma question est donc la suivante : pourquoi rien ne se passe une fois l'achat terminé, mais lorsque j'ouvre à nouveau l'activité après l'achat, cela s'affiche isacknowledged ?

Solution

Vérifiez et confirmez le statut avant le traitement :

@override
public void onpurchasedproductsfetched(@nonnull producttype producttype, @nonnull list<purchaseinfo> purchases) {
    for (purchaseinfo purchaseinfo : purchases) {
        string purchasedproduct = purchaseinfo.getproduct();
        if (!ispro() && purchasedproduct.equalsignorecase("com.xxxx.pro")) {
            if (!billingconnector.ispurchaseditemacknowledged(purchaseinfo)) {
                // here is the code of purchase processing
            }
        }
    }
}

Déplacement également de la logique de confirmation de la méthode onpurchaseacknowledged vers la méthode onpurchasedproductsfetched. Cela pourrait aider.

@Override
public void onPurchasedProductsFetched(@NonNull ProductType productType, @NonNull List<PurchaseInfo> purchases) {
    for (PurchaseInfo purchaseInfo : purchases) {
        String purchasedProduct = purchaseInfo.getProduct();
        if (!isPro() && purchasedProduct.equalsIgnoreCase("com.xxxx.pro")) {
            // here is the code of purchase processing
            handlePurchase(purchaseInfo);
        }
    }
}

private void handlePurchase(PurchaseInfo purchaseInfo) {
    String acknowledgedProduct = purchaseInfo.getProduct();
    if (acknowledgedProduct.equalsIgnoreCase("com.xxxx.pro")) {
        Toast.makeText(InfoController.this, "The purchase was successfully made.", Toast.LENGTH_SHORT).show();
        setProUser(true);
        upgradeButton.setEnabled(false);
        upgradeButton.setText("User is Pro");
    }
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer