인앱빌링 구현하기 ver3 - 구글번역

|

Implementing In-app Billing (IAB Version 3)

구글 플레이에 인앱 결제는 인앱 결제 요청을 전송하고 구글은 재생 사용하여 응용 프로그램 내 결제 트랜잭션을 관리하기위한 간단, 간단한 인터페이스를 제공합니다. 아래 정보는 버전 3 API를 사용하여 앱내 결제 서비스 응용 프로그램에서 호출을하는 방법의 기초를 다룹니다.

Note: 완전한 구현을 확인하고 응용 프로그램을 테스트하는 방법에 대해, 인 - 앱 판매 제품 교육 클래스를 참조하십시오.교육 과정은 당신의 연결을 설정하는 구글 플레이에서 결제 요청과 응답의 처리를 보내, 당신은 인 - 앱 결제를 할 수 있도록 배경 스레드 관리와 관련된 주요 작업을 처리 할 수있는 편리한 클래스를 포함하는 전체 샘플 앱 결제 응용 프로그램을 제공합니다 main Activity 에서 호출합니다.

당신이 시작하기 전에, 당신은 쉽게 당신이 인 - 앱 결제를 구현할 수 있도록합니다 개념에 익숙해 앱내 결제 개요를 읽을 수 있는지 확인하십시오.

 응용 프로그램에 위치한 앱 결제를 구현하려면 다음을 수행해야합니다 :

  1. 프로젝트에 앱내 결제 라이브러리를 추가합니다.
  2. 여러분의 AndroidManifest.xml 파일을 업데이트합니다.
  3. ServiceConnection를 만들고 IInAppBillingService에 바인딩합니다.
  4. 응용 프로그램 toIInAppBillingService에서 인 - 앱 결제 요청을 보낼 수 있습니다.
  5. 구글 플레이에서 인 - 앱 결제 응답을 처리합니다.

프로젝트에 AIDL 파일을 추가


IInAppBillingService.aidl은 인 - 앱 과금 버전 3 서비스에 대한 인터페이스를 정의하는 안드로이드 인터페이스 정의 언어 (AIDL) 파일입니다. 당신은 IPC 메서드 호출을 호출하여 결제 요청을 할이 인터페이스를 사용합니다.

AIDL 파일을 얻으려면 :

  1. Android SDK Manager 엽니다.
  2. SDK Manager에 expand the Extras 을 선택합니다.
  3. Google Play Billing Library 을 선택합니다..
  4. 다운로드를 완료하기 위해 패키지 설치를 클릭합니다.

IInAppBillingService.aidl 파일은 다음 경로에 설치됩니다.  <sdk>/extras/google/play_billing/.

프로젝트에 AIDL를 추가하려면 :

  1. 안드로이드 프로젝트에 IInAppBillingService.aidl 파일을 복사합니다.
    • 이클립스를 사용한다면:
      1. If you are starting from an existing Android project, open the project in Eclipse. If you are creating a new Android project from scratch, click File > New > Android Application Project, then follow the instructions in the New Android Application wizard to create a new project in your workspace.
      2. In the /src directory, click File > New > Package, then create a package namedcom.android.vending.billing.
      3. Copy the IInAppBillingService.aidl file from <sdk>/extras/google/play_billing/ and paste it into the src/com.android.vending.billing/ folder in your workspace.
    • 이클립스가 아닌 다른 환경을 사용한다면: Create the following directory/src/com/android/vending/billing and copy the IInAppBillingService.aidl file into this directory. Put the AIDL file into your project and use the Ant tool to build your project so that theIInAppBillingService.java file gets generated.
  2. 응용 프로그램을 빌드합니다. 당신은 당신의 프로젝트의 / gendirectory에 IInAppBillingService.java라는 생성 된 파일을 볼 수 있습니다.

Updating Your Application's Manifest


