Premiers pas avec l'API Web

Restez organisé à l'aide des collections Enregistrez et classez les contenus selon vos préférences.

Avant de commencer à utiliser l'API Web, assurez-vous d'avoir rempli les conditions préalables. Pour continuer à utiliser l'API Web, vous devez disposer d'un compte de service et d'une clé de compte de service, et vous devez autoriser ce compte de service à appeler l'API Google Wallet.

Téléchargez l'exemple de code sur GitHub pour exécuter les extraits de code référencés dans les étapes ci-dessous.

Authentification et autorisation

Les requêtes adressées à l'API Google Wallet doivent être authentifiées pour que l'API puisse identifier que la requête est effectuée par votre application. Pour ce faire, utilisez la clé du compte de service afin d'obtenir un jeton d'accès.

Commencez par effectuer les importations de bibliothèques nécessaires et définissez certaines variables pour le JSON du compte de service et les ID de l'émetteur, de la classe, de l'utilisateur unique et de l'objet qui seront enregistrés.

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.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.common.collect.Lists;

import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;

// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;

public class DemoFlight {
  public static void main(String[] args) throws Exception {
    /*
     * keyFilePath - Path to service account key file from Google Cloud Console
     * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
     */
    final String keyFilePath = System.getenv().getOrDefault(
        "GOOGLE_APPLICATION_CREDENTIALS",
        "/path/to/key.json");

    /*
     * issuerId - The issuer ID being updated in this request
     * - Environment variable: WALLET_ISSUER_ID
     */
    String issuerId = System.getenv().getOrDefault(
        "WALLET_ISSUER_ID",
        "issuer-id");

    /*
     * classId - Developer-defined ID for the wallet class
     * - Environment variable: WALLET_CLASS_ID
     */
    String classId = System.getenv().getOrDefault(
        "WALLET_CLASS_ID",
        "test-flight-class-id");

    /*
     * userId - Developer-defined ID for the user, such as an email address
     * - Environment variable: WALLET_USER_ID
     */
    String userId = System.getenv().getOrDefault(
        "WALLET_USER_ID",
        "user-id");

    /*
     * objectId - ID for the wallet object
     * - Format: `issuerId.identifier`
     * - Should only include alphanumeric characters, '.', '_', or '-'
     * - `identifier` is developer-defined and unique to the user
     */
    String objectId = String.format("%s.%s-%s",
        issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);

PHP

use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;


/*
 * keyFilePath - Path to service account key file from Google Cloud Console
 *             - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
 */
$keyFilePath = getenv('GOOGLE_APPLICATION_CREDENTIALS') ?: '/path/to/key.json';

/*
 * issuerId - The issuer ID being updated in this request
 *          - Environment variable: WALLET_ISSUER_ID
 */
$issuerId = getenv('WALLET_ISSUER_ID') ?: 'issuer-id';

/*
 * classId - Developer-defined ID for the wallet class
 *         - Environment variable: WALLET_CLASS_ID
 */
$classId = getenv('WALLET_CLASS_ID') ?: 'test-flight-class-id';

/*
 * userId - Developer-defined ID for the user, such as an email address
 *        - Environment variable: WALLET_USER_ID
 */
$userId = getenv('WALLET_USER_ID') ?: 'user-id';

/*
 * objectId - ID for the wallet object
 *          - Format: `issuerId.identifier`
 *          - Should only include alphanumeric characters, '.', '_', or '-'
 *          - `identifier` is developer-defined and unique to the user
 */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";

Python

import json
import os
import re
import uuid

from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
from google.auth import jwt, crypt

# KEY_FILE_PATH - Path to service account key file from Google Cloud Console
#               - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
KEY_FILE_PATH = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS",
                               "/path/to/key.json")

# ISSUER_ID - The issuer ID being updated in this request
#           - Environment variable: WALLET_ISSUER_ID
ISSUER_ID = os.environ.get("WALLET_ISSUER_ID", "issuer-id")

# CLASS_ID - Developer-defined ID for the wallet class
#         - Environment variable: WALLET_CLASS_ID
CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-flight-class-id")

# USER_ID - Developer-defined ID for the user, such as an email address
#        - Environment variable: WALLET_USER_ID
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")

# objectId - ID for the wallet object
#          - Format: `issuerId.identifier`
#          - Should only include alphanumeric characters, '.', '_', or '-'
#          - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)

C#

using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using Google.Apis.Auth.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;


class DemoFlight
{
  /*
  * keyFilePath - Path to service account key file from Google Cloud Console
  *             - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
  */
  static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";

