SDK Access (2) on Android Google play inside payment (In-app billing) Access

Source: Internet
Author: User
Tags oauth response code ticket root access android sdk manager


SDK Access (2) on Android Google play inside payment (In-app billing) Access


Next to the Android Facebook SDK access (1) after finishing the Facebook access process, you can then sort out the access process for Google Play in-app billing payments. Google Play is known as the official Google App Store and an important channel for publishing apps around the world. Payment as an important means of profitability, you can use the Google In-app billing API to achieve the goal.



The access process for Google Play In-app billing requires reading the access documentation. The official Access document address is:


Https://developer.android.com/google/play/billing/api.html

(1) Google Play Developer Console


The Google Play Developer console is the backend for managing apps, configuring products, and publishing. The reference address is:


Https://developer.android.com/distribute/googleplay/developer-console.html


Google Play's Help document address is:


Https://support.google.com/googleplay/android-developer/answer/6112435?hl=zh-Hans


Steps to use:


1. Sign up for Google Play developer account


The Google Play developer account Registration address is: (A $25 registration fee is required to support visa Credit card payments.) )


Https://play.google.com/apps/publish/signup

2. Configure the application products, get the client access parameters, the following steps are outlined below:


Create an app on Google Play backstage and set the game name. Fill in the product details as required. Upload APK, note that the uploaded apk must be the release signature of the formal package, while matching the package name and version number, and then configure the product item. Get access to Google Play's public key (BASE64 encoded RSA public key).


Managed Items: Each account can only be purchased once and cannot be re-purchased. Examples: Activation codes, unlocking levels, and so on.

Items that are not managed: The item can be purchased repeatedly. It is transparent to the consumer that it is not possible to repeat the purchase without consumption. For example: gold coins, diamonds and so on.

Subscription: Sell content, services, or features to users within the app by monthly or yearly billing.

3. Get Server access Parameters


After payment is completed, it is necessary to verify the validity of the paid ticket on the server. Also, you need to get the server-side parameters. The steps are as follows:
(1) Use the developer account that created the app to access the Google API admin backend. The address is as follows:


Https://console.developers.google.com/apis/credentials


(2) Confirm that the Google Play Android Developer API is enabled. If it is not enabled, click Enable.



(3) Configure OAuth, fill in the email address and product name, and save.



(4) Create the client OAuth ID.



(5) In the new interface, select the Web App. and configure the authorization address and redirect address, and click Create.



(6) Gets the client ID and client key.



(7) Back to enable API on Google Play background. Ensure an association and an enabled state.



(8) Obtain code with the client ID.
In the browser, visit the following address (note that XXX replaces the actual client ID):
Https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_ Type=code&access_type=offline&redirect_uri=http://www.example.com/oauth2callback&client_id=xxx



You get the following address, so you get the value of code:
Https://www.example.com/oauth2callback?code=XXX



(9) Use the obtained code to obtain the Refresh_token parameter.
Use post to request the following address, note the parameter:code=XXX&client_id=XXX&client_secret=XXX&redirect_uri=http://www.example.com/oauth2callback&grant_type=authorization_codewhere Grant_type is a fixed value.


Https://accounts.google.com/o/oauth2/token


Get JSON:

 
   {  
       "access_token" : "ya29.dAFAF9xX89iR4s0Li4_faSmtGFonWQz67HvfXZFkPWsY_tHI_q1c7fc6WTS9EqKMi7_wonxhp4Q2FA",  
       "token_type" : "Bearer",  
       "expires_in" : 3600,  
       "refresh_token" : "XXX"  
   }

This will get the Refresh_token parameter.
When the server verifies, it can get access_token and so on by Refresh_token.


(2) Google Play in-app Billing purchase Process


This is where I pick up the content of the process directly from the official Google Play document, so it's easy to find.


Google Play official Purchase process document: HTTPS://DEVELOPER.ANDROID.COM/GOOGLE/PLAY/BILLING/API.HTML?HL=ZH-CN

