### Install Node.js Dependencies Source: https://github.com/google-wallet/rest-samples/blob/main/nodejs/README.md Run this command in the project directory to install necessary dependencies from package.json. ```bash npm install ``` -------------------------------- ### Install Go Dependencies Source: https://github.com/google-wallet/rest-samples/blob/main/go/README.md Installs the necessary dependencies for a Go sample. Run this command once before executing any samples. ```bash go install demo_eventticket.go ``` -------------------------------- ### Run Go Sample Source: https://github.com/google-wallet/rest-samples/blob/main/go/README.md Executes a specific Google Wallet Go sample. Ensure dependencies are installed first. ```bash go run demo_eventticket.go ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/google-wallet/rest-samples/blob/main/php/README.md Run this command in the same directory as composer.json to install project dependencies. ```bash composer install ``` -------------------------------- ### Install Dependencies with Pipenv Source: https://github.com/google-wallet/rest-samples/blob/main/python/README.md Install project dependencies using pipenv after activating the virtual environment. Ensure this command is run from the directory containing the Pipfile. ```bash pipenv install ``` -------------------------------- ### Google Wallet PHP Demo Class Usage Source: https://github.com/google-wallet/rest-samples/blob/main/php/README.md This example demonstrates how to import and use a demo class for creating and managing Google Wallet passes. Ensure your Google Wallet issuer account ID and class/object suffixes are correctly set. ```php // Import the demo class require __DIR__ . '/demo_eventticket.php'; // Your Issuer account ID (@see Prerequisites) $issuerId = '3388000000000000000'; // Create a demo class instance $demo = new DemoEventTicket(); // Create a pass class $demo->createClass($issuerId, 'class_suffix'); // Update a pass class $demo->updateClass($issuerId, 'class_suffix'); // Patch a pass class $demo->patchClass($issuerId, 'class_suffix'); // Add a message to a pass class $demo->addClassMessage($issuerId, 'class_suffix', 'header', 'body'); // Create a pass object $demo->createObject($issuerId, 'class_suffix', 'object_suffix'); // Update a pass object $demo->updateObject($issuerId, 'object_suffix'); // Patch a pass object $demo->patchObject($issuerId, 'object_suffix'); // Add a message to a pass object $demo->addObjectMessage($issuerId, 'object_suffix', 'header', 'body'); // Expire a pass object $demo->expireObject($issuerId, 'object_suffix'); // Generate an Add to Google Wallet link that creates a new pass class and object $demo->createJWTNewObjects($issuerId, 'class_suffix', 'object_suffix'); // Generate an Add to Google Wallet link that references existing pass object(s) $demo->createJWTExistingObjects($issuerId); // Create pass objects in batch $demo->batchCreateObjects($issuerId, 'class_suffix'); ``` -------------------------------- ### Batch Create Gift Card Objects in Java Source: https://context7.com/google-wallet/rest-samples/llms.txt Batch create multiple gift card pass objects using the Google Wallet API for Java. This example demonstrates setting up a batch request and handling responses. ```java public void batchCreateObjects(String issuerId, String classSuffix) throws IOException { BatchRequest batch = service.batch(new HttpCredentialsAdapter(credentials)); JsonBatchCallback callback = new JsonBatchCallback() { public void onSuccess(GiftCardObject response, HttpHeaders responseHeaders) { System.out.println("Batch insert response: " + response.toString()); } public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) { System.out.println("Error: " + e.getMessage()); } }; for (int i = 0; i < 3; i++) { String objectSuffix = UUID.randomUUID().toString().replaceAll("[^\\w.-]", "_"); GiftCardObject batchObject = new GiftCardObject() .setId(String.format("%s.%s", issuerId, objectSuffix)) .setClassId(String.format("%s.%s", issuerId, classSuffix)) .setState("ACTIVE") .setCardNumber("Card number " + i) .setPin("1234") .setBalance(new Money().setMicros(20000000L).setCurrencyCode("USD")); service.giftcardobject().insert(batchObject).queue(batch, callback); } batch.execute(); } ``` -------------------------------- ### Batch Create Objects in Python Source: https://context7.com/google-wallet/rest-samples/llms.txt Batch create multiple pass objects in a single API call for improved performance. This example creates loyalty objects. ```python import uuid def batch_create_objects(client, issuer_id: str, class_suffix: str, count: int = 3): """Batch create multiple pass objects.""" batch = client.new_batch_http_request() for i in range(count): object_suffix = str(uuid.uuid4()).replace('-', '_') batch_object = { 'id': f'{issuer_id}.{object_suffix}', 'classId': f'{issuer_id}.{class_suffix}', 'state': 'ACTIVE', 'accountId': f'user{i}@example.com', 'accountName': f'User {i}', 'loyaltyPoints': { 'label': 'Points', 'balance': {'int': 100 * (i + 1)} }, 'barcode': { 'type': 'QR_CODE', 'value': f'LOYALTY{object_suffix}' } } batch.add(client.loyaltyobject().insert(body=batch_object)) # Execute all batch requests batch.execute() print('Batch complete') # Usage batch_create_objects(wallet.client, '1234567890', 'loyalty_class_01', count=10) ``` -------------------------------- ### Google Wallet Go Sample Usage Source: https://github.com/google-wallet/rest-samples/blob/main/go/README.md Demonstrates the typical workflow for interacting with Google Wallet API using Go. This includes creating pass classes and objects, expiring objects, and generating 'Add to Google Wallet' links. ```go // Create a demo type instance // Creates the authenticated HTTP client d := demoEventticket{} d.auth() // Create a pass class d.createClass(issuerId, classSuffix) // Create a pass object d.createObject(issuerId, classSuffix, objectSuffix) // Expire a pass object d.expireObject(issuerId, objectSuffix) // Create an "Add to Google Wallet" link // that generates a new pass class and object d.createJwtNewObjects(issuerId, classSuffix, objectSuffix) // Create an "Add to Google Wallet" link // that references existing pass classes and objects d.createJwtExistingObjects(issuerId) // Create pass objects in batch d.batchCreateObjects(issuerId, classSuffix) ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/google-wallet/rest-samples/blob/main/python/README.md Activate the virtual environment created in the previous step. This must be run in the same directory as the .venv folder. ```bash source .venv/bin/activate ``` -------------------------------- ### Google Wallet Node.js Demo Class Usage Source: https://github.com/google-wallet/rest-samples/blob/main/nodejs/README.md Import and instantiate a demo class to perform Google Wallet pass operations. Ensure environment variables like GOOGLE_APPLICATION_CREDENTIALS are set. ```javascript // Import the demo class const { DemoEventTicket } = require('./demo-eventticket'); // Create a demo class instance // Creates the authenticated HTTP client let demo = new DemoEventTicket(); // Create a pass class demo.createClass('issuer_id', 'class_suffix'); // Update a pass class demo.updateClass('issuer_id', 'class_suffix'); // Patch a pass class demo.patchClass('issuer_id', 'class_suffix'); // Add a message to a pass class demo.addClassMessage('issuer_id', 'class_suffix', 'header', 'body'); // Create a pass object demo.createObject('issuer_id', 'class_suffix', 'object_suffix'); // Update a pass object demo.updateObject('issuer_id', 'object_suffix'); // Patch a pass object demo.patchObject('issuer_id', 'object_suffix'); // Add a message to a pass object demo.addObjectMessage('issuer_id', 'object_suffix', 'header', 'body'); // Expire a pass object demo.expireObject('issuer_id', 'object_suffix'); // Generate an Add to Google Wallet link that creates a new pass class and object demo.createJwtNewObjects('issuer_id', 'class_suffix', 'object_suffix'); // Generate an Add to Google Wallet link that references existing pass object(s) demo.createJwtExistingObjects('issuer_id'); // Create pass objects in batch demo.batchCreateObjects('issuer_id', 'class_suffix'); ``` -------------------------------- ### XML Project Configuration for Google Wallet API Client Library Source: https://github.com/google-wallet/rest-samples/blob/main/dotnet/README.md This XML snippet shows how to include the Google Wallet API Client library in a .NET project. Update the file path to match your downloaded library location. ```xml ``` -------------------------------- ### Google Wallet Python Sample Usage Source: https://github.com/google-wallet/rest-samples/blob/main/python/README.md This Python code demonstrates how to use the Google Wallet demo classes to manage pass classes and objects. It covers creating, updating, patching, adding messages, expiring objects, generating JWT links, and batch object creation. Ensure you have set the GOOGLE_APPLICATION_CREDENTIALS environment variable. ```python # Import the demo class from .demo_eventticket import DemoEventTicket # Create a demo class instance # Creates the authenticated HTTP client demo = DemoEventTicket() # Create a pass class demo.create_class(issuer_id='issuer_id', class_suffix='class_suffix') # Update a pass class demo.update_class(issuer_id='issuer_id', class_suffix='class_suffix') # Patch a pass class demo.patch_class(issuer_id='issuer_id', class_suffix='class_suffix') # Add a message to a pass class demo.add_class_message(issuer_id='issuer_id', class_suffix='class_suffix', header='header', body='body') # Create a pass object demo.create_object(issuer_id='issuer_id', class_suffix='class_suffix', object_suffix='object_suffix') # Update a pass object demo.update_object(issuer_id='issuer_id', object_suffix='object_suffix') # Patch a pass object demo.patch_object(issuer_id='issuer_id', object_suffix='object_suffix') # Add a message to a pass object demo.add_object_message(issuer_id='issuer_id', object_suffix='object_suffix', header='header', body='body') # Expire a pass object demo.expire_object(issuer_id='issuer_id', object_suffix='object_suffix') # Create an "Add to Google Wallet" link # that generates a new pass class and object demo.create_jwt_new_objects(issuer_id='issuer_id', class_suffix='class_suffix', object_suffix='object_suffix') # Create an "Add to Google Wallet" link # that references existing pass classes and objects demo.create_jwt_existing_objects(issuer_id='issuer_id') # Create pass objects in batch demo.batch_create_objects(issuer_id='issuer_id', class_suffix='class_suffix') ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/google-wallet/rest-samples/blob/main/python/README.md Use this command to create a new virtual environment for your Python project. This isolates project dependencies. ```bash python3 -m venv .venv ``` -------------------------------- ### Create JWT for New Objects in Python Source: https://context7.com/google-wallet/rest-samples/llms.txt Generate an 'Add to Google Wallet' link that creates new loyalty pass classes and objects. This is the recommended method for distributing passes. Requires service account credentials and key file path. ```python # Python - Create JWT with New Objects from google.auth import jwt, crypt def create_jwt_new_objects(credentials, key_file_path: str, issuer_id: str, class_suffix: str, object_suffix: str) -> str: """Generate an 'Add to Google Wallet' link that creates new class and object.""" # Define the new class new_class = { 'id': f'{issuer_id}.{class_suffix}', 'issuerName': 'Baconrista Coffee', 'reviewStatus': 'UNDER_REVIEW', 'programName': 'Baconrista Rewards', 'programLogo': { 'sourceUri': { 'uri': 'https://example.com/logo.jpg' }, 'contentDescription': { 'defaultValue': { 'language': 'en-US', 'value': 'Logo description' } } } } # Define the new object new_object = { 'id': f'{issuer_id}.{object_suffix}', 'classId': f'{issuer_id}.{class_suffix}', 'state': 'ACTIVE', 'accountId': 'user123@example.com', 'accountName': 'Jane Doe', 'loyaltyPoints': { 'label': 'Points', 'balance': {'int': 500} }, 'barcode': { 'type': 'QR_CODE', 'value': 'LOYALTY123456' } } # Create JWT claims claims = { 'iss': credentials.service_account_email, 'aud': 'google', 'origins': ['www.example.com'], 'typ': 'savetowallet', 'payload': { 'loyaltyClasses': [new_class], 'loyaltyObjects': [new_object] } } # Sign the JWT with service account credentials 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('Add to Google Wallet link:', save_url) return save_url # Usage url = create_jwt_new_objects( wallet.credentials, '/path/to/key.json', '1234567890', 'loyalty_class_01', 'user_jane_doe' ) # Output: https://pay.google.com/gp/v/save/eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### Create Loyalty Pass Class (Python) Source: https://context7.com/google-wallet/rest-samples/llms.txt Creates a new loyalty card class, which serves as a template for loyalty pass objects. This function first checks if the class already exists to prevent duplicates. Requires an authenticated Wallet client. ```python # Python - Create Loyalty Class from googleapiclient.errors import HttpError def create_loyalty_class(client, issuer_id: str, class_suffix: str) -> str: """Create a loyalty card class.""" # Check if class already exists try: client.loyaltyclass().get( resourceId=f'{issuer_id}.{class_suffix}' ).execute() print(f'Class {issuer_id}.{class_suffix} already exists!') return f'{issuer_id}.{class_suffix}' except HttpError as e: if e.status_code != 404: print(e.error_details) return f'{issuer_id}.{class_suffix}' # Create new class new_class = { 'id': f'{issuer_id}.{class_suffix}', 'issuerName': 'Baconrista Coffee', 'reviewStatus': 'UNDER_REVIEW', 'programName': 'Baconrista Rewards', 'programLogo': { 'sourceUri': { 'uri': 'https://example.com/logo.jpg' }, 'contentDescription': { 'defaultValue': { 'language': 'en-US', 'value': 'Baconrista Rewards Logo' } } } } response = client.loyaltyclass().insert(body=new_class).execute() print('Class insert response:', response) return f'{issuer_id}.{class_suffix}' # Usage class_id = create_loyalty_class(wallet.client, '1234567890', 'loyalty_class_01') ``` -------------------------------- ### Authenticate with Google Cloud Service Account (Node.js) Source: https://context7.com/google-wallet/rest-samples/llms.txt Sets up an authenticated HTTP client using a Google Cloud service account for Google Wallet API interactions. The key file path can be specified via the GOOGLE_APPLICATION_CREDENTIALS environment variable. ```javascript // Node.js - Service Account Authentication const { google } = require('googleapis'); class WalletClient { constructor() { this.keyFilePath = process.env.GOOGLE_APPLICATION_CREDENTIALS || '/path/to/key.json'; const auth = new google.auth.GoogleAuth({ keyFile: this.keyFilePath, scopes: ['https://www.googleapis.com/auth/wallet_object.issuer'], }); this.credentials = require(this.keyFilePath); this.client = google.walletobjects({ version: 'v1', auth: auth, }); } } // Usage const wallet = new WalletClient(); ``` -------------------------------- ### Google Wallet API Operations in C# Source: https://github.com/google-wallet/rest-samples/blob/main/dotnet/README.md This snippet demonstrates various operations for managing Google Wallet pass classes and objects using C#. It covers creation, updates, patching, adding messages, and expiring objects. Ensure you have the Google Wallet API Client library configured. ```csharp // Create a demo class instance // Creates the authenticated HTTP client DemoEventTicket demo = new DemoEventTicket(); // Create a pass class demo.CreateClass("issuer_id", "class_suffix"); // Update a pass class demo.UpdateClass("issuer_id", "class_suffix"); // Patch a pass class demo.PatchClass("issuer_id", "class_suffix"); // Add a message to a pass class demo.AddClassMessage("issuer_id", "class_suffix", "header", "body"); // Create a pass object demo.CreateObject("issuer_id", "class_suffix", "object_suffix"); // Update a pass object demo.UpdateObject("issuer_id", "object_suffix"); // Patch a pass object demo.PatchObject("issuer_id", "object_suffix"); // Add a message to a pass object demo.AddObjectMessage("issuer_id", "object_suffix", "header", "body"); // Expire a pass object demo.ExpireObject("issuer_id", "object_suffix"); // Generate an Add to Google Wallet link that creates a new pass class and object demo.CreateJWTNewObjects("issuer_id", "class_suffix", "object_suffix"); // Generate an Add to Google Wallet link that references existing pass object(s) demo.CreateJWTExistingObjects("issuer_id"); // Create pass objects in batch demo.BatchCreateObjects("issuer_id", "class_suffix"); ``` -------------------------------- ### Authenticate with Google Cloud Service Account (Java) Source: https://context7.com/google-wallet/rest-samples/llms.txt Initializes an authenticated HTTP client using a Google Cloud service account for Google Wallet API calls. Ensure the GOOGLE_APPLICATION_CREDENTIALS environment variable points to your service account key file. ```java // Java - Service Account Authentication import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.walletobjects.*; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.FileInputStream; import java.util.List; public class WalletClient { public GoogleCredentials credentials; public Walletobjects service; public void auth() throws Exception { String keyFilePath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS"); credentials = GoogleCredentials.fromStream(new FileInputStream(keyFilePath)) .createScoped(List.of(WalletobjectsScopes.WALLET_OBJECT_ISSUER)); credentials.refresh(); service = new Walletobjects.Builder( GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("APPLICATION_NAME") .build(); } } ``` -------------------------------- ### Authenticate with Google Cloud Service Account (Python) Source: https://context7.com/google-wallet/rest-samples/llms.txt Establishes an authenticated HTTP client using a Google Cloud service account for accessing Google Wallet APIs. Ensure your service account key file path is correctly configured. ```python # Python - Service Account Authentication from googleapiclient.discovery import build from google.oauth2.service_account import Credentials class WalletClient: def __init__(self): self.key_file_path = '/path/to/service-account-key.json' self.credentials = Credentials.from_service_account_file( self.key_file_path, scopes=['https://www.googleapis.com/auth/wallet_object.issuer'] ) self.client = build('walletobjects', 'v1', credentials=self.credentials) # Usage wallet = WalletClient() # wallet.client is now ready for API calls ``` -------------------------------- ### Create Gift Card Object in Java Source: https://context7.com/google-wallet/rest-samples/llms.txt Use this Java snippet to create a new gift card pass object with balance tracking and PIN support. Ensure the Google Wallet API client is properly initialized. ```java // Java - Create Gift Card Object public String createGiftCardObject(String issuerId, String classSuffix, String objectSuffix) throws IOException { GiftCardObject newObject = new GiftCardObject() .setId(String.format("%s.%s", issuerId, objectSuffix)) .setClassId(String.format("%s.%s", issuerId, classSuffix)) .setState("ACTIVE") .setCardNumber("1234 5678 9012 3456") .setPin("1234") .setBalance(new Money().setMicros(20000000L).setCurrencyCode("USD")) // $20.00 .setBalanceUpdateTime(new DateTime().setDate("2024-01-15T10:30:00.00-05:00")) .setHeroImage( new Image() .setSourceUri(new ImageUri().setUri("https://example.com/giftcard-hero.jpg")) .setContentDescription( new LocalizedString().setDefaultValue( new TranslatedString().setLanguage("en-US").setValue("Gift card image") ) ) ) .setBarcode(new Barcode().setType("QR_CODE").setValue("GIFTCARD123456")); GiftCardObject response = service.giftcardobject().insert(newObject).execute(); System.out.println("Gift card created: " + response.getId()); return response.getId(); } ``` -------------------------------- ### Manage Google Wallet Passes with Java Source: https://github.com/google-wallet/rest-samples/blob/main/java/README.md Use these methods to create, update, patch, and add messages to Google Wallet pass classes and objects. Ensure the GOOGLE_APPLICATION_CREDENTIALS environment variable is set. ```java com.google.developers.wallet.rest.DemoEventTicket demo = new com.google.developers.wallet.rest.DemoEventTicket(); demo.createClass("issuer_id", "class_suffix"); demo.updateClass("issuer_id", "class_suffix"); demo.patchClass("issuer_id", "class_suffix"); demo.addClassMessage("issuer_id", "class_suffix", "header", "body"); demo.createObject("issuer_id", "class_suffix", "object_suffix"); demo.updateObject("issuer_id", "object_suffix"); demo.patchObject("issuer_id", "object_suffix"); demo.addObjectMessage("issuer_id", "object_suffix", "header", "body"); demo.expireObject("issuer_id", "object_suffix"); demo.createJWTNewObjects("issuer_id", "class_suffix", "object_suffix"); demo.createJWTExistingObjects("issuer_id"); demo.batchCreateObjects("issuer_id", "class_suffix"); ``` -------------------------------- ### Python - Patch Object to Add Link Source: https://context7.com/google-wallet/rest-samples/llms.txt Use this snippet to add a new promotional link to an existing loyalty object. It retrieves the current object, appends the new link to the linksModuleData, and then patches the object. ```python def patch_object_add_link(client, issuer_id: str, object_suffix: str) -> str: """Patch an object to add a new link.""" # Get existing object try: response = client.loyaltyobject().get( resourceId=f'{issuer_id}.{object_suffix}' ).execute() except HttpError as e: if e.status_code == 404: print(f'Object {issuer_id}.{object_suffix} not found!') return f'{issuer_id}.{object_suffix}' print(e.error_details) return f'{issuer_id}.{object_suffix}' existing_object = response # Build patch body with existing links plus new link patch_body = {} new_link = { 'uri': 'https://developers.google.com/wallet', 'description': 'New promotional link' } if existing_object.get('linksModuleData'): patch_body['linksModuleData'] = existing_object['linksModuleData'] else: patch_body['linksModuleData'] = {'uris': []} patch_body['linksModuleData']['uris'].append(new_link) response = client.loyaltyobject().patch( resourceId=f'{issuer_id}.{object_suffix}', body=patch_body ).execute() print('Object patch response:', response) return f'{issuer_id}.{object_suffix}' ``` -------------------------------- ### Create Loyalty Object in Python Source: https://context7.com/google-wallet/rest-samples/llms.txt This Python function creates a loyalty card object for a specific user. It first checks for the object's existence and handles potential HTTP errors. Requires the Google Wallet client, issuer ID, class suffix, and object suffix. ```python # Python - Create Loyalty Object def create_loyalty_object(client, issuer_id: str, class_suffix: str, object_suffix: str) -> str: """Create a loyalty card object for a specific user.""" # Check if object exists try: client.loyaltyobject().get( resourceId=f'{issuer_id}.{object_suffix}' ).execute() print(f'Object {issuer_id}.{object_suffix} already exists!') return f'{issuer_id}.{object_suffix}' except HttpError as e: if e.status_code != 404: print(e.error_details) return f'{issuer_id}.{object_suffix}' # Create new object new_object = { 'id': f'{issuer_id}.{object_suffix}', 'classId': f'{issuer_id}.{class_suffix}', 'state': 'ACTIVE', 'accountId': 'user123@example.com', 'accountName': 'Jane Doe', 'loyaltyPoints': { 'label': 'Points', 'balance': { 'int': 800 } }, 'heroImage': { 'sourceUri': { 'uri': 'https://example.com/hero.jpg' }, 'contentDescription': { 'defaultValue': { 'language': 'en-US', 'value': 'Hero image' } } }, 'barcode': { 'type': 'QR_CODE', 'value': 'LOYALTY123456' }, 'locations': [{ 'latitude': 37.424015499999996, 'longitude': -122.09259560000001 }], 'linksModuleData': { 'uris': [{ 'uri': 'http://maps.google.com/', 'description': 'Find a store', 'id': 'LINK_MODULE_URI_ID' }, { 'uri': 'tel:6505555555', 'description': 'Call us', 'id': 'LINK_MODULE_TEL_ID' }] }, 'textModulesData': [{ 'header': 'Member Benefits', 'body': 'Earn 1 point per $1 spent. Redeem 100 points for $5 off.', 'id': 'TEXT_MODULE_ID' }] } response = client.loyaltyobject().insert(body=new_object).execute() print('Object insert response:', response) return f'{issuer_id}.{object_suffix}' # Usage object_id = create_loyalty_object(wallet.client, '1234567890', 'loyalty_class_01', 'user_jane_doe') ``` -------------------------------- ### Create Event Ticket Class in Node.js Source: https://context7.com/google-wallet/rest-samples/llms.txt Use this function to create a new event ticket class. It checks if the class already exists before attempting creation. Requires the Google Wallet client, issuer ID, and a class suffix. ```javascript // Node.js - Create Event Ticket Class async function createEventTicketClass(client, issuerId, classSuffix) { // Check if class exists try { await client.eventticketclass.get({ resourceId: `${issuerId}.${classSuffix}` }); console.log(`Class ${issuerId}.${classSuffix} already exists!`); return `${issuerId}.${classSuffix}`; } catch (err) { if (err.response && err.response.status !== 404) { console.log(err); return `${issuerId}.${classSuffix}`; } } // Create new class const newClass = { 'eventId': `${issuerId}.${classSuffix}`, 'eventName': { 'defaultValue': { 'language': 'en-US', 'value': 'Google I/O 2024' } }, 'id': `${issuerId}.${classSuffix}`, 'issuerName': 'Google Events', 'reviewStatus': 'UNDER_REVIEW' }; const response = await client.eventticketclass.insert({ requestBody: newClass }); console.log('Class insert response:', response.data); return `${issuerId}.${classSuffix}`; } // Usage const classId = await createEventTicketClass(wallet.client, '1234567890', 'event_class_01'); ``` -------------------------------- ### Create JWT for New Objects in Node.js Source: https://context7.com/google-wallet/rest-samples/llms.txt Generates an 'Add to Google Wallet' link for creating new event ticket classes and objects. This Node.js snippet requires credentials including client email and private key. ```javascript // Node.js - Create JWT with New Objects const jwt = require('jsonwebtoken'); function createJwtNewObjects(credentials, issuerId, classSuffix, objectSuffix) { const newClass = { 'id': `${issuerId}.${classSuffix}`, 'issuerName': 'Event Organizer', 'reviewStatus': 'UNDER_REVIEW', 'eventName': { 'defaultValue': { 'language': 'en-US', 'value': 'Concert 2024' } } }; const newObject = { 'id': `${issuerId}.${objectSuffix}`, 'classId': `${issuerId}.${classSuffix}`, 'state': 'ACTIVE', 'ticketHolderName': 'John Smith', 'ticketNumber': 'TICKET-001', 'seatInfo': { 'seat': { 'defaultValue': { 'language': 'en-US', 'value': '42' } }, 'row': { 'defaultValue': { 'language': 'en-US', 'value': 'G' } }, 'section': { 'defaultValue': { 'language': 'en-US', 'value': '5' } } }, 'barcode': { 'type': 'QR_CODE', 'value': 'TICKET001' } }; const claims = { iss: credentials.client_email, aud: 'google', origins: ['www.example.com'], typ: 'savetowallet', payload: { eventTicketClasses: [newClass], eventTicketObjects: [newObject] } }; const token = jwt.sign(claims, credentials.private_key, { algorithm: 'RS256' }); const saveUrl = `https://pay.google.com/gp/v/save/${token}`; console.log('Add to Google Wallet link:', saveUrl); return saveUrl; } ``` -------------------------------- ### Create JWT for Existing Objects in Python Source: https://context7.com/google-wallet/rest-samples/llms.txt Generate an 'Add to Google Wallet' link for existing pass objects. This function combines multiple pass types into a single JWT. ```python def create_jwt_existing_objects(credentials, key_file_path: str, issuer_id: str) -> str: """Generate an 'Add to Google Wallet' link for existing pass objects.""" # Reference existing objects (multiple pass types can be combined) objects_to_add = { 'loyaltyObjects': [{ 'id': f'{issuer_id}.LOYALTY_OBJECT_SUFFIX', 'classId': f'{issuer_id}.LOYALTY_CLASS_SUFFIX' }], 'eventTicketObjects': [{ 'id': f'{issuer_id}.EVENT_OBJECT_SUFFIX', 'classId': f'{issuer_id}.EVENT_CLASS_SUFFIX' }], 'giftCardObjects': [{ 'id': f'{issuer_id}.GIFT_CARD_OBJECT_SUFFIX', 'classId': f'{issuer_id}.GIFT_CARD_CLASS_SUFFIX' }], 'offerObjects': [{ 'id': f'{issuer_id}.OFFER_OBJECT_SUFFIX', 'classId': f'{issuer_id}.OFFER_CLASS_SUFFIX' }] } # Create JWT claims claims = { 'iss': credentials.service_account_email, 'aud': 'google', 'origins': ['www.example.com'], 'typ': 'savetowallet', 'payload': objects_to_add } # Sign the JWT 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('Add to Google Wallet link:', save_url) return save_url ``` -------------------------------- ### Pass Type API Endpoints Reference in Python Source: https://context7.com/google-wallet/rest-samples/llms.txt This Python snippet lists the client methods available for interacting with different pass types in the Google Wallet API. Use these to perform class and object operations for each pass type. ```python # Pass Type API Endpoints Reference # Loyalty Cards client.loyaltyclass() # Class operations client.loyaltyobject() # Object operations # Event Tickets client.eventticketclass() client.eventticketobject() # Flight Boarding Passes client.flightclass() client.flightobject() # Gift Cards client.giftcardclass() client.giftcardobject() # Offers/Promotions client.offerclass() client.offerobject() # Transit Passes client.transitclass() client.transitobject() # Generic Passes (flexible format) client.genericclass() client.genericobject() ``` -------------------------------- ### Create Event Ticket Object Source: https://context7.com/google-wallet/rest-samples/llms.txt Use this Node.js function to create a new event ticket object. It first checks if the object already exists and logs a message if it does. Ensure the client is properly initialized. ```javascript // Node.js - Create Event Ticket Object async function createEventTicketObject(client, issuerId, classSuffix, objectSuffix) { // Check if object exists try { await client.eventticketobject.get({ resourceId: `${issuerId}.${objectSuffix}` }); console.log(`Object ${issuerId}.${objectSuffix} already exists!`); return `${issuerId}.${objectSuffix}`; } catch (err) { if (err.response && err.response.status !== 404) { return `${issuerId}.${objectSuffix}`; } } const newObject = { 'id': `${issuerId}.${objectSuffix}`, 'classId': `${issuerId}.${classSuffix}`, 'state': 'ACTIVE', 'seatInfo': { 'seat': { 'defaultValue': { 'language': 'en-US', 'value': '42' } }, 'row': { 'defaultValue': { 'language': 'en-US', 'value': 'G3' } }, 'section': { 'defaultValue': { 'language': 'en-US', 'value': '5' } }, 'gate': { 'defaultValue': { 'language': 'en-US', 'value': 'A' } } }, 'ticketHolderName': 'John Smith', 'ticketNumber': 'TICKET-2024-001', 'barcode': { 'type': 'QR_CODE', 'value': 'TICKET2024001' }, 'heroImage': { 'sourceUri': { 'uri': 'https://example.com/event-hero.jpg' }, 'contentDescription': { 'defaultValue': { 'language': 'en-US', 'value': 'Event hero image' } } } }; const response = await client.eventticketobject.insert({ requestBody: newObject }); console.log('Object insert response:', response.data); return `${issuerId}.${objectSuffix}`; } ``` -------------------------------- ### Python - Add Message to Loyalty Class Source: https://context7.com/google-wallet/rest-samples/llms.txt This function adds a notification message to all passes belonging to a specific loyalty class. It first verifies the class exists before attempting to add the message. ```python # Python - Add Message to Class def add_class_message(client, issuer_id: str, class_suffix: str, header: str, body: str) -> str: """Add a message to all passes of this class.""" # Verify class exists try: client.loyaltyclass().get( resourceId=f'{issuer_id}.{class_suffix}' ).execute() except HttpError as e: if e.status_code == 404: print(f'Class {issuer_id}.{class_suffix} not found!') return f'{issuer_id}.{class_suffix}' print(e.error_details) return f'{issuer_id}.{class_suffix}' response = client.loyaltyclass().addmessage( resourceId=f'{issuer_id}.{class_suffix}', body={ 'message': { 'header': header, 'body': body } } ).execute() print('Class addMessage response:', response) return f'{issuer_id}.{class_suffix}' # Usage add_class_message(wallet.client, '1234567890', 'loyalty_class_01', 'Double Points Weekend!', 'Earn 2x points on all purchases this weekend.') ``` -------------------------------- ### Expire Loyalty Object in Go Source: https://context7.com/google-wallet/rest-samples/llms.txt Use this snippet to set the state of a loyalty object to 'EXPIRED'. Ensure you have the necessary service object and object identifiers. ```go // Go - Expire Object func (d *demoLoyalty) expireObject(issuerId, objectSuffix string) { loyaltyObject := &walletobjects.LoyaltyObject{ State: "EXPIRED", } res, err := d.service.Loyaltyobject.Patch( fmt.Sprintf("%s.%s", issuerId, objectSuffix), loyaltyObject, ).Do() if err != nil { log.Fatalf("Unable to patch object: %v", err) } else { fmt.Printf("Object expiration id: %s\n", res.Id) } } ``` -------------------------------- ### Update Pass Class (Full Replace) Source: https://context7.com/google-wallet/rest-samples/llms.txt This Python function completely replaces an existing pass class with new attributes. It first retrieves the current class, modifies it, and then updates it. Ensure the `reviewStatus` is set to 'UNDER_REVIEW' or 'DRAFT' for updates. ```python # Python - Update Class (Full Replace) def update_class(client, issuer_id: str, class_suffix: str) -> str: """Update a class - Warning: replaces all existing attributes!""" # Get existing class try: response = client.loyaltyclass().get( resourceId=f'{issuer_id}.{class_suffix}' ).execute() except HttpError as e: if e.status_code == 404: print(f'Class {issuer_id}.{class_suffix} not found!') return f'{issuer_id}.{class_suffix}' print(e.error_details) return f'{issuer_id}.{class_suffix}' # Modify the class updated_class = response updated_class['homepageUri'] = { 'uri': 'https://developers.google.com/wallet', 'description': 'Visit our homepage' } # Note: reviewStatus must be 'UNDER_REVIEW' or 'DRAFT' for updates updated_class['reviewStatus'] = 'UNDER_REVIEW' response = client.loyaltyclass().update( resourceId=f'{issuer_id}.{class_suffix}', body=updated_class ).execute() print('Class update response:', response) return f'{issuer_id}.{class_suffix}' ``` -------------------------------- ### Patch Pass Class (Partial Update) Source: https://context7.com/google-wallet/rest-samples/llms.txt This Python function partially updates a pass class by modifying only the specified fields. It first verifies the class exists and then applies the patch. Only include fields intended for modification in the `patch_body`. ```python # Python - Patch Class (Partial Update) def patch_class(client, issuer_id: str, class_suffix: str) -> str: """Patch a class - only updates specified fields.""" # Verify class exists try: client.loyaltyclass().get( resourceId=f'{issuer_id}.{class_suffix}' ).execute() except HttpError as e: if e.status_code == 404: print(f'Class {issuer_id}.{class_suffix} not found!') return f'{issuer_id}.{class_suffix}' print(e.error_details) return f'{issuer_id}.{class_suffix}' # Patch body - only include fields to update patch_body = { 'homepageUri': { 'uri': 'https://developers.google.com/wallet', 'description': 'Homepage description' }, 'reviewStatus': 'UNDER_REVIEW' } response = client.loyaltyclass().patch( resourceId=f'{issuer_id}.{class_suffix}', body=patch_body ).execute() print('Class patch response:', response) return f'{issuer_id}.{class_suffix}' ``` -------------------------------- ### Python - Expire Loyalty Object Source: https://context7.com/google-wallet/rest-samples/llms.txt This function marks a loyalty pass object as expired, making it visually invalid in the user's wallet. It first confirms the object exists before applying the expiration state. ```python # Python - Expire Object def expire_object(client, issuer_id: str, object_suffix: str) -> str: """Expire a pass object.""" # Verify object exists try: client.loyaltyobject().get( resourceId=f'{issuer_id}.{object_suffix}' ).execute() except HttpError as e: if e.status_code == 404: print(f'Object {issuer_id}.{object_suffix} not found!') return f'{issuer_id}.{object_suffix}' print(e.error_details) return f'{issuer_id}.{object_suffix}' # Patch the object state to EXPIRED patch_body = {'state': 'EXPIRED'} response = client.loyaltyobject().patch( resourceId=f'{issuer_id}.{object_suffix}', body=patch_body ).execute() print('Object expiration response:', response) return f'{issuer_id}.{object_suffix}' # Usage expire_object(wallet.client, '1234567890', 'expired_user_pass') ``` -------------------------------- ### Python - Add Message to Loyalty Object Source: https://context7.com/google-wallet/rest-samples/llms.txt Use this snippet to add a notification message to a specific loyalty pass object. It checks for the object's existence before sending the message payload. ```python # Python - Add Message to Object def add_object_message(client, issuer_id: str, object_suffix: str, header: str, body: str) -> str: """Add a message to a specific pass object.""" # Verify object exists try: client.loyaltyobject().get( resourceId=f'{issuer_id}.{object_suffix}' ).execute() except HttpError as e: if e.status_code == 404: print(f'Object {issuer_id}.{object_suffix} not found!') return f'{issuer_id}.{object_suffix}' print(e.error_details) return f'{issuer_id}.{object_suffix}' response = client.loyaltyobject().addmessage( resourceId=f'{issuer_id}.{object_suffix}', body={ 'message': { 'header': header, 'body': body } } ).execute() print('Object addMessage response:', response) return f'{issuer_id}.{object_suffix}' # Usage add_object_message(wallet.client, '1234567890', 'user_jane_doe', 'Congrats Jane!', 'You just reached Gold status!') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.