  /*
  * issuerId - The issuer ID being used in this request
  *          - Environment variable: WALLET_ISSUER_ID
  */
  static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";

  /*
  * classId - Developer-defined ID for the wallet class
  *         - Environment variable: WALLET_CLASS_ID
  */
  static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-flight-class-id";

  /*
  * userId - Developer-defined ID for the user, such as an email address
  *        - Environment variable: WALLET_USER_ID
  */
  static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";

  /*
  * objectId - ID for the wallet object
  *          - Format: `issuerId.identifier`
  *          - Should only include alphanumeric characters, '.', '_', or '-'
  *          - `identifier` is developer-defined and unique to the user
  */
  static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";

Node.js

const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');

/*
 * keyFilePath - Path to service account key file from Google Cloud Console
 *             - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
 */
const keyFilePath = process.env.GOOGLE_APPLICATION_CREDENTIALS || '/path/to/key.json';

/*
 * issuerId - The issuer ID being updated in this request
 *          - Environment variable: WALLET_ISSUER_ID
 */
const issuerId = process.env.WALLET_ISSUER_ID || 'issuer-id';

/*
 * classId - Developer-defined ID for the wallet class
 *         - Environment variable: WALLET_CLASS_ID
 */
const classId = process.env.WALLET_CLASS_ID || 'test-flight-class-id';

/*
 * userId - Developer-defined ID for the user, such as an email address
 *        - Environment variable: WALLET_USER_ID
 */
let userId = process.env.WALLET_USER_ID || 'user-id';

/*
 * objectId - ID for the wallet object
 *          - Format: `issuerId.identifier`
 *          - Should only include alphanumeric characters, '.', '_', or '-'
 *          - `identifier` is developer-defined and unique to the user
 */
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;

Ensuite, utilisez l'une des bibliothèques du framework pour récupérer les identifiants nécessaires afin d'appeler {api_name}.

Java

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(keyFilePath))
    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/wallet_object.issuer"));
credentials.refresh();

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory httpRequestFactory = httpTransport.createRequestFactory(new HttpCredentialsAdapter(credentials));

PHP

$credentials = new ServiceAccountCredentials(
  'https://www.googleapis.com/auth/wallet_object.issuer',
  $keyFilePath
);

$middleware = new AuthTokenMiddleware($credentials);
$stack = HandlerStack::create();
$stack->push($middleware);
$httpClient = new Client([
  'handler' => $stack,
  'auth' => 'google_auth'
]);

Python

credentials = service_account.Credentials.from_service_account_file(
    KEY_FILE_PATH,
    scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])

http_client = AuthorizedSession(credentials)

C#

credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
    .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
    .UnderlyingCredential;

httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer",
    await credentials.GetAccessTokenForRequestAsync()
);

Node.js

const credentials = require(keyFilePath);

const httpClient = new GoogleAuth({
  credentials: credentials,
  scopes: 'https://www.googleapis.com/auth/wallet_object.issuer'
});

Créer un objet Passes

Un objet Passes est une instance d'une classe Passes. Pour créer un objet Passes, vous devez fournir les attributs suivants:

  • classId: id de la classe Passes
  • id: ID de carte d'embarquement unique pour un passager
  • state : active pour une nouvelle carte en cours de création.

Nous vous recommandons également d'inclure les attributs suivants:

  • passengerName : nom du passager tel qu'il apparaît sur la carte d'embarquement.
  • boardingAndSeatingInfo : informations spécifiques aux passagers concernant les places d'embarquement et les places assises (BoardingAndSeatingInfo).
  • barcode: type et valeur du code-barres (Barcode)

Reportez-vous au modèle de mise en page pour savoir comment ces attributs sont représentés dans la carte d'embarquement.

Exemple de code pour créer un objet Passes:

HTTP

POST /walletobjects/v1/flightObject HTTP/1.1
Host: walletobjects.googleapis.com
Content-Type: application/json
Authorization: Bearer <ACCESS_TOKEN>;
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