1. Purchase process


Familiarize yourself with the purchase process of the V3 version, and know the general payment steps and implementation logic.



(1) Your app sends a request to Google PlayisBillingSupportedto determine if the target version of the in-app billing API You're currently using is supported.



(2) When your app launches or when a user logs in, it's a good idea to check with Google Play to determine which products the user has. To inquire about a user's in-app purchase, send agetPurchasesrequest. If the request succeeds, Google Play returns a list of item IDs for the items purchased, aBundlelist of individual purchase details, and a list of purchase signatures.



(3) Usually, you need to inform the user whether the product is available for purchase. To find out more about in-app items that you define on Google Play, the app can sendgetSkuDetailsrequests. You must specify a list of product IDs in the query request. If the request succeeds, Google Play returns a product details (including the price, title, description, and Purchase type) of the itemBundle.



(4) If the user does not have an in-app item, you may be prompted to purchase it. In order to initiate a purchase request, your app sends agetBuyIntentrequest specifying the item ID and other parameters for the item to be purchased. When you create a new in-app item in the developer console, you should record its product ID.



Google Play isBundleincluded in the returnPendingIntent, and your app can use it to launch the checkout screen.



Your app starts by invoking astartIntentSenderForResultmethodPendingIntent.



Google Play sends a response Intent to your method when the checkout process is finished (that is, the user successfully buys the item or cancels the purchase)onActivityResult. AonActivityResultcode in the result code will be used to indicate whether the user completed the purchase or canceled the purchase. The responseIntentwill contain information about the items purchased, including the strings generated by Google Play in order to uniquely identify the purchase transactionpurchaseToken.Intentalso includes a purchase signature signed with your private developer key.


2. Consumption process


The payment for Google play is divided into购买-消耗two steps. If the product item that is configured on the Google Play background is a managed type of item, you only need to call the purchase, which is not a duplicate purchase. If you are configuring an item that is not managed type, you must manually invoke the consumption interface in the purchase success callback, otherwise the item cannot be purchased again.



In version 3rd, all in-app products are managed. In other words, the user's ownership of the purchased in-app product is maintained by Google Play, and your app can query the user's purchase information when needed. Once a user has successfully purchased an in-app item, the purchase is recorded on Google Play. In-app items are considered "owned" once they are sold. In-app items that are in the "owned" state can no longer be purchased via Google Play. You must send a consumption request to an in-app product that is owned and then Google Play to make it available for purchase again. Consuming in-app items will switch the item back to the "not owned" status and delete the previous purchase data.



In order to retrieve a list of items owned by the user, your app will send a call to Google PlaygetPurchases. Your app can make a consumption request by sending aconsumePurchasecall. In the request parameter, you must specify a unique string for the in-app itempurchaseToken, which is specified by Google Play when the item is sold. Google Play Returns a status code indicating whether the consumption has been successfully recorded.



(1) Call togetBuyIntentstart the purchase process.
(2) Receive a response from Google Play that indicates whether the purchase was completed successfullyBundle.
(3) If the purchase succeeds, the purchase is consumed by the callconsumePurchase.
(4) Receive a response code that indicates whether the consumption was completed successfully from Google Play.
(5) If the consumption is successful, configure the product in the application.



These are the entire process of buying to consumption, and how this complex purchase process can be implemented in the code layer. Fortunately we can use the Trickery method, with Google Play to provide us with the code "samples", save the development cycle.


(3) Google Play In-app Billing API Access 1. Download Google Play billing Library


Open Android SDK Manager. Tick the Google Play Billing library and Google Play Service in extras.



The downloaded library path should be in<android-sdk-root>/extras/google/play_billing. Directory structure

and import samples into eclipse. Similar to the Androidstudio, here is an introduction to the operation steps of Eclipse.


2. Copy the samples corresponding code directly into your project.