인앱 결제는 구글이 응용 프로그램과 구글 플레이 서버 사이의 모든 통신을 처리하는 응용 프로그램을 재생에 의존합니다.구글 재생 응용 프로그램을 사용하려면 응용 프로그램이 적절한 권한을 요청해야합니다. 당신은 당신의 AndroidManifest.xml 파일에 com.android.vending.BILLING 권한을 추가하여이 작업을 수행 할 수 있습니다. 응용 프로그램이 앱내 결제 권한이 있지만, 결제 요청을 보내려고 시도를 선언하지 않는 경우, 구글의 플레이는 요청을 거부하고 오류로 응답합니다.

To give your app the necessary permission, add this line in your Android.xml manifest file:

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

Creating a ServiceConnection


응용 프로그램은 응용 프로그램과 구글 플레이 사이의 메시징을 촉진하기 ServiceConnection이 있어야합니다. 최소한 응용 프로그램은 다음을 수행해야합니다 :

  • IInAppBillingService에 바인딩합니다.
  • 구글 응용 프로그램을 재생하려면 (IPC 메서드 호출 등)의 결제 요청을 보낼 수 있습니다..
  • 각 대금 청구 요청과 함께 반환되는 동기 응답 메시지를 처리 할 수 ​​있습니다.

Binding to IInAppBillingService

구글 플레이에 앱내 결제 서비스와의 연결을 설정하려면, IInAppBillingService에 활동을 결합하는 ServiceConnection를 구현합니다.연결이 설정된 후 IInAppBillingService 인스턴스에 대한 참조를 얻을 수있는 onServiceDisconnected 및 onServiceConnected 방법을 재정의합니다. 

IInAppBillingService mService;

