Android:购买后消费产品(应用内结算) [英] Android: Consume a product after purchase (in-app billing)

查看:170
本文介绍了Android:购买后消费产品(应用内结算)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用计费方面遇到一些问题,我想在应用内创建一个可以多次购买的产品。但谷歌以一种产品首先必须消费的方式进行应用程序计费,然后才能再次购买。我尝试使用以下代码:

I have some problems with in app billing, I wanted to create an product inside the app that can be bought several times. But google made the in app billing in a way that a product first must be consumed before you can buy it again. I tried it with the following code:

public class HomeFragment extends Fragment {

    private WebView homesite;
    private String homeTabUrl;
    private ProgressBar pBar;
    private Bundle webViewBundle;
    private Boolean buddyProfile = false;
    private Boolean buddyProfile2 = false;
    String url="";

    private Context mContext;
    final static String REQUEST_SUCCESS = "COMPLETED";


    //Amount point
    private static final int CREDIT_AMOUNT_100 = 100;
    private static final int CREDIT_AMOUNT_500 = 500;

    public static final String PAY_UID_100 = "messages";
    public static final String PAY_UID_500 = "messages2";


    private int mCreditAmount;
    private IabHelper mHelper;

    private static final int PAYINAPP_REQUESTCODE = 10001;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        setRetainInstance(true);
        StaticMembers.loadHomeTab = true;

        purchaseCredit(CREDIT_AMOUNT_100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Logger.error("YES-HERE IN ONACTIVITY RESULT");
        if (checkReultPayInApp(requestCode,resultCode, data)) {
            return;
        }

        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }



    private void loadData(View v) {
        initPayinApp();
    }

    private void initPayinApp() {
        // TODO Auto-generated method stub
        String base64EncodedPublicKey = "n9goJ2waiwGS3F0E+XpjlMJRnn6rKtaH3lWxGUZQjNJeAAdL78mFeUTAGaZLgX/YOIuERWL5IzLaTXNi69c60oeh489wi3lyGtWbNvXR5EXVNhazti2mZgwvjhUdzW7/73mV0rHZn0f24G3Dpy0zLaTXNi69c60oeh489wi3lyGtWbNvXR5EXVNhazti2mZgwvjhUdzW7/73mV0rHZn0f24G3Dpy0wkIFWt51OnnusIVlJHrwJ8dYz4mUZ6SLFhkXL8NhrRAcZKvUV3WySB55SA5uu1+IoGG7mJw0QPn9goJ2waiwGS3F0E+XpjlMJRnn6rKtaH3lWxGUZQjNJeAAdL78mFeUTAGaZLgX/YOIuERWL5I7uInsqWH+ny1HFDr2wIDAQAB";

        mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if (!result.isSuccess()) {
                    Log.d("YES", "In-app Billing setup failed: " + result);
                } else {
                    Log.d("YES", "In-app Billing is set up OK");
                }
            }
        });
    }

    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
            new IabHelper.OnConsumeFinishedListener() {
                public void onConsumeFinished(Purchase purchase, IabResult result) {
                    Logger.error("YES- Only in consume Listener");
                    if (result.isSuccess()) {

                        Logger.error("YES-in success consume Listener");
                    }
                    else {
                        Logger.error("YES-!in success consume Listener");
                    }
                }
            };


    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
            = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase)
        {
            Logger.error("YES-IN SUCCESS: " + result.getMessage());
            if (result.isFailure()) {
                Logger.error("YES-"+result.getMessage());
                return;
            }
           else if (purchase.getSku().equals(PAY_UID_100)) {

                Logger.error("YES-100 purchased");
                // remove query inventory method from here and put consumeAsync() directly
                Toast.makeText(getActivity(), "100 points added successfully", Toast.LENGTH_SHORT).show();
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);

            } else if ( purchase.getSku().equals(PAY_UID_500)) {
                Toast.makeText(getActivity(), "500 points added successfully", Toast.LENGTH_SHORT).show();
                Logger.error("YES-500 purchased");
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            }

        }
    };

    private void purchaseCredit(int creditAmount) {
        mCreditAmount = creditAmount;
        try {
            if (mHelper != null) mHelper.flagEndAsync();
            mHelper.launchPurchaseFlow(getActivity(), getIdPayInAppByAmount(creditAmount), PAYINAPP_REQUESTCODE,
                    mPurchaseFinishedListener, "mypurchasetoken");
        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    protected String getIdPayInAppByAmount(int creditAmount) {
        switch (creditAmount) {
            case CREDIT_AMOUNT_100:
                return PAY_UID_100;
            case CREDIT_AMOUNT_500:
                return PAY_UID_500;
        }
        return null;
    }

    private boolean checkReultPayInApp(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode!= PAYINAPP_REQUESTCODE) {
            return false;
        }

        int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
        String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
        String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");

        if (resultCode == Activity.RESULT_OK) {
            // Purchased Status = Purchased
            try {
                // Product Details JSON
                JSONObject jo = new JSONObject(purchaseData);
                // Purchased Product ID
                String sku = jo.getString("productId");
                addCredit(mCreditAmount);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

        }

        return true;
    }

    public void addCredit(final int creditAmount) {
        TaskPost.depositPoint(getActivity(), new User().getEmail(), creditAmount, new MyHttpClient.OnRequestListener() {

            public void OnStart() {
                // TODO Auto-generated method stub
            }

            @Override
            public void OnFinish(String result) {
                if (result.equalsIgnoreCase(REQUEST_SUCCESS)) {
                    Toast.makeText(mContext,"You have just add " + creditAmount+ " success to your account",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

请告诉我在消费时我做错了什么因此我可以相应地进行更改。

Please let me know what wrong I am doing while consuming the product so I can make changes accordingly.

推荐答案

您应该使用以前购买的商品。

you should consume the previously purchased items.

private void initPayinApp() {
        // TODO Auto-generated method stub
        String base64EncodedPublicKey = "";

        mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if (!result.isSuccess()) {
                    Log.d("YES", "In-app Billing setup failed: " + result);
                } else {
                    Log.d("YES", "In-app Billing is set up OK");

                    //comment this function once all the previously purchased items are consumed successfully 
                    reset();
                }
            }
        });
    }

void reset() {

    mHelper.queryInventoryAsync(mGotInventoryListener);
}


IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {

        @Override
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            Log.d(TAG, "Query inventory finished.");
            if (result.isFailure()) {
                Log.d(TAG, "Failed to query inventory: " + result);
                return;
            }

            Log.d(TAG, "Query inventory was successful.");
            if(inventory.hasPurchase(PAY_UID_100))
            {
                Log.d(TAG, "already purchased : " + PAY_UID_100);
                mHelper.consumeAsync(inventory.getPurchase(PAY_UID_100), mConsumeFinishedListener);
            }
            if(inventory.hasPurchase(PAY_UID_500))
            {
                Log.d(TAG, "already purchased : " + PAY_UID_500);
                mHelper.consumeAsync(inventory.getPurchase(PAY_UID_500), mConsumeFinishedListener);
            }
        }
    };

这篇关于Android:购买后消费产品(应用内结算)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