3. Add the following permissions in the Androidmanifest:
<uses-permission android:name="com.android.vending.BILLING" />
4. Initialize the In-app billing API. Put the following code directly to the appropriate place, usually in the oncreate of the main activity.IabHelperis a tool class that encapsulates the purchase-consumptionqueryInventoryAsyncis the order Query method. Note Replace the actual public key (in the Google play background creation app, in the services and APIs this can be found, a string of Base64 encoded strings).
// base64EncodedPublicKey is a Base64 encoded RSA public key
    String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE";
    // 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.
                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);
        }
    }); 
5. Payment. The following code is called when the purchase request is initiated. The SKU parameter is the product item ID that corresponds to the Google Play background configuration. Extradata can be used for transmitting parameters
 IabHelper.launchPurchaseFlow(Activity act, String sku, int requestCode, 
OnIabPurchaseFinishedListener listener, String extraData)
6. Consumption. The consumption method is typically called in the callback where the payment succeeds or the query succeeds.

Note: Items that are not managed will need to be called for consumption after payment is completed. Otherwise, you can't repeat the purchase. The ticket returned by the test account is not OrderID.

IabHelper.consumeAsync(Purchase purchase, OnConsumeFinishedListener listener)
7. Inquiries. In the query callback, detect if there is a payment but not consumption of goods, continue to invoke consumption. Can be used for missing orders processing. It is placed directly in the Iaphelper initialization.
IabHelper.queryInventoryAsync(QueryInventoryFinishedListener listener)
8. Destruction. It is generally performed in the ondestory of the main activity.
 
public void onDestroy() { super.onDestroy(); // very important:
        Log.d(TAG, "Destroying helper."); if (mHelper != null) mHelper.dispose();
        mHelper = null;
    }
(4) test access to Google Play In-app billing API 1. Install Google Framework on a test machine


Mobile phones in China generally need to manually install Google Play store, Google Play service, etc., and a "Google Installer" app is recommended here. Install this app to automatically detect which Google services are missing from your phone. However, installing the "Google Installer" section of the phone requires root access.
Download Google installer. Of course, the installation of Google Framework also requires a VPN, can FQ, normally open the Google Play store.


2. Install Google Play in-app billing app to Phone


As mentioned earlier, testing Google Play In-app billing access, must be the package name, the version is good and upload the same, and the signature must be release signed. This allows us to modify the release signature file to the default signature so that we can debug it. Run directly with your phone, eliminating the hassle of installing to your phone every time you pack



(1) Back up the official signature file first. Then, in the Windows command-line window, modify the KeyStore password for Android.
Keytool-storepasswd-keystore Test.keystore
First enter the original signature file password, and then enter the new password for Android.
(2) Modify the alias of the original signature file and modify it to Androiddebugkey.
Keytool-changealias-keystore Test.keystore-alias Test-destalias Androiddebugkey
Test is the alias of the original signature file, modified toandroiddebugkey
This step will require you to enter the password for the KeyStore (ie: Android) and the current alias
(3) Modify alias password
Keytool-keypasswd-keystore My.keystore-alias Androiddebugkey
This step will require you to enter the KeyStore password (ie: Android) and the original alias password, and then enter the new alias password, enter Android.
(4) Specify a default signature in eclipse
Select Window->preferences->android->build->browse and select the signature file you just created. In this way, you can directly connect the phone debugging run.


3. Add a Test Account


Add a tester account to the Google Play background upload alpha test or beta version.
(1) Create a Google + group
Invite testers to join the Google + Group, and the invitation will receive an email, but the invitation will probably have a 4-hour delay.



(2) Sharing test connection
Share the form as below to the tester, the tester opens the connection to join the test. "Org.cocos2d.game" is the package name that the app corresponds to.


Https://play.google.com/apps/testing/org.cocos2d.game

(5) Access FAQ 1. You can't buy the item you want to buy.


The current Google Play account is not a test account


