開始使用 Android SDK

開始使用 Android SDK 之前,請確認您已完成必要條件

Android SDK 可讓您在 Google 錢包中新增票證。在應用程式中新增「Google 錢包」按鈕後,使用者不但可以輕鬆又安全地地將票證新增至 Google 錢包,

按照步驟將 Google 錢包按鈕新增至 Android 應用程式:

1. 建立票證物件

注意:必須有票證類別才能建立票證物件。如果您尚未建立票證,請按照建立票證類別的操作說明操作。 定義對應的 EventObject,包括下列必要屬性:

  • classId:在先決條件中建立的票證類別 ID。
  • id:物件的專屬 ID。

  • state:這個欄位的用途是決定物件的顯示方式。舉例來說,系統會將無效的物件移至「過期的票證」部分。

如要進一步瞭解如何在活動票券中代表這些屬性,請參閱版面配置範本

以下為範例活動票券的定義:

JSON

      
{
  "id": "ISSUER_ID.OBJECT_ID",
  "classId": "ISSUER_ID.CLASS_ID",
  "state": "ACTIVE"
}
      
    

2. 使用物件建立未簽署的 JWT

建立 EventObject 後,請使用 payload.EventObjects 屬性使用未簽署的 JWT 進行包裝,如以下程式碼片段所示:

JSON

{
  "iss": "OWNER_EMAIL_ADDRESS",
  "aud": "google",
  "typ": "savetowallet",
  "iat": "UNIX_TIME",
  "origins": [],
  "payload": {
      "eventticketObjects": [ NEW_OBJECT ]
  }
}

3. 在使用者介面中加入 Google 錢包按鈕

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

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

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

<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 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
}

現在,使用用戶端查看該 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 是否可用時,呼叫應用程式中定義的方法。

5. 將物件新增至 Google 錢包

步驟 2 將未簽署的 JWT 傳遞至 savePasses 方法,即可新增 EventObject。按一下 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 的值。

[TEST ONLY] 次傳球

如果您一直處於展示模式,您建立的所有票證的名稱都會含有「[TEST ONLY]」字樣。這有助於區分試用版票證和即時票證。我們的團隊取得正式版核准後,當使用者在已連結裝置上重新開啟錢包應用程式時,這些示範模式票證就不會再提供其他文字。

後續步驟