Quase todos os cartões que você pode emitir para um usuário final salvar na Carteira do Google são definidos por dois componentes: uma classe de cartões e um objeto de cartões. Sempre que você emitir um cartão para um usuário, vai precisar de uma instância de uma classe de cartões e de um objeto de cartões, que informa à API Google Wallet o tipo de cartão a ser criado, bem como os detalhes a serem exibidos no cartão, como o valor de um vale-presente ou o nome do titular do cartão.
A API Google Wallet oferece um conjunto predefinido de classes e objetos de cartões usados por você para criar instâncias e um cartão emitido para um usuário, como GiftCardClass
, GiftCardObject
, GenericClass
, GenericObject
e outros.
Cada instância de classe e objeto de cartões é definida como um objeto JSON, que tem um conjunto de propriedades obrigatórias e opcionais que correspondem ao caso de uso específico pretendido para esse tipo de cartão.
Criar uma classe de cartões
Uma classe de cartões pode ser considerada um modelo compartilhado de criação dos cartões. Uma classe de cartões define determinadas propriedades que serão incluídas em todos os cartões que a usam. Um emissor de cartão pode criar várias classes, cada uma com o próprio conjunto distinto de propriedades que definem atributos como estilo e aparência, além de recursos adicionais como Toque inteligente e inscrição e login.
As classes de cartões podem ser criadas usando a API REST da Carteira do Google, o SDK da Carteira do Google para Android ou o Business Console da Carteira do Google.
Para novos usuários, o Business Console é a maneira mais fácil de começar a criar uma classe de cartões, porque ele oferece uma interface do usuário simples, em que é possível definir os vários campos da primeira classe de cartões preenchendo os campos do formulário.
Para usuários avançados, a melhor abordagem é criar classes de cartões de forma programática.
Usar o Business Console da Carteira do Google
Para criar uma classe de cartões no Console empresarial da Carteira do Google, faça o seguinte:
- Acesse o Business Console do Google Pay e da Carteira e faça login com sua conta de emissor da API Google Wallet.
- Na "API Google Wallet" clique em "Gerenciar cartões" .
- Em "Obter acesso de publicação", clique no botão "Criar uma classe" .
- Escolha um tipo de cartão na caixa de diálogo. A Carteira do Google oferece vários tipos de cartão (ingresso para evento, oferta, cartão de fidelidade etc.). Para um caso de uso flexível, selecione "Genérico" como o tipo de cartão.
- Preencha os campos obrigatórios com os valores adequados.
- Clique no botão "Criar classe" para salvar a turma.
Usar a API REST da Carteira do Google
Para criar uma classe de cartões usando a API REST da Carteira do Google, envie uma solicitação POST
para https://walletobjects.googleapis.com/walletobjects/v1/flightClass
. Para mais informações, consulte a documentação de referência.
Java
Para iniciar sua integração em Java, consulte nosso exemplos de código no GitHub (link em inglês).
/** * 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.flightclass().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/boarding-passes/rest/v1/flightclass FlightClass newClass = new FlightClass() .setId(String.format("%s.%s", issuerId, classSuffix)) .setIssuerName("Issuer name") .setReviewStatus("UNDER_REVIEW") .setLocalScheduledDepartureDateTime("2023-07-02T15:30:00") .setFlightHeader( new FlightHeader() .setCarrier(new FlightCarrier().setCarrierIataCode("LX")) .setFlightNumber("123")) .setOrigin(new AirportInfo().setAirportIataCode("LAX").setTerminal("1").setGate("A2")) .setDestination( new AirportInfo().setAirportIataCode("SFO").setTerminal("2").setGate("C3")); FlightClass response = service.flightclass().insert(newClass).execute(); System.out.println("Class insert response"); System.out.println(response.toPrettyString()); return response.getId(); }
PHP
Para iniciar sua integração em PHP, consulte nosso exemplos de código no GitHub (link em inglês).
/** * 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 { $response = $this->service->flightclass->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/boarding-passes/rest/v1/flightclass $newClass = new FlightClass([ 'id' => "{$issuerId}.{$classSuffix}", 'issuerName' => 'Issuer name', 'reviewStatus' => 'UNDER_REVIEW', 'localScheduledDepartureDateTime' => '2023-07-02T15:30:00', 'flightHeader' => new FlightHeader([ 'carrier' => new FlightCarrier([ 'carrierIataCode' => 'LX' ]), 'flightNumber' => '123' ]), 'origin' => new AirportInfo([ 'airportIataCode' => 'LAX', 'terminal' => '1', 'gate' => 'A2' ]), 'destination' => new AirportInfo([ 'airportIataCode' => 'SFO', 'terminal' => '2', 'gate' => 'C3' ]) ]); $response = $this->service->flightclass->insert($newClass); print "Class insert response\n"; print_r($response); return $response->id; }
Python
Para iniciar sua integração em Python, consulte nosso exemplos de código no GitHub (link em inglês).
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.flightclass().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/events/rest/v1/eventticketclass new_class = { 'id': f'{issuer_id}.{class_suffix}', 'issuerName': 'Issuer name', 'reviewStatus': 'UNDER_REVIEW', 'localScheduledDepartureDateTime': '2023-07-02T15:30:00', 'flightHeader': { 'carrier': { 'carrierIataCode': 'LX' }, 'flightNumber': '123' }, 'origin': { 'airportIataCode': 'LAX', 'terminal': '1', 'gate': 'A2' }, 'destination': { 'airportIataCode': 'SFO', 'terminal': '2', 'gate': 'C3' } } response = self.client.flightclass().insert(body=new_class).execute() print('Class insert response') print(response) return f'{issuer_id}.{class_suffix}'
C#
Para iniciar sua integração em C#, consulte nosso exemplos de código no GitHub (link em inglês).
/// <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.Flightclass .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/boarding-passes/rest/v1/flightclass FlightClass newClass = new FlightClass { Id = $"{issuerId}.{classSuffix}", IssuerName = "Issuer name", ReviewStatus = "UNDER_REVIEW", LocalScheduledDepartureDateTime = "2023-07-02T15:30:00", FlightHeader = new FlightHeader { Carrier = new FlightCarrier { CarrierIataCode = "LX" }, FlightNumber = "123" }, Origin = new AirportInfo { AirportIataCode = "LAX", Terminal = "1", Gate = "A2" }, Destination = new AirportInfo { AirportIataCode = "SFO", Terminal = "2", Gate = "C3" } }; responseStream = service.Flightclass .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
Para iniciar sua integração no Node, consulte nosso exemplos de código no GitHub (link em inglês).
/** * 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.flightclass.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/boarding-passes/rest/v1/flightclass let newClass = { 'id': `${issuerId}.${classSuffix}`, 'issuerName': 'Issuer name', 'reviewStatus': 'UNDER_REVIEW', 'localScheduledDepartureDateTime': '2023-07-02T15:30:00', 'flightHeader': { 'carrier': { 'carrierIataCode': 'LX' }, 'flightNumber': '123' }, 'origin': { 'airportIataCode': 'LAX', 'terminal': '1', 'gate': 'A2' }, 'destination': { 'airportIataCode': 'SFO', 'terminal': '2', 'gate': 'C3' } }; response = await this.client.flightclass.insert({ requestBody: newClass }); console.log('Class insert response'); console.log(response); return `${issuerId}.${classSuffix}`; }
Go
Para iniciar sua integração em Go, consulte nossos exemplos de código completos no GitHub exemplos de código no GitHub.
// Create a class. func (d *demoFlight) createClass(issuerId, classSuffix string) { flightClass := new(walletobjects.FlightClass) flightClass.Id = fmt.Sprintf("%s.%s", issuerId, classSuffix) flightClass.ReviewStatus = "UNDER_REVIEW" flightClass.IssuerName = "Issuer name" flightClass.Origin = &walletobjects.AirportInfo{ Terminal: "1", Gate: "A2", AirportIataCode: "LAX", } flightClass.Destination = &walletobjects.AirportInfo{ Terminal: "2", Gate: "C3", AirportIataCode: "SFO", } flightClass.FlightHeader = &walletobjects.FlightHeader{ Carrier: &walletobjects.FlightCarrier{ CarrierIataCode: "LX", }, FlightNumber: "123", } flightClass.LocalScheduledDepartureDateTime = "2023-06-12T23:20:50" res, err := d.service.Flightclass.Insert(flightClass).Do() if err != nil { log.Fatalf("Unable to insert class: %v", err) } else { fmt.Printf("Class insert id:\n%v\n", res.Id) } }
Criar um objeto de cartões
Um objeto de cartões é uma instância de uma classe de cartões. Para criar cartões Objeto, você precisa informar os seguintes atributos:
classId
: oid
da classe de cartõesid
: um ID exclusivo para o clienteConsulte a Modelo de layout para mais informações sobre como esses atributos são representados no Cartão de embarque
Exemplo de código para criar um objeto de cartões:
Java
Para iniciar sua integração em Java, consulte nosso exemplos de código no GitHub (link em inglês).
/** * 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.flightobject().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) { // 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/boarding-passes/rest/v1/flightobject FlightObject newObject = new FlightObject() .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))) .setPassengerName("Passenger name") .setBoardingAndSeatingInfo( new BoardingAndSeatingInfo().setBoardingGroup("B").setSeatNumber("42")) .setReservationInfo(new ReservationInfo().setConfirmationCode("Confirmation code")); FlightObject response = service.flightobject().insert(newObject).execute(); System.out.println("Object insert response"); System.out.println(response.toPrettyString()); return response.getId(); }
PHP
Para iniciar sua integração em PHP, consulte nosso exemplos de código no GitHub (link em inglês).
/** * 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->flightobject->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/boarding-passes/rest/v1/flightobject $newObject = new FlightObject([ '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 ]) ], 'passengerName' => 'Passenger name', 'boardingAndSeatingInfo' => new BoardingAndSeatingInfo([ 'boardingGroup' => 'B', 'seatNumber' => '42' ]), 'reservationInfo' => new ReservationInfo([ 'confirmationCode' => 'Confirmation code' ]) ]); $response = $this->service->flightobject->insert($newObject); print "Object insert response\n"; print_r($response); return $response->id; }
Python
Para iniciar sua integração em Python, consulte nosso exemplos de código no GitHub (link em inglês).
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.flightobject().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/boarding-passes/rest/v1/flightobject 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 }], 'passengerName': 'Passenger name', 'boardingAndSeatingInfo': { 'boardingGroup': 'B', 'seatNumber': '42' }, 'reservationInfo': { 'confirmationCode': 'Confirmation code' } } # Create the object response = self.client.flightobject().insert(body=new_object).execute() print('Object insert response') print(response) return f'{issuer_id}.{object_suffix}'
C#
Para iniciar sua integração em C#, consulte nosso exemplos de código no GitHub (link em inglês).
/// <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.Flightobject .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/boarding-passes/rest/v1/flightobject FlightObject newObject = new FlightObject { 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 } }, PassengerName = "Passenger name", BoardingAndSeatingInfo = new BoardingAndSeatingInfo { BoardingGroup = "B", SeatNumber = "42" }, ReservationInfo = new ReservationInfo { ConfirmationCode = "Confirmation code" } }; responseStream = service.Flightobject .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
Para iniciar sua integração no Node, consulte nosso exemplos de código no GitHub (link em inglês).
/** * 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.flightobject.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/boarding-passes/rest/v1/flightobject 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 } ], 'passengerName': 'Passenger name', 'boardingAndSeatingInfo': { 'boardingGroup': 'B', 'seatNumber': '42' }, 'reservationInfo': { 'confirmationCode': 'Confirmation code' } }; response = await this.client.flightobject.insert({ requestBody: newObject }); console.log('Object insert response'); console.log(response); return `${issuerId}.${objectSuffix}`; }
Go
Para iniciar sua integração em Go, consulte nossos exemplos de código completos no GitHub exemplos de código no GitHub.
// Create an object. func (d *demoFlight) createObject(issuerId, classSuffix, objectSuffix string) { flightObject := new(walletobjects.FlightObject) flightObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix) flightObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix) flightObject.State = "ACTIVE" flightObject.PassengerName = "Passenger name" flightObject.ReservationInfo = &walletobjects.ReservationInfo{ ConfirmationCode: "Confirmation code", } flightObject.BoardingAndSeatingInfo = &walletobjects.BoardingAndSeatingInfo{ BoardingGroup: "B", SeatNumber: "42", } flightObject.HeroImage = &walletobjects.Image{ SourceUri: &walletobjects.ImageUri{ Uri: "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg", }, } flightObject.Barcode = &walletobjects.Barcode{ Type: "QR_CODE", Value: "QR code", } flightObject.Locations = []*walletobjects.LatLongPoint{ &walletobjects.LatLongPoint{ Latitude: 37.424015499999996, Longitude: -122.09259560000001, }, } flightObject.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", }, }, } flightObject.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", }, }, }, } flightObject.TextModulesData = []*walletobjects.TextModuleData{ &walletobjects.TextModuleData{ Body: "Text module body", Header: "Text module header", Id: "TEXT_MODULE_ID", }, } res, err := d.service.Flightobject.Insert(flightObject).Do() if err != nil { log.Fatalf("Unable to insert object: %v", err) } else { fmt.Printf("Object insert id:\n%s\n", res.Id) } }
Depois de concluído, o objeto de cartões do cliente será criado no servidor. No entanto, nesta etapa, o objeto de cartões não está vinculado a um do usuário do Google ou do dispositivo dele. Para que o cartão seja associado a um usuário da Carteira do Google, é necessário emitir o cartão.