ServiceConnection mServiceConn = new ServiceConnection() {
   
@Override
   
public void onServiceDisconnected(ComponentName name) {
       mService
= null;
   
}

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

귀하의 활동의에서 onCreate 메서드에서 bindService 메서드를 호출하여 바인딩을 수행합니다.앱내 결제 서비스 및 사용자가 만든 ServiceConnection의 인스턴스를 참조하는 방법 anIntent을 전달합니다.

@Override
public void onCreate(Bundle savedInstanceState) {    
   
super.onCreate(savedInstanceState);
    setContentView
(R.layout.activity_main);        
    bindService
(new
       
Intent("com.android.vending.billing.InAppBillingService.BIND"),
                mServiceConn
, Context.BIND_AUTO_CREATE);

이제 구글 플레이 서비스와 통신하는 mService 참조를 사용할 수 있습니다. 위 해당 함수 같은 경우

구글 샘플 ver3 IAPHelper 클래스에 정의 되있음.


Important: 당신이 당신의 활동을 완료하면 앱내 결제 서비스에서 바인딩을 해제해야합니다. 당신이 바인딩을 해제하지 않을 경우, 오픈 서비스 연결 장치의 성능이 저하 될 수 있습니다. 이 예제에서는 활동의들의 OnDestroy 메서드를 재정 의하여 mServiceConn라는 앱내 결제에 대한 서비스 연결에 바인딩 해제 작업을 수행하는 방법을 보여줍니다.

@Override
public void onDestroy() {
   
super.onDestroy();
   
if (mService != null) {
        unbindService
(mServiceConn);
   
}  
}

IInAppBillingService에 결합 서비스 연결의 전체 구현을 위해, 인 - 앱 판매 제품 교육 클래스 및 관련 샘플을 참조하십시오.

Making In-app Billing Requests


응용 프로그램이 구글 플레이에 연결 한 후에는 응용 프로그램 내 제품의 구매 요청을 시작할 수 있습니다. 구글 플레이는 사용자가 자신의 지불 방법을 입력 할 수있는 체크 아웃 인터페이스를 제공하여 응용 프로그램이 직접 지불 트랜잭션을 처리 할 필요가 없습니다.항목이 구입되면, 구글의 플레이는 사용자가 해당 항목의 소유권을 가지고 있으며, 그것이 소비 될 때까지 동일한 제품 ID와 다른 아이템을 구입하는 사용자를 방지 함을 인식합니다. 당신은 항목이 응용 프로그램에서 소비되는 방법을 제어하고, 구글은 다시 구입을위한 항목을 사용할 수 있도록 재생 알릴 수 있습니다. 또한 구글은 사용자가 빠르고 만들어진 구매 목록을 검색 재생 조회 할 수 있습니다. 당신은 당신의 사용자가 응용 프로그램을 시작할 때 사용자의 구매를 복원하려는 경우에 유용합니다.

Querying for Items Available for Purchase

응용 프로그램에서, 당신은 앱내 결제 버전 3 API를 사용하여 Google 플레이에서 항목 상세 정보를 조회 할 수 있습니다. 먼저 각 문자열이 살 수있는 항목에 대한 제품 ID입니다 키 "ITEM_ID_LIST"와 제품 ID의 문자열 ArrayList에 포함 된 번들을 작성, 인 - 앱 결제 서비스에 대한 요청을 전달합니다.

ArrayList<String> skuList = new ArrayList<String> ();
skuList
.add("premiumUpgrade");
skuList
.add("gas");
Bundle querySkus = new Bundle();
querySkus
.putStringArrayList(“ITEM_ID_LIST”, skuList);

구글 플레이에서이 정보를 검색 앱내 결제 버전 3 API에 getSkuDetails의 메서드를 호출하는 방법에게 인 - 앱 결제 API 버전 ( "3")를 전달하려면, 당신의 전화 응용 프로그램, 구입 형태의 패키지 이름 ( "inapp"), 당신이 만든 번들.

Bundle skuDetails = mService.getSkuDetails(3, 
   getPackageName
(), "inapp", querySkus);

만약 결과가 성공하면 리턴해준다. BILLING_RESPONSE_RESULT_OK (0) 값을.

Warning: 주 스레드에 getSkuDetails 메서드를 호출하지 마십시오. 이 메서드를 호출하면 주 스레드를 차단할 수있는 네트워크 요청을 트리거합니다. 대신, 별도의 스레드를 만들고 해당 스레드 내부에서 getSkuDetails 메서드를 호출합니다.

구글 플레이에서 가능한 모든 응답 코드를 참조하십시오 인 - 앱 결제 참조 (영문)를 참조하십시오. 

조회 결과가 키 DETAILS_LIST의 String ArrayList에 저장됩니다.구매 정보는 JSON 형식의 문자열에 저장됩니다. 반환되는 제품 상세 정보의 종류를 확인하려면, 앱 결제 참조를 참조하십시오. 

이 예에서 skuDetails 번들에서 - 응용 프로그램 항목에 대한 가격을 검색하는 이전의 코드에서 반환.

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");
     
if (sku.equals("premiumUpgrade")) mPremiumUpgradePrice = price;
     
else if (sku.equals("gas")) mGasPrice = price;
   
}
}

Purchasing an Item

앱에서 구매 요청을 시작하려면 앱내 결제 서비스에 getBuyIntent 메서드를 호출합니다. 메서드에 전달하는 인 - 앱 결제 API 버전 ( "3"), 사용자 통화 앱, 구매하는 품목에 대한 제품 ID의 패키지 이름, 구입 형태 ( "inapp"또는 "서브") 및 developerPayload 문자열입니다.developerPayload 문자열은 사용자가 구글의 구매 정보와 함께 다시 보낼 플레이 할 추가 인수를 지정하는 데 사용됩니다.

Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
   sku
, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");