2. You need to verify your identity. You'll need to sign in to your Google account.


The version number of the local test is the same as the version number of Google upload


3. Cannot load Library:soinfo_relocate (linker.cpp:993): Cannot locate symbol "signal"

05-05 19:08:32.148:e/androidruntime (7822): FATAL exception:main
05-05 19:08:32.148:e/androidruntime (7822): Java.lang.UnsatisfiedLinkError:Cannot load Library:soinfo_relocate ( linker.cpp:993): Cannot locate symbol "signal" referenced by "libcocos2dlua.so" ...
05-05 19:08:32.148:e/androidruntime (7822): at Java.lang.Runtime.loadLibrary (runtime.java:372)
05-05 19:08:32.148:e/androidruntime (7822): at Java.lang.System.loadLibrary (system.java:514)
05-05 19:08:32.148:e/androidruntime (7822): at Org.cocos2dx.lib.Cocos2dxActivity.onLoadNativeLibraries ( cocos2dxactivity.java:113)
05-05 19:08:32.148:e/androidruntime (7822): at Org.cocos2dx.lib.Cocos2dxActivity.onCreate (Cocos2dxactivity.java : 128)
05-05 19:08:32.148:e/androidruntime (7822): at Org.cocos2dx.lua.AppActivity.onCreate (appactivity.java:90)
05-05 19:08:32.148:e/androidruntime (7822): at Android.app.Activity.performCreate (activity.java:5226)
05-05 19:08:32.148:e/androidruntime (7822): at Android.app.Instrumentation.callActivityOnCreate ( instrumentation.java:1151)
05-05 19:08:32.148:e/androidruntime (7822): at Com.lbe.security.service.core.client.b.x.callactivityoncreate ( Unknown Source)
05-05 19:08:32.148:e/androidruntime (7822): at Android.app.ActivityThread.performLaunchActivity ( ACTIVITYTHREAD.JAVA:2360)
05-05 19:08:32.148:e/androidruntime (7822): at Android.app.ActivityThread.handleLaunchActivity (Activitythread.java : 2448)
05-05 19:08:32.148:e/androidruntime (7822): at android.app.activitythread.access$600 (ActivityThread.java:173)
05-05 19:08:32.148:e/androidruntime (7822): at Android.app.activitythread$h.handlemessage (ActivityThread.java:1392 )
05-05 19:08:32.148:e/androidruntime (7822): at Android.os.Handler.dispatchMessage (handler.java:107)
05-05 19:08:32.148:e/androidruntime (7822): at Android.os.Looper.loop (looper.java:194)
05-05 19:08:32.148:e/androidruntime (7822): at Android.app.ActivityThread.main (activitythread.java:5469)
05-05 19:08:32.148:e/androidruntime (7822): at Java.lang.reflect.Method.invokeNative (Native Method)
05-05 19:08:32.148:e/androidruntime (7822): at Java.lang.reflect.Method.invoke (method.java:525)
05-05 19:08:32.148:e/androidruntime (7822): at Com.android.internal.os.zygoteinit$methodandargscaller.run ( zygoteinit.java:857)
05-05 19:08:32.148:e/androidruntime (7822): at Com.android.internal.os.ZygoteInit.main (zygoteinit.java:624)
05-05 19:08:32.148:e/androidruntime (7822): at Dalvik.system.NativeStart.main (Native Method)


Application.mk added: app_platform: = ANDROID-17


4. This version of the app is configured to settle via Google Play. For more information, please visit the Help Center.


Check that the signature used for packaging and uploading Google Play backstage has been signed.


5. In-app Billing Error:purchase Signature Verification FAILED


The Base64encodedpublickey parameter in the code is incorrect, inconsistent with the Google background.



Technical Exchange QQ Group: 528655025
Alphagl
Source: http://www.cnblogs.com/alphagl/
All rights reserved, please keep the original link to reprint:)



SDK Access (2) on Android Google play payment (In-app billing) 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.