Google Wallet API에 대한 요청 인증

Google Wallet API에 대한 요청은 월렛 API가 애플리케이션에서 요청을 작성했음을 식별할 수 있도록 인증되어야 합니다.

시작하기 전에 Google Wallet REST APIGoogle Wallet Android SDK에 대한 사용자 인증 정보를 제대로 생성하고 등록했는지 확인하세요.

Google Wallet REST API 요청

Google Wallet REST API에 대한 요청은 액세스 토큰을 얻기 위해 Google Wallet REST API Google Cloud 서비스 계정 키를 사용하여 인증됩니다.

Google API 클라이언트 라이브러리는 인증과 API 요청을 처리합니다. 다음 예에서 사용하는 원하는 프로그래밍 언어의 라이브러리를 설치해야 합니다.

먼저 필요한 라이브러리 가져오기를 수행하고 서비스 계정 JSON의 일부 변수와 저장할 발급기관, 클래스, 순 사용자, 객체의 ID를 정의합니다.

자바

Java에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

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 Event tickets in Google Wallet. */
public class DemoEventTicket {
  /**
   * 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 DemoEventTicket() throws Exception {
    keyFilePath =
        System.getenv().getOrDefault("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/key.json");

    auth();
  }

PHP

PHP에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Client as GoogleClient;
use Google\Service\Walletobjects;
use Google\Service\Walletobjects\EventSeat;
use Google\Service\Walletobjects\LatLongPoint;
use Google\Service\Walletobjects\Barcode;
use Google\Service\Walletobjects\ImageModuleData;
use Google\Service\Walletobjects\LinksModuleData;
use Google\Service\Walletobjects\TextModuleData;
use Google\Service\Walletobjects\ImageUri;
use Google\Service\Walletobjects\Image;
use Google\Service\Walletobjects\EventTicketObject;
use Google\Service\Walletobjects\Message;
use Google\Service\Walletobjects\AddMessageRequest;
use Google\Service\Walletobjects\Uri;
use Google\Service\Walletobjects\TranslatedString;
use Google\Service\Walletobjects\LocalizedString;
use Google\Service\Walletobjects\EventTicketClass;

/** Demo class for creating and managing Event tickets in Google Wallet. */
class DemoEventTicket
{
  /**
   * 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에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

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 DemoEventTicket:
    """Demo class for creating and managing Event tickets 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#에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

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 Event tickets in Google Wallet.
/// </summary>
class DemoEventTicket
{
  /// <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 DemoEventTicket()
  {
    keyFilePath = Environment.GetEnvironmentVariable(
        "GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";

    Auth();
  }

Node.js

노드에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

const { google } = require('googleapis');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');

/**
 * Demo class for creating and managing Event tickets in Google Wallet.
 */
class DemoEventTicket {
  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의 전체 코드 샘플을 참고하세요. <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

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에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

/**
 * 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에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

/**
 * 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에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

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#에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

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

노드에서 통합을 시작하려면 전체 <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

/**
 * 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의 전체 코드 샘플을 참고하세요. <ph type="x-smartling-placeholder"></ph> 코드 샘플을 확인하세요.

// Create authenticated HTTP client using a service account file.
func (d *demoEventticket) 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 월렛 Android SDK를 사용하는 요청은 앱 서명 인증서를 사용하여 자동으로 인증됩니다. Android SDK는 서명 인증서의 SHA-1 지문을 자동으로 생성하고 이를 Google Wallet API 요청에 포함합니다.

앱 서명 인증서의 SHA-1 디지털 지문을 생성하고 등록하는 방법에 대한 자세한 내용은 Google 월렛 Android SDK에 대해 앱 승인을 참조하세요.