Android Payment access Google in-app-billing

Source: Internet
Author: User
Tags android sdk manager



Because companies need to access Google's in-app payments (that is, Google's In-app billing V3), access to a lot of articles in the process, but also encountered a lot of problems. So I would like to share with you and the exchange of ideas, good nonsense not much to say below we began to access Google's in-app payment.



The first step: getting Ready for work



First you want to use Google's payment, you must first have a test machine with Google Play service installed, here are three ways to:



1) If you have Xiaomi test machine it is best to keep the Google Play service intact because of Xiaomi's system.



2) If you are not able to see the attached connection here: Http://zhidao.baidu.com/link?url=qDozAoR_-mlZrVAp6oxLdcyR6uscgdDTsN2Z8PWvdLVF1USqKuAEIjw_QI_ 9ea5tkbzwifvhmdhvhlepjd5aeq installs Google Play services.



3) If you fail in either of these ways, don't be depressed. The following method may be better, click on the link: http://www.droid4x.cn/Download the hippocampus play simulator, which can solve the problem in one step.



The Google Play service is installed as shown below:






Second you need a VPN account (the best in the United States), recommend the VPN I use (such as) can choose the location of arbitrary.






Finally, you need to download the development kit, open the Android SDK Manager to download the Extras section of the Android SDK (for example), which includes the packages we used to pay for, development of the documentation, examples, and so on.






This folder can be found in the SDK directory after the download is complete android-sdk-windows\extras\google\play_billing






One of the samples is Google pay Access demo, can be based on the example of Google pay access. This folder can also be found in the SDK directory android-sdk-windows\docs\google\play\billing This is the official Google Payment documentation that provides an understanding of payment engineering and principles.






Instructions in the document is very detailed, it is recommended to complete the document, I believe that if you understand these documents, Google payment will be easy to take care of



Step Two: Code access



The preparation is done, the next step is the code access process, First you need to add the previously downloaded Iinappbillingservice.aidl file to your project, adding a new com.android.vending.billing folder in your project, which will iinappbillingservice.aidl this Files to refresh the project (specifically, you can refer to the downloaded demo).



Next, paste the code from the demo simple example in the previously downloaded Google Payment library into your project file (for example), and you can create a new package to put it in.






Here, if you are a beginner like me, you can use the banner of take doctrine directly, but pay attention to modify the class name and variable name, after all, this code is open to everyone can see, if you are the great God think this code is too low, you can also modify it to the fan you want.



1. Add Permissions



You need to add payment permissions to the Androidmanifest.xml file before accessing it:

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

// Create the helper, passing it our context and the public key to verify signatures with
        Log.d (TAG, "Creating IAB helper.");
        mHelper = new IabHelper (this, base64EncodedPublicKey);

        // enable debug logging (for a production application, you should set this to false).
        mHelper.enableDebugLogging (true);

        // Start setup. This is asynchronous and the specified listener
        // will be called once setup completes.
        Log.d (TAG, "Starting setup.");
        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.");
                mHelper.queryInventoryAsync (mGotInventoryListener);
            }
        });


3. Call the payment interface:
Is the method used to purchase goods:


mHelper.launchPurchaseFlow (this, SKU_GAS, RC_REQUEST,
                mPurchaseFinishedListener, payload);
Purchase method callback:

// Callback for when a purchase is finished
    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 ("Error purchasing:" + result);
                setWaitScreen (false);
                return;
            }
            if (! verifyDeveloperPayload (purchase)) {
                complain ("Error purchasing. Authenticity verification failed.");
                setWaitScreen (false);
                return;
            }

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

            if (purchase.getSku (). equals (SKU_GAS)) {
                // bought 1/4 tank of gas. So consume it.
                Log.d (TAG, "Purchase is gas. Starting gas consumption.");
                mHelper.consumeAsync (purchase, mConsumeFinishedListener);
            }
            else if (purchase.getSku (). equals (SKU_PREMIUM)) {
                // bought the premium upgrade!
                Log.d (TAG, "Purchase is premium upgrade. Congratulating user.");
                alert ("Thank you for upgrading to premium!");
                mIsPremium = true;
                updateUi ();
                setWaitScreen (false);
            }
            else if (purchase.getSku (). equals (SKU_INFINITE_GAS)) {
                // bought the infinite gas subscription
                Log.d (TAG, "Infinite gas subscription purchased.");
                alert ("Thank you for subscribing to infinite gas!");
                mSubscribedToInfiniteGas = true;
                mTank = TANK_MAX;
                updateUi ();
                setWaitScreen (false);
            }
        }
    };

    // Called when consumption is complete
    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.");
                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);
            }
            updateUi ();
            setWaitScreen (false);
            Log.d (TAG, "End consumption flow.");
        }
    };


