Créer des classes de cartes et des objets Cartes

Presque toutes les cartes que vous pouvez émettre pour qu'un utilisateur final les enregistre dans son compte Google Wallet sont définies par deux composants: une classe Cartes et un objet Cartes. Chaque fois que vous envoyez une carte à un utilisateur, vous avez besoin d'une instance de classe Cartes et d'un objet Cartes, qui indique à l'API Google Wallet le type de carte à créer, ainsi que les informations à afficher sur la carte, comme la valeur d'une carte cadeau ou le nom d'un détenteur de billet.

L'API Google Wallet fournit un ensemble prédéfini d'objets Cartes et de classes de cartes dont vous créez des instances, puis que vous utilisez pour créer une carte émise à un utilisateur, par exemple GiftCardClass et GiftCardObject, GenericClass et GenericObject, entre autres.

Chaque classe d'objet Cartes et chaque instance d'objet Cartes est définie en tant qu'objet JSON, qui possède un ensemble de propriétés obligatoires et facultatives correspondant au cas d'utilisation spécifique destiné à ce type de carte.

Créer une classe de carte

Une classe Cartes peut être considérée comme un modèle partagé à partir duquel sont créées des cartes. Une classe Cartes définit certaines propriétés qui seront incluses dans toutes les cartes qui l'utilisent. Un émetteur de cartes peut créer plusieurs classes, chacune avec son propre ensemble distinct de propriétés qui définissent des attributs tels que le style et l'apparence, ainsi que des fonctionnalités supplémentaires comme Smart Tap, l'enregistrement et la connexion.

Vous pouvez créer des classes de carte à l'aide de l'API REST de Google Wallet, du SDK Google Wallet pour Android ou de la Business Console de Google Wallet.

Pour les nouveaux utilisateurs, la Business Console est le moyen le plus simple de commencer à créer une classe de carte. En effet, elle fournit une interface utilisateur simple dans laquelle vous pouvez définir les différents champs de votre première classe Cartes en remplissant les champs de formulaire.

La création programmatique de classes de cartes est la meilleure approche pour les utilisateurs avancés.

Utiliser la Business Console de Google Wallet

Pour créer une classe de carte dans la Google Wallet Business Console, procédez comme suit:

  1. Accédez à la Google Pay and Wallet Business Console et connectez-vous avec votre compte d'émetteur pour l'API Google Wallet.
  2. Sur l'API Google Wallet cliquez sur "Gérer les cartes", .
  3. Sous "Obtenir l'accès en publication", cliquez sur "Créer un cours". .
  4. Choisissez un type de carte dans la boîte de dialogue. Google Wallet propose différents types de cartes (billet pour un événement, offre, carte de fidélité, etc.). Pour un cas d'utilisation flexible, sélectionnez "Générique". comme type de carte.
  5. Renseignez les champs obligatoires.
  6. Cliquez sur le bouton "Créer un cours" pour enregistrer votre cours.

Utiliser l'API REST Google Wallet

Pour créer une classe de carte à l'aide de l'API REST Google Wallet, envoyez une requête POST à https://walletobjects.googleapis.com/walletobjects/v1/transitClass. Pour en savoir plus, consultez la documentation de référence.

Java

Pour commencer votre intégration en Java, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

/**
 * Create a class.
 *
 * @param issuerId The issuer ID being used for this request.
 * @param classSuffix Developer-defined unique ID for this pass class.
 * @return The pass class ID: "{issuerId}.{classSuffix}"
 */
