Android SDK スタートガイド

Android SDK の使用を開始する前に、前提条件を満たしていることを確認してください。

Android SDK を使用して、Google ウォレットにパスを追加できます。アプリに Google ウォレット ボタンを追加すると、ユーザーは Google ウォレットにパスを簡単に追加できるようになります。

Google ウォレット ボタンを Android アプリに追加する手順は次のとおりです。

1. パス オブジェクトを作成する

注: パス オブジェクトを作成するには、パスクラスが必要です。まだ作成していない場合は、パスクラスを作成するの手順に沿って作成してください。対応する LoyaltyObject を定義します。これには以下の必須属性が含まれます。 * classId: 前提条件で作成したパスクラスの ID。 * id: オブジェクトの一意の ID。

* state: このフィールドは、オブジェクトの表示方法を決定するために使用されます。たとえば、無効なオブジェクトは「期限切れのパス」セクションに移動されます。

これらの属性がポイントカードでどのように表されるかについて詳しくは、レイアウト テンプレートをご覧ください。

ポイントカードの定義の例を次に示します。

JSON

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

2. オブジェクトを使用して無署名の JWT を作成する

LoyaltyObject を作成したら、次のスニペットに示すように、payload.LoyaltyObjects 属性を含む無署名の JWT でこのオブジェクトをラップします。

JSON

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

3. UI に 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 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 ウォレットに追加する

LoyaltyObject を追加するには、ステップ 2 で作成した無署名の JWT を savePasses メソッドに渡します。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 になります。

[テスト用] パス

デモモードを使用している場合は、作成するすべてのパスのタイトルに「[テスト用]」というテキストが追加されます。これは、デモパスとライブパスを区別するためです。このようにデモモードのパスに追加されたテキストは、Google のチームから製品版の承認を得ると、接続済みのデバイスでユーザーがウォレット アプリを再び開いたときに表示されなくなります。

次のステップ