{
  "id": "issuer-id.user-id",
  "classId": "issuer-id.class-id",
  "heroImage": {
    "sourceUri": {
      "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
      "description": "Test heroImage description"
    }
  },
  "textModulesData": [
    {
      "header": "Test text module header",
      "body": "Test text module body"
    }
  ],
  "linksModuleData": {
    "uris": [
      {
        "kind": "walletobjects#uri",
        "uri": "http://maps.google.com/",
        "description": "Test link module uri description"
      },
      {
        "kind": "walletobjects#uri",
        "uri": "tel:6505555555",
        "description": "Test link module tel description"
      }
    ]
  },
  "imageModulesData": [
    {
      "mainImage": {
        "kind": "walletobjects#image",
        "sourceUri": {
          "kind": "walletobjects#uri",
          "uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
          "description": "Test image module description"
        }
      }
    }
  ],
  "barcode": {
    "kind": "walletobjects#barcode",
    "type": "qrCode",
    "value": "Test QR Code"
  },
  "state": "active",
  "passengerName": "Test passenger name",
  "reservationInfo": {
    "confirmationCode": "Test confirmation code"
  },
  "boardingAndSeatingInfo": {
    "seatNumber": "42",
    "boardingGroup": "B"
  },
  "locations": [
    {
      "kind": "walletobjects#latLongPoint",
      "latitude": 37.424015499999996,
      "longitude": -122.09259560000001
    }
  ]
}

Java

HttpRequest objectRequest;
HttpResponse objectResponse;

GenericUrl objectUrl = new GenericUrl(
    "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/" + objectId);
String objectPayload = String.format(
    "{"
  + "  \"id\": \"%s\","
  + "  \"classId\": \"%s.%s\","
  + "  \"heroImage\": {"
  + "    \"sourceUri\": {"
  + "      \"uri\": \"https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg\","
  + "      \"description\": \"Test heroImage description\""
  + "    }"
  + "  },"
  + "  \"textModulesData\": ["
  + "    {"
  + "      \"header\": \"Test text module header\","
  + "      \"body\": \"Test text module body\""
  + "    }"
  + "  ],"
  + "  \"linksModuleData\": {"
  + "    \"uris\": ["
  + "      {"
  + "        \"kind\": \"walletobjects#uri\","
  + "        \"uri\": \"http://maps.google.com/\","
  + "        \"description\": \"Test link module uri description\""
  + "      },"
  + "      {"
  + "        \"kind\": \"walletobjects#uri\","
  + "        \"uri\": \"tel:6505555555\","
  + "        \"description\": \"Test link module tel description\""
  + "      }"
  + "    ]"
  + "  },"
  + "  \"imageModulesData\": ["
  + "    {"
  + "      \"mainImage\": {"
  + "        \"kind\": \"walletobjects#image\","
  + "        \"sourceUri\": {"
  + "          \"kind\": \"walletobjects#uri\","
  + "          \"uri\": \"http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg\","
  + "          \"description\": \"Test image module description\""
  + "        }"
  + "      }"
  + "    }"
  + "  ],"
  + "  \"barcode\": {"
  + "    \"kind\": \"walletobjects#barcode\","
  + "    \"type\": \"qrCode\","
  + "    \"value\": \"Test QR Code\""
  + "  },"
  + "  \"state\": \"active\","
  + "  \"passengerName\": \"Test passenger name\","
  + "  \"reservationInfo\": {"
  + "    \"confirmationCode\": \"Test confirmation code\""
  + "  },"
  + "  \"boardingAndSeatingInfo\": {"
  + "    \"seatNumber\": \"42\","
  + "    \"boardingGroup\": \"B\""
  + "  },"
  + "  \"locations\": ["
  + "    {"
  + "      \"kind\": \"walletobjects#latLongPoint\","
  + "      \"latitude\": 37.424015499999996,"
  + "      \"longitude\": -122.09259560000001"
  + "    }"
  + "  ]"
  + "}", objectId, issuerId, classId);

try {
  // Create and send the request
  objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
  objectResponse = objectRequest.execute();

  System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
  if (ex.getStatusCode() == 404) {
    // Object does not yet exist
    // Send POST request to create it
    // Convert body to JSON
    JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
    GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
    HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);

    // Create and send the request
    objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
    objectResponse = objectRequest.execute();

    System.out.println("object POST response: " + objectResponse.parseAsString());
  } else {
    // Something else went wrong
    throw ex;
  }
}

