创建卡券并将其编码为 JWT 后,您就可以在 Android 应用中发放该卡券了。为此,您需要检查用户的设备上是否提供 Google Wallet API,向用户显示“添加到 Google 钱包”按钮,然后在用户点按该按钮后将卡券保存到其 Google 钱包。
前提条件
在尝试签发卡券之前,请务必完成以下操作:
1. 安装 Google Wallet Android SDK
如需使用 Google Wallet Android SDK,请将 com.google.android.gms:play-services-pay 添加到应用级 build.gradle 文件的 dependencies 部分:
implementation "com.google.android.gms:play-services-pay:16.5.0"
2. 检查 Google Wallet API 是否可用
在保存新对象之前,请通过调用 PayClient 类中的 getPayApiAvailabilityStatus 方法,确保目标设备上可以使用 Google Wallet API。
首先,向您将显示按钮的 activity 添加一个成员变量,并在创建该 activity 时实例化该变量:
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 模式,请在 activity 或 fragment 中放置与界面相关的业务逻辑(例如界面元素、activity 结果),并在视图模型中放置操作逻辑(例如客户端实例化、网络调用触发器)。
接下来,使用 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 导入矢量资源。在向导中选择“Local file”,并添加名称(例如: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 钱包
通过将未签名的 JWT 传递给 savePasses 方法,可以添加 FlightObject。您可以在点击 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。
 
    
