向 Google Wallet API 發出的要求必須經過驗證, Wallet API 才能確認該項要求確實是由您的應用程式提出。
在開始之前,請確認您已正確產生並註冊 Google Wallet REST API 和 Google Wallet Android SDK 的憑證。
Google Wallet REST API 要求
向 Google Wallet REST API 發出的要求會使用 Google Wallet REST API Google Cloud 服務帳戶金鑰進行驗證,藉此取得存取權杖。
Google API 用戶端程式庫可處理驗證作業及提出 API 要求。請務必安裝您偏好的程式設計語言的程式庫;下列範例將使用您選擇的程式設計語言。
首先,執行必要的程式庫匯入作業,並為服務帳戶 JSON 定義一些變數,以及要儲存的核發者、類別、不重複使用者 ID 和物件 ID。
Java
如要開始在 Java 中整合,請參閱我們提供的完整 查看程式碼範例
import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.*; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.walletobjects.*; import com.google.api.services.walletobjects.model.*; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import java.io.*; import java.security.interfaces.RSAPrivateKey; import java.util.*; /** Demo class for creating and managing Generic passes in Google Wallet. */ public class DemoGeneric { /** * Path to service account key file from Google Cloud Console. Environment variable: * GOOGLE_APPLICATION_CREDENTIALS. */ public static String keyFilePath; /** Service account credentials for Google Wallet APIs. */ public static GoogleCredentials credentials; /** Google Wallet service client. */ public static Walletobjects service; public DemoGeneric() throws Exception { keyFilePath = System.getenv().getOrDefault("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/key.json"); auth(); }
PHP
如要在 PHP 中開始整合,請參閱我們提供的完整 查看程式碼範例
use Firebase\JWT\JWT; use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Client as GoogleClient; use Google\Service\Walletobjects; use Google\Service\Walletobjects\GenericObject; use Google\Service\Walletobjects\GenericClass; use Google\Service\Walletobjects\Barcode; use Google\Service\Walletobjects\ImageModuleData; use Google\Service\Walletobjects\LinksModuleData; use Google\Service\Walletobjects\TextModuleData; use Google\Service\Walletobjects\TranslatedString; use Google\Service\Walletobjects\LocalizedString; use Google\Service\Walletobjects\ImageUri; use Google\Service\Walletobjects\Image; use Google\Service\Walletobjects\Uri; /** Demo class for creating and managing Generic passes in Google Wallet. */ class DemoGeneric { /** * The Google API Client * https://github.com/google/google-api-php-client */ public GoogleClient $client; /** * Path to service account key file from Google Cloud Console. Environment * variable: GOOGLE_APPLICATION_CREDENTIALS. */ public string $keyFilePath; /** * Service account credentials for Google Wallet APIs. */ public ServiceAccountCredentials $credentials; /** * Google Wallet service client. */ public Walletobjects $service; public function __construct() { $this->keyFilePath = getenv('GOOGLE_APPLICATION_CREDENTIALS') ?: '/path/to/key.json'; $this->auth(); }
Python
如要開始以 Python 進行整合,請參閱我們提供的完整 查看程式碼範例
import json import os import uuid from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google.oauth2.service_account import Credentials from google.auth import jwt, crypt class DemoGeneric: """Demo class for creating and managing Generic passes in Google Wallet. Attributes: key_file_path: Path to service account key file from Google Cloud Console. Environment variable: GOOGLE_APPLICATION_CREDENTIALS. base_url: Base URL for Google Wallet API requests. """ def __init__(self): self.key_file_path = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', '/path/to/key.json') # Set up authenticated client self.auth()
C#
如要開始在 C# 中整合,請參閱我們提供的完整 查看程式碼範例
using System.IdentityModel.Tokens.Jwt; using System.Net.Http.Headers; using System.Text.RegularExpressions; using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using Google.Apis.Walletobjects.v1; using Google.Apis.Walletobjects.v1.Data; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Demo class for creating and managing Generic passes in Google Wallet. /// </summary> class DemoGeneric { /// <summary> /// Path to service account key file from Google Cloud Console. Environment /// variable: GOOGLE_APPLICATION_CREDENTIALS. /// </summary> public static string keyFilePath; /// <summary> /// Service account credentials for Google Wallet APIs /// </summary> public static ServiceAccountCredential credentials; /// <summary> /// Google Wallet service client /// </summary> public static WalletobjectsService service; public DemoGeneric() { keyFilePath = Environment.GetEnvironmentVariable( "GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; Auth(); }
Node.js
如要在節點環境中展開整合作業,請參閱我們提供的完整 查看程式碼範例
const { google } = require('googleapis'); const jwt = require('jsonwebtoken'); const { v4: uuidv4 } = require('uuid'); /** * Demo class for creating and managing Generic passes in Google Wallet. */ class DemoGeneric { constructor() { /** * Path to service account key file from Google Cloud Console. Environment * variable: GOOGLE_APPLICATION_CREDENTIALS. */ this.keyFilePath = process.env.GOOGLE_APPLICATION_CREDENTIALS || '/path/to/key.json'; this.auth(); }
Go
如要在 Go 中開始進行整合作業,請參閱 GitHub 上的完整程式碼範例 GitHub 上的程式碼範例。
package main import ( "bytes" "context" "encoding/json" "fmt" "github.com/golang-jwt/jwt" "github.com/google/uuid" "golang.org/x/oauth2" "golang.org/x/oauth2/google" oauthJwt "golang.org/x/oauth2/jwt" "google.golang.org/api/option" "google.golang.org/api/walletobjects/v1" "io" "log" "os" "strings" )
接著,使用其中一個架構程式庫擷取必要憑證,以呼叫 Google Wallet API。
Java
如要開始在 Java 中整合,請參閱我們提供的完整 查看程式碼範例
/** * Create authenticated HTTP client using a service account file. * */ public void auth() throws Exception { credentials = GoogleCredentials.fromStream(new FileInputStream(keyFilePath)) .createScoped(List.of(WalletobjectsScopes.WALLET_OBJECT_ISSUER)); credentials.refresh(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Initialize Google Wallet API service service = new Walletobjects.Builder( httpTransport, GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("APPLICATION_NAME") .build(); }
PHP
如要在 PHP 中開始整合,請參閱我們提供的完整 查看程式碼範例
/** * Create authenticated HTTP client using a service account file. */ public function auth() { $this->credentials = new ServiceAccountCredentials( Walletobjects::WALLET_OBJECT_ISSUER, $this->keyFilePath ); // Initialize Google Wallet API service $this->client = new GoogleClient(); $this->client->setApplicationName('APPLICATION_NAME'); $this->client->setScopes(Walletobjects::WALLET_OBJECT_ISSUER); $this->client->setAuthConfig($this->keyFilePath); $this->service = new Walletobjects($this->client); }
Python
如要開始以 Python 進行整合,請參閱我們提供的完整 查看程式碼範例
def auth(self): """Create authenticated HTTP client using a service account file.""" self.credentials = Credentials.from_service_account_file( self.key_file_path, scopes=['https://www.googleapis.com/auth/wallet_object.issuer']) self.client = build('walletobjects', 'v1', credentials=self.credentials)
C#
如要開始在 C# 中整合,請參閱我們提供的完整 查看程式碼範例
/// <summary> /// Create authenticated service client using a service account file. /// </summary> public void Auth() { credentials = (ServiceAccountCredential)GoogleCredential .FromFile(keyFilePath) .CreateScoped(new List<string> { WalletobjectsService.ScopeConstants.WalletObjectIssuer }) .UnderlyingCredential; service = new WalletobjectsService( new BaseClientService.Initializer() { HttpClientInitializer = credentials }); }
Node.js
如要在節點環境中展開整合作業,請參閱我們提供的完整 查看程式碼範例
/** * Create authenticated HTTP client using a service account file. */ auth() { const auth = new google.auth.GoogleAuth({ keyFile: this.keyFilePath, scopes: ['https://www.googleapis.com/auth/wallet_object.issuer'], }); this.credentials = require(this.keyFilePath); this.client = google.walletobjects({ version: 'v1', auth: auth, }); }
Go
如要在 Go 中開始進行整合作業,請參閱 GitHub 上的完整程式碼範例 GitHub 上的程式碼範例。
// Create authenticated HTTP client using a service account file. func (d *demoGeneric) auth() { credentialsFile := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") b, _ := os.ReadFile(credentialsFile) credentials, err := google.JWTConfigFromJSON(b, walletobjects.WalletObjectIssuerScope) if err != nil { fmt.Println(err) log.Fatalf("Unable to load credentials: %v", err) } d.credentials = credentials d.service, _ = walletobjects.NewService(context.Background(), option.WithCredentialsFile(credentialsFile)) }
Google 錢包 Android SDK 要求
使用 Google Wallet Android SDK 的要求會自動使用您的應用程式簽署憑證進行驗證。Android SDK 會自動建立您的簽署憑證 SHA-1 指紋,並在對 Google Wallet API 提出的要求中加入該指紋。
如要進一步瞭解如何產生及註冊應用程式簽署憑證的 SHA-1 指紋,請參閱「為應用程式使用 Google Wallet Android SDK 授權」一文。