使用 Android SDK 核發票證

建立票證並編碼至 JWT 後,即可直接在 Android 應用程式中發出。操作步驟如下:檢查使用者裝置是否支援 Google Wallet API,並註明「新增至 Google 錢包」按鈕,然後輕觸按鈕,即可將票證儲存到 Google 錢包。

必要條件

核發票證前,請確認已完成下列事項:

1. 安裝 Google 錢包 Android SDK

如要使用 Google 錢包 Android SDK,請在應用程式層級 build.gradle 檔案的 dependencies 部分新增 com.google.android.gms:play-services-pay

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

2. 確認 Google Wallet API 適用國家/地區

儲存新物件之前,請確認 Google Wallet API 為 透過呼叫 PayClient 類別的 getPayApiAvailabilityStatus 方法,在目標裝置上提供可用版本。

首先,將成員變數新增至 活動,其中會顯示按鈕,並在活動發生時將按鈕執行個體化 已建立:

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 元素 活動結果) 和檢視模型中的操作邏輯 (例如:client 建立例項。

接著,使用 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 方法,即可新增 GenericObject。 你必須先點選「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 的值。