PHP

$objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/";
$objectPayload = <<<EOD
{
  "id": "{$objectId}",
  "classId": "{$issuerId}.{$classId}",
  "heroImage": {
    "sourceUri": {
      "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
      "description": "Test heroImage description"
    }
  },
  "textModulesData": [
    {
      "header": "Test text module header",
      "body": "Test text module body"
    }
  ],
  "linksModuleData": {
    "uris": [
      {
        "kind": "walletobjects#uri",
        "uri": "http://maps.google.com/",
        "description": "Test link module uri description"
      },
      {
        "kind": "walletobjects#uri",
        "uri": "tel:6505555555",
        "description": "Test link module tel description"
      }
    ]
  },
  "imageModulesData": [
    {
      "mainImage": {
        "kind": "walletobjects#image",
        "sourceUri": {
          "kind": "walletobjects#uri",
          "uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
          "description": "Test image module description"
        }
      }
    }
  ],
  "barcode": {
    "kind": "walletobjects#barcode",
    "type": "qrCode",
    "value": "Test QR Code"
  },
  "state": "active",
  "passengerName": "Test passenger name",
  "reservationInfo": {
    "confirmationCode": "Test confirmation code"
  },
  "boardingAndSeatingInfo": {
    "seatNumber": "42",
    "boardingGroup": "B"
  },
  "locations": [
    {
      "kind": "walletobjects#latLongPoint",
      "latitude": 37.424015499999996,
      "longitude": -122.09259560000001
    }
  ]
}
EOD;

try {
  $objectResponse = $httpClient->get($objectUrl . $objectId);
} catch (ClientException $err) {
  if ($err->getResponse()->getStatusCode() == 404) {
    // Object does not yet exist
    // Send POST request to create it
    $objectResponse = $httpClient->post(
      $objectUrl,
      ['json' => json_decode($objectPayload)]
    );
  }
}

echo 'object GET or POST response: ' . $objectResponse->getBody();

Python

OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/"
object_payload = {
    "id": OBJECT_ID,
    "classId": f"{ISSUER_ID}.{CLASS_ID}",
    "heroImage": {
        "sourceUri": {
            "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
            "description": "Test heroImage description"
        }
    },
    "textModulesData": [
        {
            "header": "Test text module header",
            "body": "Test text module body"
        }
    ],
    "linksModuleData": {
        "uris": [
            {
                "kind": "walletobjects#uri",
                "uri": "http://maps.google.com/",
                "description": "Test link module uri description"
            },
            {
                "kind": "walletobjects#uri",
                "uri": "tel:6505555555",
                "description": "Test link module tel description"
            }
        ]
    },
    "imageModulesData": [
        {
            "mainImage": {
                "kind": "walletobjects#image",
                "sourceUri": {
                    "kind": "walletobjects#uri",
                    "uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
                    "description": "Test image module description"
                }
            }
        }
    ],
    "barcode": {
        "kind": "walletobjects#barcode",
        "type": "qrCode",
        "value": "Test QR Code"
    },
    "state": "active",
    "passengerName": "Test passenger name",
    "reservationInfo": {
        "confirmationCode": "Test confirmation code"
    },
    "boardingAndSeatingInfo": {
        "seatNumber": "42",
        "boardingGroup": "B"
    },
    "locations": [
        {
            "kind": "walletobjects#latLongPoint",
            "latitude": 37.424015499999996,
            "longitude": -122.09259560000001
        }
    ]
}

object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
    # Object does not yet exist
    # Send POST request to create it
    object_response = http_client.post(
        OBJECT_URL,
        json=object_payload
    )

print("object GET or POST response:", object_response.text)

C#