요청이 성공하면, 반환 된 번들은 당신이 구입 흐름을 시작하는 데 사용할 수있는 BILLING_RESPONSE_RESULT_OK (0) 및 aPendingIntent의 응답 코드가 있습니다. 구글 플레이에서 가능한 모든 응답 코드를 참조하십시오 인 - 앱 결제 참조 (영문)를 참조하십시오. 다음으로, 키 BUY_INTENT와 응답 번들에서 PendingIntent의 압축을 풉니 다.

PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");

구매 거래를 완료하려면 startIntentSenderForResult 메서드를 호출하고 사용자가 만든 PendingIntentthat를 사용합니다. 이 예에서, 요청 코드 (1001)의 임의의 값을 사용하고있다.

startIntentSenderForResult(pendingIntent.getIntentSender(),
   
1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
   
Integer.valueOf(0));

구글 재생 응용 프로그램의는 onActivityResult 메서드로 PendingIntent에 대한 응답을 보냅니다. TheonActivityResult 방법은 Activity.RESULT_OK (1) 또는 Activity.RESULT_CANCELED의 결과 코드를가집니다 (0). 응답 의도에 반환되는 주문 정보의 종류를 확인하려면, 인 - 앱 결제 참조를 참조하십시오. 

주문에 대한 구매 데이터는 예를 들어, 응답 의도에 INAPP_PURCHASE_DATA 키에 매핑 된 JSON 형식의 문자열입니다 :

'{ 
   "orderId":"12999763169054705758.1371079406387615",
   "packageName":"com.example.app",
   "productId":"exampleSku",
   "purchaseTime":1345678900000,
   "purchaseState":0,
   "developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
   "purchaseToken":"rojeslcdyyiapnqcynkjyyjh"
 }'

앞의 예에서 계속, 당신은 응답 의도에서 응답 코드, 구매 데이터 및 서명을 얻을..

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   
if (requestCode == 1001) {          
     
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
     
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
     
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
       
     
if (resultCode == RESULT_OK) {
         
try {
           
JSONObject jo = new JSONObject(purchaseData);
           
String sku = jo.getString("productId");
            alert
("You have bought the " + sku + ". Excellent choice,
               adventurer!"
);
         
}
         
catch (JSONException e) {
             alert
("Failed to parse purchase data.");
             e
.printStackTrace();
         
}
     
}
   
}
}

Security Recommendation: When you send a purchase request, create a String token that uniquely identifies this purchase request and include this token in the developerPayload.You can use a randomly generated string as the token. When you receive the purchase response from Google Play, make sure to check the returned data signature, the orderId, and the developerPayload String. For added security, you should perform the checking on your own secure server. Make sure to verify that the orderId is a unique value that you have not previously processed, and the developerPayload String matches the token that you sent previously with the purchase request.

Querying for Purchased Items

To retrieve information about purchases made by a user from your app, call the getPurchases method on the In-app Billing Version 3 service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, and the purchase type (“inapp” or "subs").

Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);

The Google Play service returns only the purchases made by the user account that is currently logged in to the device. If the request is successful, the returned Bundle has a response code of 0. The response Bundle also contains a list of the product IDs, a list of the order details for each purchase, and the signatures for each purchase.

To improve performance, the In-app Billing service returns only up to 700 products that are owned by the user when getPurchase is first called. If the user owns a large number of products, Google Play includes a String token mapped to the key INAPP_CONTINUATION_TOKEN in the response Bundle to indicate that more products can be retrieved. Your application can then make a subsequent getPurchases call, and pass in this token as an argument. Google Play continues to return a continuation token in the response Bundle until all products that are owned by the user has been sent to your app.

For more information about the data returned by getPurchases, see In-app Billing Reference. The following example shows how you can retrieve this data from the response.