public String createClass(String issuerId, String classSuffix) throws IOException {
  // Check if the class exists
  try {
    service.transitclass().get(String.format("%s.%s", issuerId, classSuffix)).execute();

    System.out.printf("Class %s.%s already exists!%n", issuerId, classSuffix);
    return String.format("%s.%s", issuerId, classSuffix);
  } catch (GoogleJsonResponseException ex) {
    if (ex.getStatusCode() != 404) {
      // Something else went wrong...
      ex.printStackTrace();
      return String.format("%s.%s", issuerId, classSuffix);
    }
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitclass
  TransitClass newClass =
      new TransitClass()
          .setId(String.format("%s.%s", issuerId, classSuffix))
          .setIssuerName("Issuer name")
          .setReviewStatus("UNDER_REVIEW")
          .setLogo(
              new Image()
                  .setSourceUri(
                      new ImageUri()
                          .setUri(
                              "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png"))
                  .setContentDescription(
                      new LocalizedString()
                          .setDefaultValue(
                              new TranslatedString()
                                  .setLanguage("en-US")
                                  .setValue("Logo description"))))
          .setTransitType("BUS");

  TransitClass response = service.transitclass().insert(newClass).execute();

  System.out.println("Class insert response");
  System.out.println(response.toPrettyString());

  return response.getId();
}

PHP

Pour commencer l'intégration en PHP, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

/**
 * Create a class.
 *
 * @param string $issuerId The issuer ID being used for this request.
 * @param string $classSuffix Developer-defined unique ID for this pass class.
 *
 * @return string The pass class ID: "{$issuerId}.{$classSuffix}"
 */
public function createClass(string $issuerId, string $classSuffix)
{
  // Check if the class exists
  try {
    $this->service->transitclass->get("{$issuerId}.{$classSuffix}");

    print("Class {$issuerId}.{$classSuffix} already exists!");
    return "{$issuerId}.{$classSuffix}";
  } catch (Google\Service\Exception $ex) {
    if (empty($ex->getErrors()) || $ex->getErrors()[0]['reason'] != 'classNotFound') {
      // Something else went wrong...
      print_r($ex);
      return "{$issuerId}.{$classSuffix}";
    }
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitclass
  $newClass = new TransitClass([
    'id' => "{$issuerId}.{$classSuffix}",
    'issuerName' => 'Issuer name',
    'reviewStatus' => 'UNDER_REVIEW',
    'logo' => new Image([
      'sourceUri' => new ImageUri([
        'uri' => 'https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png'
      ]),
      'contentDescription' => new LocalizedString([
        'defaultValue' => new TranslatedString([
          'language' => 'en-US',
          'value' => 'Logo description'
        ])
      ])
    ]),
    'transitType' => 'BUS'
  ]);

  $response = $this->service->transitclass->insert($newClass);

  print "Class insert response\n";
  print_r($response);

  return $response->id;
}

Python

Pour commencer l'intégration dans Python, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

def create_class(self, issuer_id: str, class_suffix: str) -> str:
    """Create a class.

    Args:
        issuer_id (str): The issuer ID being used for this request.
        class_suffix (str): Developer-defined unique ID for this pass class.

    Returns:
        The pass class ID: f"{issuer_id}.{class_suffix}"
    """

    # Check if the class exists
    try:
        self.client.transitclass().get(resourceId=f'{issuer_id}.{class_suffix}').execute()
    except HttpError as e:
        if e.status_code != 404:
            # Something else went wrong...
            print(e.error_details)
            return f'{issuer_id}.{class_suffix}'
    else:
        print(f'Class {issuer_id}.{class_suffix} already exists!')
        return f'{issuer_id}.{class_suffix}'

    # See link below for more information on required properties
    # https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitclass
    new_class = {
        'id': f'{issuer_id}.{class_suffix}',
        'issuerName': 'Issuer name',
        'reviewStatus': 'UNDER_REVIEW',
        'logo': {
            'sourceUri': {
                'uri':
                    'https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png'
            },
            'contentDescription': {
                'defaultValue': {
                    'language': 'en-US',
                    'value': 'Logo description'
                }
            }
        },
        'transitType': 'BUS'
    }

    response = self.client.transitclass().insert(body=new_class).execute()

    print('Class insert response')
    print(response)

    return f'{issuer_id}.{class_suffix}'

C#

Pour commencer votre intégration en C#, consultez notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

/// <summary>
/// Create a class.
/// </summary>
/// <param name="issuerId">The issuer ID being used for this request.</param>
/// <param name="classSuffix">Developer-defined unique ID for this pass class.</param>
/// <returns>The pass class ID: "{issuerId}.{classSuffix}"</returns>
public string CreateClass(string issuerId, string classSuffix)
{
  // Check if the class exists
  Stream responseStream = service.Transitclass
      .Get($"{issuerId}.{classSuffix}")
      .ExecuteAsStream();

  StreamReader responseReader = new StreamReader(responseStream);
  JObject jsonResponse = JObject.Parse(responseReader.ReadToEnd());

  if (!jsonResponse.ContainsKey("error"))
  {
    Console.WriteLine($"Class {issuerId}.{classSuffix} already exists!");
    return $"{issuerId}.{classSuffix}";
  }
  else if (jsonResponse["error"].Value<int>("code") != 404)
  {
    // Something else went wrong...
    Console.WriteLine(jsonResponse.ToString());
    return $"{issuerId}.{classSuffix}";
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitclass
  TransitClass newClass = new TransitClass
  {
    Id = $"{issuerId}.{classSuffix}",
    IssuerName = "Issuer name",
    ReviewStatus = "UNDER_REVIEW",
    Logo = new Image
    {
      SourceUri = new ImageUri
      {
        Uri = "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png"
      },
      ContentDescription = new LocalizedString
      {
        DefaultValue = new TranslatedString
        {
          Language = "en-US",
          Value = "Logo description"
        }
      }
    },
    TransitType = "BUS"
  };

  responseStream = service.Transitclass
      .Insert(newClass)
      .ExecuteAsStream();

  responseReader = new StreamReader(responseStream);
  jsonResponse = JObject.Parse(responseReader.ReadToEnd());

  Console.WriteLine("Class insert response");
  Console.WriteLine(jsonResponse.ToString());

  return $"{issuerId}.{classSuffix}";
}

Node.js

Pour commencer votre intégration dans Node, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

/**
 * Create a class.
 *
 * @param {string} issuerId The issuer ID being used for this request.
 * @param {string} classSuffix Developer-defined unique ID for this pass class.
 *
 * @returns {string} The pass class ID: `${issuerId}.${classSuffix}`
 */
async createClass(issuerId, classSuffix) {
  let response;

  // Check if the class exists
  try {
    response = await this.client.transitclass.get({
      resourceId: `${issuerId}.${classSuffix}`
    });

    console.log(`Class ${issuerId}.${classSuffix} already exists!`);

    return `${issuerId}.${classSuffix}`;
  } catch (err) {
    if (err.response && err.response.status !== 404) {
      // Something else went wrong...
      console.log(err);
      return `${issuerId}.${classSuffix}`;
    }
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitclass
  let newClass = {
    'id': `${issuerId}.${classSuffix}`,
    'issuerName': 'Issuer name',
    'reviewStatus': 'UNDER_REVIEW',
    'logo': {
      'sourceUri': {
        'uri': 'https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png'
      },
      'contentDescription': {
        'defaultValue': {
          'language': 'en-US',
          'value': 'Logo description'
        }
      }
    },
    'transitType': 'BUS'
  };

  response = await this.client.transitclass.insert({
    requestBody: newClass
  });

  console.log('Class insert response');
  console.log(response);

  return `${issuerId}.${classSuffix}`;
}

Go

Pour commencer votre intégration dans Go, consultez nos exemples de code complets sur GitHub. <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

// Create a class.
func (d *demoTransit) createClass(issuerId, classSuffix string) {
	logo := walletobjects.Image{
		SourceUri: &walletobjects.ImageUri{
			Uri: "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg",
		},
	}
	transitClass := new(walletobjects.TransitClass)
	transitClass.Id = fmt.Sprintf("%s.%s", issuerId, classSuffix)
	transitClass.IssuerName = "Issuer name"
	transitClass.ReviewStatus = "UNDER_REVIEW"
	transitClass.Logo = &logo
	transitClass.TransitType = "BUS"
	res, err := d.service.Transitclass.Insert(transitClass).Do()
	if err != nil {
		log.Fatalf("Unable to insert class: %v", err)
	} else {
		fmt.Printf("Class insert id:\n%v\n", res.Id)
	}
}

Créer un objet Cartes

<ph type="x-smartling-placeholder">

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

  • classId: id de la classe Cartes
  • id: identifiant unique de votre client

    Consultez le Modèle de mise en page pour en savoir plus sur la représentation de ces attributs dans le titre de transport.

    Exemple de code permettant de créer un objet Cartes:

    Java

    Pour commencer votre intégration en Java, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

    /**
     * Create an object.
     *
     * @param issuerId The issuer ID being used for this request.
     * @param classSuffix Developer-defined unique ID for this pass class.
     * @param objectSuffix Developer-defined unique ID for this pass object.
     * @return The pass object ID: "{issuerId}.{objectSuffix}"
     */
    public String createObject(String issuerId, String classSuffix, String objectSuffix)
        throws IOException {
      // Check if the object exists
      try {
        service.transitobject().get(String.format("%s.%s", issuerId, objectSuffix)).execute();
    
        System.out.printf("Object %s.%s already exists!%n", issuerId, objectSuffix);
        return String.format("%s.%s", issuerId, objectSuffix);
      } catch (GoogleJsonResponseException ex) {
        if (ex.getStatusCode() == 404) {
          // Object does not exist
          // Do nothing
        } else {
          // Something else went wrong...
          ex.printStackTrace();
          return String.format("%s.%s", issuerId, objectSuffix);
        }
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
      TransitObject newObject =
          new TransitObject()
              .setId(String.format("%s.%s", issuerId, objectSuffix))
              .setClassId(String.format("%s.%s", issuerId, classSuffix))
              .setState("ACTIVE")
              .setHeroImage(
                  new Image()
                      .setSourceUri(
                          new ImageUri()
                              .setUri(
                                  "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"))
                      .setContentDescription(
                          new LocalizedString()
                              .setDefaultValue(
                                  new TranslatedString()
                                      .setLanguage("en-US")
                                      .setValue("Hero image description"))))
              .setTextModulesData(
                      List.of(
                              new TextModuleData()
                                      .setHeader("Text module header")
                                      .setBody("Text module body")
                                      .setId("TEXT_MODULE_ID")))
              .setLinksModuleData(
                  new LinksModuleData()
                      .setUris(
                          Arrays.asList(
                              new Uri()
                                  .setUri("http://maps.google.com/")
                                  .setDescription("Link module URI description")
                                  .setId("LINK_MODULE_URI_ID"),
                              new Uri()
                                  .setUri("tel:6505555555")
                                  .setDescription("Link module tel description")
                                  .setId("LINK_MODULE_TEL_ID"))))
              .setImageModulesData(
                      List.of(
                              new ImageModuleData()
                                      .setMainImage(
                                              new Image()
                                                      .setSourceUri(
                                                              new ImageUri()
                                                                      .setUri(
                                                                              "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"))
                                                      .setContentDescription(
                                                              new LocalizedString()
                                                                      .setDefaultValue(
                                                                              new TranslatedString()
                                                                                      .setLanguage("en-US")
                                                                                      .setValue("Image module description"))))
                                      .setId("IMAGE_MODULE_ID")))
              .setBarcode(new Barcode().setType("QR_CODE").setValue("QR code value"))
              .setLocations(
                      List.of(
                              new LatLongPoint()
                                      .setLatitude(37.424015499999996)
                                      .setLongitude(-122.09259560000001)))
              .setPassengerType("SINGLE_PASSENGER")
              .setPassengerNames("Passenger names")
              .setTripType("ONE_WAY")
              .setTicketLeg(
                  new TicketLeg()
                      .setOriginStationCode("LA")
                      .setOriginName(
                          new LocalizedString()
                              .setDefaultValue(
                                  new TranslatedString()
                                      .setLanguage("en-US")
                                      .setValue("Origin name")))
                      .setDestinationStationCode("SFO")
                      .setDestinationName(
                          new LocalizedString()
                              .setDefaultValue(
                                  new TranslatedString()
                                      .setLanguage("en-US")
                                      .setValue("Origin name")))
                      .setDepartureDateTime("2020-04-12T16:20:50.52Z")
                      .setArrivalDateTime("2020-04-12T20:20:50.52Z")
                      .setFareName(
                          new LocalizedString()
                              .setDefaultValue(
                                  new TranslatedString()
                                      .setLanguage("en-US")
                                      .setValue("Fare name"))));
    
      TransitObject response = service.transitobject().insert(newObject).execute();
    
      System.out.println("Object insert response");
      System.out.println(response.toPrettyString());
    
      return response.getId();
    }
    

    PHP

    Pour commencer l'intégration en PHP, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

    /**
     * Create an object.
     *
     * @param string $issuerId The issuer ID being used for this request.
     * @param string $classSuffix Developer-defined unique ID for this pass class.
     * @param string $objectSuffix Developer-defined unique ID for this pass object.
     *
     * @return string The pass object ID: "{$issuerId}.{$objectSuffix}"
     */
    public function createObject(string $issuerId, string $classSuffix, string $objectSuffix)
    {
      // Check if the object exists
      try {
        $this->service->transitobject->get("{$issuerId}.{$objectSuffix}");
    
        print("Object {$issuerId}.{$objectSuffix} already exists!");
        return "{$issuerId}.{$objectSuffix}";
      } catch (Google\Service\Exception $ex) {
        if (empty($ex->getErrors()) || $ex->getErrors()[0]['reason'] != 'resourceNotFound') {
          // Something else went wrong...
          print_r($ex);
          return "{$issuerId}.{$objectSuffix}";
        }
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
      $newObject = new TransitObject([
        'id' => "{$issuerId}.{$objectSuffix}",
        'classId' => "{$issuerId}.{$classSuffix}",
        'state' => 'ACTIVE',
        'heroImage' => new Image([
          'sourceUri' => new ImageUri([
            'uri' => 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg'
          ]),
          'contentDescription' => new LocalizedString([
            'defaultValue' => new TranslatedString([
              'language' => 'en-US',
              'value' => 'Hero image description'
            ])
          ])
        ]),
        'textModulesData' => [
          new TextModuleData([
            'header' => 'Text module header',
            'body' => 'Text module body',
            'id' => 'TEXT_MODULE_ID'
          ])
        ],
        'linksModuleData' => new LinksModuleData([
          'uris' => [
            new Uri([
              'uri' => 'http://maps.google.com/',
              'description' => 'Link module URI description',
              'id' => 'LINK_MODULE_URI_ID'
            ]),
            new Uri([
              'uri' => 'tel:6505555555',
              'description' => 'Link module tel description',
              'id' => 'LINK_MODULE_TEL_ID'
            ])
          ]
        ]),
        'imageModulesData' => [
          new ImageModuleData([
            'mainImage' => new Image([
              'sourceUri' => new ImageUri([
                'uri' => 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg'
              ]),
              'contentDescription' => new LocalizedString([
                'defaultValue' => new TranslatedString([
                  'language' => 'en-US',
                  'value' => 'Image module description'
                ])
              ])
            ]),
            'id' => 'IMAGE_MODULE_ID'
          ])
        ],
        'barcode' => new Barcode([
          'type' => 'QR_CODE',
          'value' => 'QR code value'
        ]),
        'locations' => [
          new LatLongPoint([
            'latitude' => 37.424015499999996,
            'longitude' =>  -122.09259560000001
          ])
        ],
        'passengerType' => 'SINGLE_PASSENGER',
        'passengerNames' => 'Passenger names',
        'tripType' => 'ONE_WAY',
        'ticketLeg' => new TicketLeg([
          'originStationCode' => 'LA',
          'originName' => new LocalizedString([
            'defaultValue' => new TranslatedString([
              'language' => 'en-US',
              'value' => 'Origin name'
            ])
          ]),
          'destinationStationCode' => 'SFO',
          'destinationName' => new LocalizedString([
            'defaultValue' => new TranslatedString([
              'language' => 'en-US',
              'value' => 'Destination name'
            ])
          ]),
          'departureDateTime' => '2020-04-12T16:20:50.52Z',
          'arrivalDateTime' => '2020-04-12T20:20:50.52Z',
          'fareName' => new LocalizedString([
            'defaultValue' => new TranslatedString([
              'language' => 'en-US',
              'value' => 'Fare name'
            ])
          ])
        ])
      ]);
    
      $response = $this->service->transitobject->insert($newObject);
    
      print "Object insert response\n";
      print_r($response);
    
      return $response->id;
    }
    

    Python

    Pour commencer l'intégration dans Python, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

    def create_object(self, issuer_id: str, class_suffix: str,
                      object_suffix: str) -> str:
        """Create an object.
    
        Args:
            issuer_id (str): The issuer ID being used for this request.
            class_suffix (str): Developer-defined unique ID for the pass class.
            object_suffix (str): Developer-defined unique ID for the pass object.
    
        Returns:
            The pass object ID: f"{issuer_id}.{object_suffix}"
        """
    
        # Check if the object exists
        try:
            self.client.transitobject().get(resourceId=f'{issuer_id}.{object_suffix}').execute()
        except HttpError as e:
            if e.status_code != 404:
                # Something else went wrong...
                print(e.error_details)
                return f'{issuer_id}.{object_suffix}'
        else:
            print(f'Object {issuer_id}.{object_suffix} already exists!')
            return f'{issuer_id}.{object_suffix}'
    
        # See link below for more information on required properties
        # https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
        new_object = {
            'id': f'{issuer_id}.{object_suffix}',
            'classId': f'{issuer_id}.{class_suffix}',
            'state': 'ACTIVE',
            'heroImage': {
                'sourceUri': {
                    'uri':
                        'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg'
                },
                'contentDescription': {
                    'defaultValue': {
                        'language': 'en-US',
                        'value': 'Hero image description'
                    }
                }
            },
            'textModulesData': [{
                'header': 'Text module header',
                'body': 'Text module body',
                'id': 'TEXT_MODULE_ID'
            }],
            'linksModuleData': {
                'uris': [{
                    'uri': 'http://maps.google.com/',
                    'description': 'Link module URI description',
                    'id': 'LINK_MODULE_URI_ID'
                }, {
                    'uri': 'tel:6505555555',
                    'description': 'Link module tel description',
                    'id': 'LINK_MODULE_TEL_ID'
                }]
            },
            'imageModulesData': [{
                'mainImage': {
                    'sourceUri': {
                        'uri':
                            'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg'
                    },
                    'contentDescription': {
                        'defaultValue': {
                            'language': 'en-US',
                            'value': 'Image module description'
                        }
                    }
                },
                'id': 'IMAGE_MODULE_ID'
            }],
            'barcode': {
                'type': 'QR_CODE',
                'value': 'QR code'
            },
            'locations': [{
                'latitude': 37.424015499999996,
                'longitude': -122.09259560000001
            }],
            'passengerType': 'SINGLE_PASSENGER',
            'passengerNames': 'Passenger names',
            'tripType': 'ONE_WAY',
            'ticketLeg': {
                'originStationCode': 'LA',
                'originName': {
                    'defaultValue': {
                        'language': 'en-US',
                        'value': 'Origin name'
                    }
                },
                'destinationStationCode': 'SFO',
                'destinationName': {
                    'defaultValue': {
                        'language': 'en-US',
                        'value': 'Destination name'
                    }
                },
                'departureDateTime': '2020-04-12T16:20:50.52Z',
                'arrivalDateTime': '2020-04-12T20:20:50.52Z',
                'fareName': {
                    'defaultValue': {
                        'language': 'en-US',
                        'value': 'Fare name'
                    }
                }
            }
        }
    
        # Create the object
        response = self.client.transitobject().insert(body=new_object).execute()
    
        print('Object insert response')
        print(response)
    
        return f'{issuer_id}.{object_suffix}'
    
    

    C#

    Pour commencer votre intégration en C#, consultez notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

    /// <summary>
    /// Create an object.
    /// </summary>
    /// <param name="issuerId">The issuer ID being used for this request.</param>
    /// <param name="classSuffix">Developer-defined unique ID for this pass class.</param>
    /// <param name="objectSuffix">Developer-defined unique ID for this pass object.</param>
    /// <returns>The pass object ID: "{issuerId}.{objectSuffix}"</returns>
    public string CreateObject(string issuerId, string classSuffix, string objectSuffix)
    {
      // Check if the object exists
      Stream responseStream = service.Transitobject
          .Get($"{issuerId}.{objectSuffix}")
          .ExecuteAsStream();
    
      StreamReader responseReader = new StreamReader(responseStream);
      JObject jsonResponse = JObject.Parse(responseReader.ReadToEnd());
    
      if (!jsonResponse.ContainsKey("error"))
      {
        Console.WriteLine($"Object {issuerId}.{objectSuffix} already exists!");
        return $"{issuerId}.{objectSuffix}";
      }
      else if (jsonResponse["error"].Value<int>("code") != 404)
      {
        // Something else went wrong...
        Console.WriteLine(jsonResponse.ToString());
        return $"{issuerId}.{objectSuffix}";
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
      TransitObject newObject = new TransitObject
      {
        Id = $"{issuerId}.{objectSuffix}",
        ClassId = $"{issuerId}.{classSuffix}",
        State = "ACTIVE",
        HeroImage = new Image
        {
          SourceUri = new ImageUri
          {
            Uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"
          },
          ContentDescription = new LocalizedString
          {
            DefaultValue = new TranslatedString
            {
              Language = "en-US",
              Value = "Hero image description"
            }
          }
        },
        TextModulesData = new List<TextModuleData>
        {
          new TextModuleData
          {
            Header = "Text module header",
            Body = "Text module body",
            Id = "TEXT_MODULE_ID"
          }
        },
        LinksModuleData = new LinksModuleData
        {
          Uris = new List<Google.Apis.Walletobjects.v1.Data.Uri>
          {
            new Google.Apis.Walletobjects.v1.Data.Uri
            {
              UriValue = "http://maps.google.com/",
              Description = "Link module URI description",
              Id = "LINK_MODULE_URI_ID"
            },
            new Google.Apis.Walletobjects.v1.Data.Uri
            {
              UriValue = "tel:6505555555",
              Description = "Link module tel description",
              Id = "LINK_MODULE_TEL_ID"
            }
          }
        },
        ImageModulesData = new List<ImageModuleData>
        {
          new ImageModuleData
          {
            MainImage = new Image
            {
              SourceUri = new ImageUri
              {
                Uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"
              },
              ContentDescription = new LocalizedString
              {
                DefaultValue = new TranslatedString
                {
                  Language = "en-US",
                  Value = "Image module description"
                }
              }
            },
            Id = "IMAGE_MODULE_ID"
          }
        },
        Barcode = new Barcode
        {
          Type = "QR_CODE",
          Value = "QR code"
        },
        Locations = new List<LatLongPoint>
        {
          new LatLongPoint
          {
            Latitude = 37.424015499999996,
            Longitude = -122.09259560000001
          }
        },
        PassengerType = "SINGLE_PASSENGER",
        PassengerNames = "Passenger names",
        TripType = "ONE_WAY",
        TicketLeg = new TicketLeg
        {
          OriginStationCode = "LA",
          OriginName = new LocalizedString
          {
            DefaultValue = new TranslatedString
            {
              Language = "en-US",
              Value = "Origin name"
            }
          },
          DestinationStationCode = "SFO",
          DestinationName = new LocalizedString
          {
            DefaultValue = new TranslatedString
            {
              Language = "en-US",
              Value = "Destination name"
            }
          },
          DepartureDateTime = "2020-04-12T16:20:50.52Z",
          ArrivalDateTime = "2020-04-12T20:20:50.52Z",
          FareName = new LocalizedString
          {
            DefaultValue = new TranslatedString
            {
              Language = "en-US",
              Value = "Fare name"
            }
          }
        }
      };
    
      responseStream = service.Transitobject
          .Insert(newObject)
          .ExecuteAsStream();
      responseReader = new StreamReader(responseStream);
      jsonResponse = JObject.Parse(responseReader.ReadToEnd());
    
      Console.WriteLine("Object insert response");
      Console.WriteLine(jsonResponse.ToString());
    
      return $"{issuerId}.{objectSuffix}";
    }
    

    Node.js

    Pour commencer votre intégration dans Node, reportez-vous à notre <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

    /**
     * Create an object.
     *
     * @param {string} issuerId The issuer ID being used for this request.
     * @param {string} classSuffix Developer-defined unique ID for the pass class.
     * @param {string} objectSuffix Developer-defined unique ID for the pass object.
     *
     * @returns {string} The pass object ID: `${issuerId}.${objectSuffix}`
     */
    async createObject(issuerId, classSuffix, objectSuffix) {
      let response;
    
      // Check if the object exists
      try {
        response = await this.client.transitobject.get({
          resourceId: `${issuerId}.${objectSuffix}`
        });
    
        console.log(`Object ${issuerId}.${objectSuffix} already exists!`);
    
        return `${issuerId}.${objectSuffix}`;
      } catch (err) {
        if (err.response && err.response.status !== 404) {
          // Something else went wrong...
          console.log(err);
          return `${issuerId}.${objectSuffix}`;
        }
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
      let newObject = {
        'id': `${issuerId}.${objectSuffix}`,
        'classId': `${issuerId}.${classSuffix}`,
        'state': 'ACTIVE',
        'heroImage': {
          'sourceUri': {
            'uri': 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg'
          },
          'contentDescription': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'Hero image description'
            }
          }
        },
        'textModulesData': [
          {
            'header': 'Text module header',
            'body': 'Text module body',
            'id': 'TEXT_MODULE_ID'
          }
        ],
        'linksModuleData': {
          'uris': [
            {
              'uri': 'http://maps.google.com/',
              'description': 'Link module URI description',
              'id': 'LINK_MODULE_URI_ID'
            },
            {
              'uri': 'tel:6505555555',
              'description': 'Link module tel description',
              'id': 'LINK_MODULE_TEL_ID'
            }
          ]
        },
        'imageModulesData': [
          {
            'mainImage': {
              'sourceUri': {
                'uri': 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg'
              },
              'contentDescription': {
                'defaultValue': {
                  'language': 'en-US',
                  'value': 'Image module description'
                }
              }
            },
            'id': 'IMAGE_MODULE_ID'
          }
        ],
        'barcode': {
          'type': 'QR_CODE',
          'value': 'QR code'
        },
        'locations': [
          {
            'latitude': 37.424015499999996,
            'longitude': -122.09259560000001
          }
        ],
        'passengerType': 'SINGLE_PASSENGER',
        'passengerNames': 'Passenger names',
        'tripType': 'ONE_WAY',
        'ticketLeg': {
          'originStationCode': 'LA',
          'originName': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'Origin name'
            }
          },
          'destinationStationCode': 'SFO',
          'destinationName': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'Destination name'
            }
          },
          'departureDateTime': '2020-04-12T16:20:50.52Z',
          'arrivalDateTime': '2020-04-12T20:20:50.52Z',
          'fareName': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'Fare name'
            }
          }
        }
      };
    
      response = await this.client.transitobject.insert({
        requestBody: newObject
      });
    
      console.log('Object insert response');
      console.log(response);
    
      return `${issuerId}.${objectSuffix}`;
    }
    

    Go

    Pour commencer votre intégration dans Go, consultez nos exemples de code complets sur GitHub. <ph type="x-smartling-placeholder"></ph> exemples de code sur GitHub.

    // Create an object.
    func (d *demoTransit) createObject(issuerId, classSuffix, objectSuffix string) {
    	transitObject := new(walletobjects.TransitObject)
    	transitObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix)
    	transitObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix)
    	transitObject.State = "ACTIVE"
    	transitObject.PassengerNames = "Passenger names"
    	transitObject.TripType = "ONE_WAY"
    	transitObject.PassengerType = "SINGLE_PASSENGER"
    	transitObject.TicketLeg = &walletobjects.TicketLeg{
    		DestinationStationCode: "SFO",
    		OriginStationCode:      "LA",
    	}
    	transitObject.HeroImage = &walletobjects.Image{
    		SourceUri: &walletobjects.ImageUri{
    			Uri: "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
    		},
    	}
    	transitObject.Barcode = &walletobjects.Barcode{
    		Type:  "QR_CODE",
    		Value: "QR code",
    	}
    	transitObject.Locations = []*walletobjects.LatLongPoint{
    		&walletobjects.LatLongPoint{
    			Latitude:  37.424015499999996,
    			Longitude: -122.09259560000001,
    		},
    	}
    	transitObject.LinksModuleData = &walletobjects.LinksModuleData{
    		Uris: []*walletobjects.Uri{
    			&walletobjects.Uri{
    				Id:          "LINK_MODULE_URI_ID",
    				Uri:         "http://maps.google.com/",
    				Description: "Link module URI description",
    			},
    			&walletobjects.Uri{
    				Id:          "LINK_MODULE_TEL_ID",
    				Uri:         "tel:6505555555",
    				Description: "Link module tel description",
    			},
    		},
    	}
    	transitObject.ImageModulesData = []*walletobjects.ImageModuleData{
    		&walletobjects.ImageModuleData{
    			Id: "IMAGE_MODULE_ID",
    			MainImage: &walletobjects.Image{
    				SourceUri: &walletobjects.ImageUri{
    					Uri: "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
    				},
    			},
    		},
    	}
    	transitObject.TextModulesData = []*walletobjects.TextModuleData{
    		&walletobjects.TextModuleData{
    			Body:   "Text module body",
    			Header: "Text module header",
    			Id:     "TEXT_MODULE_ID",
    		},
    	}
    	res, err := d.service.Transitobject.Insert(transitObject).Do()
    	if err != nil {
    		log.Fatalf("Unable to insert object: %v", err)
    	} else {
    		fmt.Printf("Object insert id:\n%s\n", res.Id)
    	}
    }
    
    

    Une fois l'opération terminée, l'objet Cartes de votre client est disponible dans la Google Cloud. Toutefois, à ce stade, l'objet Cartes n'est associé à aucune un utilisateur Google ou son appareil. Pour que la carte soit associée à un Utilisateur Google Wallet, vous devez émettre la carte.