string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/";
var objectPayload = new
{
  id = objectId,
  classId = $"{issuerId}.{classId}",
  heroImage = new
  {
    sourceUri = new
    {
      uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
      description = "Test heroImage description"
    }
  },
  textModulesData = new object[]
  {
    new
    {
      header = "Test text module header",
      body = "Test text module body"
    }
  },
  linksModuleData = new
  {
    uris = new object[]
    {
      new
      {
        kind = "walletobjects#uri",
        uri = "http://maps.google.com/",
        description = "Test link module uri description"
      },
      new
      {
        kind = "walletobjects#uri",
        uri = "tel:6505555555",
        description = "Test link module tel description"
      }
    }
  },
  imageModulesData = new object[]
  {
    new
    {
      mainImage = new
      {
        kind = "walletobjects#image",
        sourceUri = new
        {
          kind = "walletobjects#uri",
          uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
          description = "Test image module description"
        }
      }
    }
  },
  barcode = new
  {
    kind = "walletobjects#barcode",
    type = "qrCode",
    value = "Test QR Code"
  },
  state = "active",
  passengerName = "Test passenger name",
  reservationInfo = new
  {
    confirmationCode = "Test confirmation code"
  },
  boardingAndSeatingInfo = new
  {
    seatNumber = "42",
    boardingGroup = "B"
  },
  locations = new object[]
  {
    new
    {
      kind = "walletobjects#latLongPoint",
      latitude = 37.424015499999996,
      longitude = -122.09259560000001
    }
  }
};

HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
  // Object does not yet exist
  // Send POST request to create it
  objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
  objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
  objectResponse = httpClient.Send(objectRequest);
}

string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");

Node.js

const objectUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/flightObject/';
const objectPayload = {
  "id": objectId,
  "classId": `${issuerId}.${classId}`,
  "heroImage": {
    "sourceUri": {
      "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
      "description": "Test heroImage description"
    }
  },
  "textModulesData": [
    {
      "header": "Test text module header",
      "body": "Test text module body"
    }
  ],
  "linksModuleData": {
    "uris": [
      {
        "kind": "walletobjects#uri",
        "uri": "http://maps.google.com/",
        "description": "Test link module uri description"
      },
      {
        "kind": "walletobjects#uri",
        "uri": "tel:6505555555",
        "description": "Test link module tel description"
      }
    ]
  },
  "imageModulesData": [
    {
      "mainImage": {
        "kind": "walletobjects#image",
        "sourceUri": {
          "kind": "walletobjects#uri",
          "uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
          "description": "Test image module description"
        }
      }
    }
  ],
  "barcode": {
    "kind": "walletobjects#barcode",
    "type": "qrCode",
    "value": "Test QR Code"
  },
  "state": "active",
  "passengerName": "Test passenger name",
  "reservationInfo": {
    "confirmationCode": "Test confirmation code"
  },
  "boardingAndSeatingInfo": {
    "seatNumber": "42",
    "boardingGroup": "B"
  },
  "locations": [
    {
      "kind": "walletobjects#latLongPoint",
      "latitude": 37.424015499999996,
      "longitude": -122.09259560000001
    }
  ]
};
let objectResponse;

try {
  objectResponse = await httpClient.request({
    url: objectUrl + objectId,
    method: 'GET'
  });
} catch (err) {
  if (err.response && err.response.status === 404) {
    // Object does not yet exist
    // Send POST request to create it
    objectResponse = await httpClient.request({
      url: objectUrl,
      method: 'POST',
      data: objectPayload
    });
  } else {
    objectResponse = err;
  }
}

console.log('object GET or POST response:', objectResponse);

Une fois cette étape terminée, l'objet Passes de vos passagers sera créé sur le serveur. Toutefois, à ce stade, l'objet Passes n'a pas été associé à un utilisateur Google ou à son appareil. Pour que la carte soit associée à un utilisateur Google Wallet, il doit d'abord ajouter la carte à Google Wallet.

Ajout à Google Wallet en cours

L'ajout d'une carte à Google Wallet associe l'objet Passes à un utilisateur Google et ne peut être lancé que dans le cadre d'une identité Google. Pour ce faire, redirigez l'utilisateur vers une URL "Ajouter à Google Wallet".

L'URL Add to Google Wallet est générée de manière dynamique. Elle contient les informations suivantes sur l'ID d'objet Passes créé à l'étape précédente. Ces informations sont encodées au format JSON Web Token (JWT).

Jeton Web JSON (JWT)