int response = ownedItems.getInt("RESPONSE_CODE");
if (response == 0) {
   
ArrayList<String> ownedSkus =
      ownedItems
.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
   
ArrayList<String>  purchaseDataList =
      ownedItems
.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
   
ArrayList<String>  signatureList =
      ownedItems
.getStringArrayList("INAPP_DATA_SIGNATURE");
   
String continuationToken =
      ownedItems
.getString("INAPP_CONTINUATION_TOKEN");
   
   
for (int i = 0; i < purchaseDataList.size(); ++i) {
     
String purchaseData = purchaseDataList.get(i);
     
String signature = signatureList.get(i);
     
String sku = ownedSkus.get(i);
 
     
// do something with this purchase information
     
// e.g. display the updated list of products owned by user
   
}

   
// if continuationToken != null, call getPurchases again
   
// and pass in the token to retrieve more items
}

Consuming a Purchase

You can use the In-app Billing Version 3 API to track the ownership of purchased in-app products in Google Play. Once an in-app product is purchased, it is considered to be "owned" and cannot be purchased from Google Play. You must send a consumption request for the in-app product before Google Play makes it available for purchase again.

Important: Managed in-app products are consumable, but subscriptions are not.

How you use the consumption mechanism in your app is up to you. Typically, you would implement consumption for in-app products with temporary benefits that users may want to purchase multiple times (for example, in-game currency or equipment). You would typically not want to implement consumption for in-app products that are purchased once and provide a permanent effect (for example, a premium upgrade).

To record a purchase consumption, send the consumePurchase method to the In-app Billing service and pass in the purchaseToken String value that identifies the purchase to be removed. The purchaseToken is part of the data returned in the INAPP_PURCHASE_DATA String by the Google Play service following a successful purchase request. In this example, you are recording the consumption of a product that is identified with the purchaseToken in thetoken variable.

int response = mService.consumePurchase(3, getPackageName(), token);

Warning: Do not call the consumePurchase method on the main thread. Calling this method triggers a network request which could block your main thread. Instead, create a separate thread and call the consumePurchasemethod from inside that thread.

It's your responsibility to control and track how the in-app product is provisioned to the user. For example, if the user purchased in-game currency, you should update the player's inventory with the amount of currency purchased.

Security Recommendation: You must send a consumption request before provisioning the benefit of the consumable in-app purchase to the user. Make sure that you have received a successful consumption response from Google Play before you provision the item.

Implementing Subscriptions

Launching a purchase flow for a subscription is similar to launching the purchase flow for a product, with the exception that the product type must be set to "subs". The purchase result is delivered to your Activity'sonActivityResult method, exactly as in the case of in-app products.

Bundle bundle = mService.getBuyIntent(3, "com.example.myapp",
   MY_SKU
, "subs", developerPayload);

PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT);
if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) {
   
// Start purchase flow (this brings up the Google Play UI).
   
// Result will be delivered through onActivityResult().
   startIntentSenderForResult
(pendingIntent, RC_BUY, new Intent(),
       
Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
}

To query for active subscriptions, use the getPurchases method, again with the product type parameter set to "subs".

Bundle activeSubs = mService.getPurchases(3, "com.example.myapp",
                   
"subs", continueToken);

The call returns a Bundle with all the active subscriptions owned by the user. Once a subscription expires without renewal, it will no longer appear in the returned Bundle.

Securing Your Application


To help ensure the integrity of the transaction information that is sent to your application, Google Play signs the JSON string that contains the response data for a purchase order. Google Play uses the private key that is associated with your application in the Developer Console to create this signature. The Developer Console generates an RSA key pair for each application.

Note:To find the public key portion of this key pair, open your application's details in the Developer Console, then click on Services & APIs, and look at the field titled Your License Key for This Application.

The Base64-encoded RSA public key generated by Google Play is in binary encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public key that is used with Google Play licensing.

When your application receives this signed response you can use the public key portion of your RSA key pair to verify the signature. By performing signature verification you can detect responses that have been tampered with or that have been spoofed. You can perform this signature verification step in your application; however, if your application connects to a secure remote server then we recommend that you perform the signature verification on that server.

For more information about best practices for security and design, see Security and Design.


Trackback 0 And Comment 0