1. 程式人生 > >in-app-billing for google play (google應用內付費 v3)

in-app-billing for google play (google應用內付費 v3)

詳細文件參考: https://developer.android.com/google/play/billing/billing_integrate.html#billing-add-aidl

        Google的In-app Billing, V3版本的介面是google釋出的最新充值介面,支援以服務的形式非同步的與Google Play進行互動,更加安全可靠,減少交易中的不確定因素造成的損失。 但是暫時只支援 In-app Products,不支援訂閱。
       基本步驟如下:
將 IInAppBillingService.aidl檔案拷貝到src資料夾下,正常的話會在gen目錄下生成對應的.java檔案

在AndroidManifest.xml 檔案中新增如下許可權 
<uses-permission android:name="com.android.vending.BILLING" />
建立一個 ServiceConnection  並將其與  IInAppBillingService繫結。這個是最核心的功能,用於與Google Play進行通訊。詳細程式碼參考IabHelper.java 核心程式碼如下:

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);
   }
};
@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);
@Override
public void onDestroy() {
    super.onDestroy();
    if (mServiceConn != null) {
        unbindService(mServiceConn);
    }
}


一旦成功與Google Play建立連線,就可以使用上面建立的service與其進行通訊。比如獲取商品資訊,釋出購買請求等等。獲取商品資訊的程式碼示例(注意,不要在主執行緒呼叫此程式碼,涉及網路請求可能會阻塞主執行緒,應該另開一個執行緒呼叫):
ArrayList skuList = new ArrayList();
skuList.add("premiumUpgrade");
skuList.add("gas");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList(“ITEM_ID_LIST”, skuList);


Bundle skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
   ArrayList 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;
   }
}




申請購買商品:
// 購買程式碼
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
   sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(),
   1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
   Integer.valueOf(0));


// 結果返回
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();
          }
      }
   }
}


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


設定物品已消耗(預設情況下,物品一旦被購買就屬於使用者,不允許再次被購買,如果是消耗型商品,比如貨幣或者裝備,就需要向Google Play傳送資訊通知該物品已被消耗。注意,這個步驟要在真正提供商品之前進行,之後正確的獲取到返回值才提供商品給玩家。)
int response = mService.consumePurchase(3, getPackageName(), token);

Handle In-app Billing responses from Google Play.

除錯不成功報錯:Error checking for billing v3 support. (response: 3:Billing Unavailable)