Le JWT contient les déclarations que vous (l'émetteur) faites sur l'objet Passes qui sera enregistré par l'utilisateur. Le jeton JWT doit être signé à l'aide de la clé private_key provenant de la clé du compte de service obtenue à l'étape Créer un compte de service. Google valide ensuite ces revendications en validant la signature JWT.

Les revendications JWT doivent avoir la structure suivante:

{
  "aud": "google",
  "origins": ["https://example.com"],
  "iss": "my-service-account@my-project-id.iam.gserviceaccount.com",
  "typ": "savetowallet",
  "payload": {
    "flightObjects": [
      {
        "id": "PASSES_OBJECT_ID_1234567890"
      }
    ]
  }
}

Créez le jeton JWT claims et obtenez la valeur token en signant les revendications avec la clé du compte de service private_key:

Java

HashMap<String, String> objectIdMap = new HashMap<String, String>();
objectIdMap.put("id", objectId);

HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put("flightObjects", new ArrayList<>(Arrays.asList(objectIdMap)));

HashMap<String, Object> claims = new HashMap<String, Object>();
claims.put("iss", ((ServiceAccountCredentials) credentials).getClientEmail());
claims.put("aud", "google");
claims.put("origins", new ArrayList<>(Arrays.asList("www.example.com")));
claims.put("typ", "savetowallet");
claims.put("payload", payload);

Algorithm algorithm = Algorithm.RSA256(
    null,
    (RSAPrivateKey) ((ServiceAccountCredentials) credentials).getPrivateKey());
String token = JWT.create()
    .withPayload(claims)
    .sign(algorithm);
String saveUrl = "https://pay.google.com/gp/v/save/" + token;

System.out.println(saveUrl);

PHP

$serviceAccount = json_decode(file_get_contents($keyFilePath), true);
$claims = [
  'iss' => $serviceAccount['client_email'],
  'aud' => 'google',
  'origins' => ['www.example.com'],
  'typ' => 'savetowallet',
  'payload' => [
    'flightObjects' => [
      ['id' => $objectId]
    ]
  ]
];

$token = JWT::encode($claims, $serviceAccount['private_key'], 'RS256');
$saveUrl = "https://pay.google.com/gp/v/save/${token}";

echo $saveUrl;

Python

claims = {
    "iss": http_client.credentials.service_account_email,
    "aud": "google",
    "origins": ["www.example.com"],
    "typ": "savetowallet",
    "payload": {
        "flightObjects": [
            {
                "id": OBJECT_ID
            }
        ]
    }
}

signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
token = jwt.encode(signer, claims).decode("utf-8")
save_url = f"https://pay.google.com/gp/v/save/{token}"

print(save_url)

C#

JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
  flightObjects = new object[]
  {
    new
    {
      id = objectId
    }
  }
});

RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";

Console.WriteLine(saveUrl);

Node.js

const claims = {
  iss: credentials.client_email,
  aud: 'google',
  origins: ['www.example.com'],
  typ: 'savetowallet',
  payload: {
    flightObjects: [{
      id: objectId
    }],
  }
};

const token = jwt.sign(claims, credentials.private_key, { algorithm: 'RS256' });
const saveUrl = `https://pay.google.com/gp/v/save/${token}`;

console.log(saveUrl);

Après avoir obtenu un jeton JWT signé, vous pouvez créer un lien d'ajout à Google Wallet à l'aide de ces informations.

Le lien "Ajouter à Google Wallet" se présente comme suit:

https://pay.google.com/gp/v/save/{token}

Ce lien peut être intégré dans votre page Web ou transmis par e-mail sous forme de lien hypertexte. Vous pouvez également l'envoyer au passager via d'autres canaux tels que le chat et les SMS.

La longueur sécurisée d'un JWT encodé est de 1 800 caractères. Si le JWT est inférieur à cette limite, l'objet entier peut être inclus dans le JWT signé. Vos JWT doivent rester en dessous de cette limite. Si la longueur dépasse 1 800 caractères, l'option "Ajouter à Google Wallet" peut ne pas fonctionner si le navigateur a été tronqué.

Bouton "Ajouter à Google Wallet"

Pour optimiser les résultats, exploitez les éléments du bouton Google Wallet sur votre page Web, dans votre messagerie ou dans votre application Android.

Vous pouvez afficher le bouton Google Wallet de deux manières:

  • Vous pouvez utiliser le bouton Web JavaScript pour les sites Web.
  • Le lien JWT avec un bouton Google Wallet peut être utilisé pour les e-mails, les SMS, les applications et les sites Web.

Étapes suivantes