Android SDK 相關問題

建立票證並以 JWT 進行編碼後,就可以準備在 Android 應用程式中核發票證。方法是檢查 Google Wallet API 是否可在使用者的裝置上播放,並掛上 [新增至 Google 錢包] 按鈕,然後在使用者輕觸按鈕後將票證儲存至他們的 Google 錢包。

必要條件

核發票證前,請確認您已完成下列步驟:

1. 安裝 Google 錢包 Android SDK

如要使用 Google 錢包 Android SDK,請將 com.google.android.gms:play-services-pay 加入應用程式層級 build.gradle 檔案的 dependencies 區段:

  implementation "com.google.android.gms:play-services-pay:16.4.0"

2. 檢查 Google Wallet API 是否可用

儲存新物件前,請在 PayClient 類別呼叫 getPayApiAvailabilityStatus 方法,確保目標裝置提供 Google Wallet API。

請先在活動中新增成員變數,這樣活動建立時才會顯示按鈕,並將該變數例項化:

Kotlin

import com.google.android.gms.pay.PayClient

private lateinit var walletClient: PayClient

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)

  walletClient = Pay.getClient(this)

  // Additional logic in your onCreate method
}

Java

import com.google.android.gms.pay.PayClient;

private final PayClient walletClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  walletClient = Pay.getClient(application);

  // Additional logic in your onCreate method
}

如果您使用其他設計模式,建議您適當加入特定領域的商業邏輯。舉例來說,如果您使用的是 MVVM 模式,請將 UI 相關商業邏輯放入活動或片段 (例如:檢視模型中的 UI 元素、活動結果) 和作業邏輯 (例如用戶端執行個體化、網路呼叫觸發條件)。

接下來,請使用 PayClient 檢查 API 是否可用:

Kotlin

import com.google.android.gms.pay.PayApiAvailabilityStatus

private fun fetchCanUseGoogleWalletApi() {
  walletClient
    .getPayApiAvailabilityStatus(PayClient.RequestType.SAVE_PASSES)
    .addOnSuccessListener { status ->
      if (status == PayApiAvailabilityStatus.AVAILABLE) {
        // The API is available, show the button in your UI
      } else {
        // The user or device is not eligible for using the Pay API
      }
    }
    .addOnFailureListener {
      // Hide the button and optionally show an error message
    }
}

Java

import com.google.android.gms.pay.PayApiAvailabilityStatus;

private void fetchCanAddPassesToGoogleWallet() {
  walletClient
    .getPayApiAvailabilityStatus(PayClient.RequestType.SAVE_PASSES)
    .addOnSuccessListener(status -> {
      if (status == PayApiAvailabilityStatus.AVAILABLE) {
        // The API is available, show the button in your UI
      } else {
        // The user or device is not eligible for using the Pay API
      };
    })
    .addOnFailureListener(exception -> {
      // Google Play Services is too old, or API availability not verified
      // Hide the button and optionally show an error message
    });
}

最後,當您需要判斷 API 的可用性時,請呼叫您在應用程式中定義的方法。

處理 API 無法使用時的處理方式

無法使用此 API 的可能原因包括 Android 或 Google Play 服務版本過舊,或使用者所在的國家/地區無法使用 Google 錢包。

如果 API 無法使用,請考慮隱藏按鈕,並改回不同的整合方式 (例如使用 JWT 連結)。請注意,使用者日後可能符合使用這個 API 的資格。

3. 新增「新增至 Google 錢包」按鈕

Google 錢包提供熟悉的按鈕,可用於觸發應用程式中的「新增至 Google 錢包」流程。如需按鈕的向量素材資源,請參閱按鈕指南

您可以在 Android Studio 的 File > New > Vector Asset 中匯入向量素材資源。在精靈中選取「本機檔案」,並新增名稱 (例如:add_to_google_wallet_button.xml) 並在本機磁碟中找到要匯入的檔案。

  • 「新增至 Google 錢包」按鈕
  • 「新增至 Google 錢包」按鈕已壓縮

現在,您可以使用匯入的可繪項目,將按鈕新增至使用者介面:

    <ImageButton
        android:id="@+id/addToGoogleWalletButton"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:minWidth="200dp"
        android:clickable="true"
        android:src="@drawable/add_to_google_wallet_button" />

按鈕的 layout_height 為 48 dp,寬度不得小於 200 dp。

4. 將票證新增至使用者的 Google 錢包

您可以將未簽署的 JWT 傳送至 savePasses 方法,藉此新增 GiftCardObject。您只要按一下「Google 錢包」按鈕,即可開始新增作業。

Kotlin

import android.os.Bundle
import android.view.View
import com.google.android.gms.samples.wallet.databinding.ActivityCheckoutBinding

private val addToGoogleWalletRequestCode = 1000

private lateinit var layout: ActivityCheckoutBinding
private lateinit var addToGoogleWalletButton: View

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)

  // Use view binding to access the UI elements
  layout = ActivityCheckoutBinding.inflate(layoutInflater)
  setContentView(layout.root)

  addToGoogleWalletButton = layout.addToGoogleWalletButton
  addToGoogleWalletButton.setOnClickListener {
    walletClient.savePasses(newObjectJson, this, addToGoogleWalletRequestCode)
  }

  // Additional logic in your onCreate method
}

Java

import android.os.Bundle;
import android.view.View;
import com.google.android.gms.samples.wallet.databinding.ActivityCheckoutBinding;

private static final int ADD_TO_GOOGLE_WALLET_REQUEST_CODE = 999;

private ActivityCheckoutBinding layout:
private View addToGoogleWalletButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // Use view binding to access the UI elements
  layout = ActivityCheckoutBinding.inflate(getLayoutInflater());
  setContentView(layout.getRoot());

  addToGoogleWalletButton = layout.addToGoogleWalletButton;
  addToGoogleWalletButton.setOnClickListener(v -> {
    walletClient.savePasses(newObjectJson, this, ADD_TO_GOOGLE_WALLET_REQUEST_CODE);
  });

  // Additional logic in your onCreate method
}

結果處理

savePasses 方法會在儲存流程完成後觸發儲存流程,並叫用 onActivityResult 方法。onActivityResult 的實作應與以下所示類似:

Kotlin

import android.content.Intent

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  super.onActivityResult(requestCode, resultCode, data)

  if (requestCode == addToGoogleWalletRequestCode) {
    when (resultCode) {
      RESULT_OK -> {
        // Pass saved successfully
      }

      RESULT_CANCELED -> {
        // Save operation canceled
      }

      PayClient.SavePassesResult.SAVE_ERROR -> data?.let { intentData ->
        val errorMessage = intentData.getStringExtra(PayClient.EXTRA_API_ERROR_MESSAGE)
        // Handle error
      }

      else -> {
          // Handle unexpected (non-API) exception
      }
    }
  }
}

Java

import android.content.Intent;

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == ADD_TO_GOOGLE_WALLET_REQUEST_CODE) {
    switch (resultCode) {
      case RESULT_OK: {
        // Pass saved successfully
        break;
      }

      case RESULT_CANCELED: {
        // Save operation canceled
        break;
      }

      case PayClient.SavePassesResult.SAVE_ERROR: {
        if (data != null) {
          String apiErrorMessage = data.getStringExtra(PayClient.EXTRA_API_ERROR_MESSAGE);
          // Handle error
        }
        break;
      }

      default: {
        // Handle unexpected (non-API) exception
      }
    }
  }
}

成功新增票證後,resultCode 會包含 Activity.RESULT_OK 的值。