4. Call the query interface:

Is used to query the goods you currently buy
mHelper.queryInventoryAsync (mGotInventoryListener);
Query method callback:
// Listener that's called when we finish querying the items and subscriptions we own
    IabHelper.QueryInventoryFinish edListener 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.");

            / *
             * 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 premiumPurchase = inventory.getPurchase (SKU_PREMIUM);
            mIsPremium = (premiumPurchase! = null && verifyDeveloperPayload (premiumPurchase));
            Log.d (TAG, "User is" + (mIsPremium? "PREMIUM": "NOT PREMIUM"));

            // Do we have the infinite gas plan?
            Purchase infiniteGasPurchase = inventory.getPurchase (SKU_INFINITE_GAS);
            mSubscribedToInfiniteGas = (infiniteGasPurchase! = null &&
                    verifyDeveloperPayload (infiniteGasPurchase));
            Log.d (TAG, "User" + (mSubscribedToInfiniteGas? "HAS": "DOES NOT HAVE")
                        + "infinite gas subscription.");
            if (mSubscribedToInfiniteGas) mTank = TANK_MAX;

            // Check for gas delivery-if we own gas, we should fill up the tank immediately
            Purchase gasPurchase = inventory.getPurchase (SKU_GAS);
            if (gasPurchase! = null && verifyDeveloperPayload (gasPurchase)) {
                Log.d (TAG, "We have gas. Consuming it.");
                mHelper.consumeAsync (inventory.getPurchase (SKU_GAS), mConsumeFinishedListener);
                return;
            }

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

5. Consumable goods
Because our in-app purchase products can be purchased repeatedly, but after each purchase, you need to consume the product. Note that this consumption does not mean that you have used the purchased product, but eliminates a mark that Google has imposed on the purchased product to indicate The second purchase has been successful before the next purchase can be made to avoid the problem of multiple deductions due to repeated purchases and inconsistent product numbers.

mHelper.consumeAsync (purchase, mConsumeFinishedListener);

Callback for consumed goods:
// Called when consumption is complete
    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.");
                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);
            }
            updateUi ();
            setWaitScreen (false);
            Log.d (TAG, "End consumption flow.");
        }
    };

6. Return data method:
Don't forget to add the following method when purchasing, it is used to come out the returned data.
@Override
    protected 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 ...
            super.onActivityResult (requestCode, resultCode, data);
        }
        else {
            Log.d (TAG, "onActivityResult handled by IABUtil.");
        }
    }
7. Destroy IabHelper after exiting:
IabHelper needs to be destroyed when exiting:

// We're being destroyed. It's important to dispose of the helper here!
    @Override
    public void onDestroy () {
        super.onDestroy ();

        // very important:
        Log.d (TAG, "Destroying helper.");
        if (mHelper! = null) {
            mHelper.dispose ();
            mHelper = null;
        }
    }
The third step: package upload
First of all, you need to have a google developer account, log in to the google developer background to add an application, and add the relevant parts of the product.
Secondly, Google ’s payment is not payable after writing the code and compiling it, so after completing the part of the code, you need to package the project and upload it to the Google developer background. You can look at this connection: http://jingyan.baidu.com/article / 7908e85c8dea30af491ad24f.html, upload to Bate version or ALPHA version, if it is developed by the company, there should be a girl or a man to help you complete this step, if it is your own. . . Ha ha.

Google's review process is still about half an hour soon. At this time, you need to add a test account. This document details how to add a test account. Of course, adding a test account does not mean that you can test it. At the end of the review, there is a test connection in the apk interface of the Google developer background. After opening, enter the test account to become a tester. At this time, you can test the Google payment

Step 4: Problems in the test

First of all, the test account needs to have a bound credit card and a VISA credit card account. Click the payment button. If you have become a tester, but Google prompts "I need to verify your identity and need to log in to your Google account", it is likely that your product id If there is a problem, you can check whether the product id is correct and try again.

There will be detailed instructions on how to add the product id google payment documentation.

If you encounter the prompt "Cannot buy the product you want to buy" during the test, it may be the reason that you have not yet become a tester or you use the developer account for testing.

1. The current application does not support the purchase of this product: make sure that the package name and signature on your phone are the same as those uploaded in the background. p.s. After uploading the background, the APK will take a while to take effect.

2. The purchased product does not exist: Make sure that the name of the product in your code is the same as the backend. If they are the same, you may have to wait an hour or two before testing. Google backend issues.

3. Loaded for a long time, and finally give you an unknown error: This problem regardless of it, Google background problem, will be tested again.

Finally, domestic developers make sure to test under vpn, if you have any doubts, you can chat with me privately! ! ! !

Source code download: https://github.com/guojunhua/GooglePay.git

Google In-app-Billing for Android payment access

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.