Addition of batch pass creation examples

* Updated .NET and Java file names to be consistent
* Corrected indentation in .NET files
* Added missing quotes in HTTP request bodies
* Updated gradle version for Java examples
* Added missing JSON conversion for Java HTTP requests
* Added code to generate batch statements
This commit is contained in:
Nick Alteen
2022-09-01 13:11:25 -04:00
parent a1f4cce7c6
commit 5a1ab2a455
57 changed files with 5608 additions and 1643 deletions

10
.gitignore vendored
View File

@@ -2,6 +2,7 @@
.DS_Store
.vscode
*.code-workspace
testing/
# Node.js
node_modules
@@ -15,12 +16,18 @@ build
local.properties
.classpath
.project
java/lib/
# See: https://developers.google.com/wallet/generic/resources/libraries
java/lib/libwalletobjects_public_java_lib_v1.jar
# Python
*.pyc
__pycache__
.venv/
Pipfile.lock
*.yapf
.python-version
# .NET
bin
@@ -32,6 +39,9 @@ obj
vendor
composer.lock
# See: https://developers.google.com/wallet/generic/resources/libraries
php/lib/Walletobjects.php
# Ruby
Gemfile.lock

View File

@@ -3,7 +3,7 @@
This project contains samples for using the [Google Wallet REST APIs](https://developers.google.com/wallet/) in the following languages:
- Java
- C#
- C#
- JavaScript (Node.js)
- PHP
- Python
@@ -19,4 +19,4 @@ Each sample demonstrates the following:
## Contributing
Please note that the samples are automatically generated using templates found in the "templates" directory, where you will also find the "generate.py" script that generates the samples. If contributing any changes, please work on the files in this directory.
Please note that the samples are automatically generated using templates found in the "templates" directory, where you will also find the "generate.py" script that generates the samples. If contributing any changes, please work on the files in this directory.

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-eventTicket-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -96,7 +98,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -268,6 +270,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -331,3 +334,165 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
kind = "walletobjects#barcode",
type = "qrCode",
value = "Test QR Code"
},
state = "active",
seatInfo = new
{
kind = "walletobjects#eventSeat",
seat = new
{
kind = "walletobjects#localizedString",
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "42"
}
},
row = new
{
kind = "walletobjects#localizedString",
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "G3"
}
},
section = new
{
kind = "walletobjects#localizedString",
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "5"
}
},
gate = new
{
kind = "walletobjects#localizedString",
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "A"
}
}
},
ticketHolderName = "Test ticket holder name",
ticketNumber = "Test ticket number",
locations = new object[]
{
new
{
kind = "walletobjects#latLongPoint",
latitude = 37.424015499999996,
longitude = -122.09259560000001
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/eventTicketObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-flight-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -109,7 +111,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -245,6 +247,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -308,3 +311,129 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
kind = "walletobjects#barcode",
type = "qrCode",
value = "Test QR Code"
},
state = "active",
passengerName = "Test passenger name",
reservationInfo = new
{
confirmationCode = "Test confirmation code"
},
boardingAndSeatingInfo = new
{
seatNumber = "42",
boardingGroup = "B"
},
locations = new object[]
{
new
{
kind = "walletobjects#latLongPoint",
latitude = 37.424015499999996,
longitude = -122.09259560000001
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/flightObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-generic-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -87,7 +89,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -236,6 +238,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -299,3 +302,142 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
kind = "walletobjects#barcode",
type = "qrCode",
value = "Test QR Code"
},
genericType = "GENERIC_TYPE_UNSPECIFIED",
hexBackgroundColor = "#4285f4",
logo = new
{
sourceUri = new
{
uri = "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"
}
},
cardTitle = new
{
defaultValue = new
{
language = "en-US",
value = "Testing Generic Title"
}
},
header = new
{
defaultValue = new
{
language = "en-US",
value = "Testing Generic Header"
}
},
subheader = new
{
defaultValue = new
{
language = "en",
value = "Testing Generic Sub Header"
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/genericObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-giftCard-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -90,7 +92,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -227,6 +229,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -290,3 +293,130 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
kind = "walletobjects#barcode",
type = "qrCode",
value = "Test QR Code"
},
cardNumber = "Test card number",
cardPin = "Test card pin",
balance = new
{
kind = "walletobjects#money",
micros = 20000000,
currencyCode = "USD"
},
balanceUpdateTime = new
{
date = "2020-04-12T16:20:50.52Z"
},
locations = new object[]
{
new
{
kind = "walletobjects#latLongPoint",
latitude = 37.424015499999996,
longitude = -122.09259560000001
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/giftCardObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-loyalty-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -98,7 +100,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -234,6 +236,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -297,3 +300,129 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
kind = "walletobjects#barcode",
type = "qrCode",
value = "Test QR Code"
},
state = "active",
accountId = "Test account id",
accountName = "Test account name",
loyaltyPoints = new
{
balance = new
{
@string = "800"
},
label = "Points"
},
locations = new object[]
{
new
{
kind = "walletobjects#latLongPoint",
latitude = 37.424015499999996,
longitude = -122.09259560000001
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/loyaltyObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-offer-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -91,7 +93,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -228,6 +230,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -291,3 +294,130 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
type = "qrCode",
value = "Testing Offers QR Code"
},
state = "active",
validTimeInterval = new
{
kind = "walletobjects#timeInterval",
start = new
{
date = "2023-06-12T23:20:50.52Z"
},
end = new
{
date = "2023-12-12T23:20:50.52Z"
}
},
locations = new object[]
{
new
{
kind = "walletobjects#latLongPoint",
latitude = 37.424015499999996,
longitude = -122.09259560000001
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/offerObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-transit-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -99,7 +101,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -290,6 +292,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -353,3 +356,184 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
{
new
{
header = "Test text module header",
body = "Test text module body"
}
},
linksModuleData = new
{
uris = new object[]
{
new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
},
new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
}
}
}
},
barcode = new
{
kind = "walletobjects#barcode",
type = "qrCode",
value = "Test QR Code"
},
passengerType = "singlePassenger",
passengerNames = "Test passenger names",
ticketLeg = new
{
originStationCode = "LA",
originName = new
{
kind = "walletobjects#localizedString",
translatedValues = new object[]
{
new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "Test translated origin name"
}
},
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "Test default origin name"
}
},
destinationStationCode = "SFO",
destinationName = new
{
kind = "walletobjects#localizedString",
translatedValues = new object[]
{
new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "Test translated destination name"
}
},
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "Test default destination name"
}
},
departureDateTime = "2020-04-12T16:20:50.52Z",
arrivalDateTime = "2020-04-12T20:20:50.52Z",
fareName = new
{
kind = "walletobjects#localizedString",
translatedValues = new object[]
{
new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "Test translated fare name"
}
},
defaultValue = new
{
kind = "walletobjects#translatedString",
language = "en-us",
value = "Test default fare name"
}
}
},
locations = new object[]
{
new
{
kind = "walletobjects#latLongPoint",
latitude = 37.424015499999996,
longitude = -122.09259560000001
}
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/transitObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -3,9 +3,9 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>wallet_rest_samples</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>wallet_rest_samples</RootNamespace>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -8,8 +8,8 @@ Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{
"id": issuer-id.user-id,
"classId": issuer-id.class-id,
"id": "issuer-id.user-id",
"classId": "issuer-id.class-id",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",

View File

@@ -10,11 +10,15 @@ repositories {
}
dependencies {
// Replace with path to your local download of the Google Wallet library
implementation files('lib/libwalletobjects_public_java_lib_v1.jar')
implementation 'com.auth0:java-jwt:3.19.1'
implementation 'com.auth0:jwks-rsa:0.9.0'
implementation 'com.google.apis:google-api-services-oauth2:v1-rev20190313-1.30.3'
implementation 'com.google.api-client:google-api-client:2.0.0'
implementation 'com.google.api-client:google-api-client:1.25.0'
implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0'
implementation 'com.google.guava:guava:r05'
implementation 'com.google.api-client:google-api-client:1.19.1'
implementation 'com.squareup.okhttp3:okhttp:4.3.1'
implementation 'javax.json:javax.json-api:1.1'
implementation 'org.glassfish:javax.json:1.1'
}

Binary file not shown.

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

275
java/gradlew vendored
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright 2015 the original author or authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,67 +17,101 @@
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
@@ -106,80 +140,101 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

14
java/gradlew.bat vendored
View File

@@ -14,7 +14,7 @@
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -25,7 +25,7 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -75,13 +75,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View File

@@ -1,2 +1 @@
rootProject.name = 'wallet-samples'

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,9 +35,14 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoEventticket {
public class DemoEventTicket {
public static void main(String[] args) throws Exception {
/*
* keyFilePath - Path to service account key file from Google Cloud Console
@@ -70,10 +78,12 @@ public class DemoEventticket {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -333,10 +343,73 @@ public class DemoEventticket {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<EventTicketObject> callback = new JsonBatchCallback<EventTicketObject>() {
// Invoked if the request was successful
public void onSuccess(EventTicketObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
EventTicketObject eventTicketObject = new EventTicketObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/events/rest/v1/eventticketobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE");;
client.eventticketobject().insert(eventTicketObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoFlight {
@@ -70,10 +78,12 @@ public class DemoFlight {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -315,10 +325,75 @@ public class DemoFlight {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<FlightObject> callback = new JsonBatchCallback<FlightObject>() {
// Invoked if the request was successful
public void onSuccess(FlightObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
FlightObject flightObject = new FlightObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/boarding-passes/rest/v1/flightobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE")
.setPassengerName("NAME")
.setReservationInfo(new ReservationInfo());;
client.flightobject().insert(flightObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoGeneric {
@@ -70,10 +78,12 @@ public class DemoGeneric {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -306,10 +316,74 @@ public class DemoGeneric {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<GenericObject> callback = new JsonBatchCallback<GenericObject>() {
// Invoked if the request was successful
public void onSuccess(GenericObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
GenericObject genericObject = new GenericObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/generic/rest/v1/genericobject
.setId(objectId)
.setClassId(classId)
.setCardTitle(new LocalizedString().setDefaultValue(new TranslatedString().setLanguage("en-US").setValue("TITLE")))
.setHeader(new LocalizedString().setDefaultValue(new TranslatedString().setLanguage("en-US").setValue("HEADER")));;
client.genericobject().insert(genericObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,9 +35,14 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoGiftcard {
public class DemoGiftCard {
public static void main(String[] args) throws Exception {
/*
* keyFilePath - Path to service account key file from Google Cloud Console
@@ -70,10 +78,12 @@ public class DemoGiftcard {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -301,10 +311,74 @@ public class DemoGiftcard {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<GiftCardObject> callback = new JsonBatchCallback<GiftCardObject>() {
// Invoked if the request was successful
public void onSuccess(GiftCardObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
GiftCardObject giftCardObject = new GiftCardObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE")
.setCardNumber("CARD_NUMBER");;
client.giftcardobject().insert(giftCardObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoLoyalty {
@@ -70,10 +78,12 @@ public class DemoLoyalty {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -306,10 +316,73 @@ public class DemoLoyalty {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<LoyaltyObject> callback = new JsonBatchCallback<LoyaltyObject>() {
// Invoked if the request was successful
public void onSuccess(LoyaltyObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
LoyaltyObject loyaltyObject = new LoyaltyObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE");;
client.loyaltyobject().insert(loyaltyObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoOffer {
@@ -70,10 +78,12 @@ public class DemoOffer {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -301,10 +311,73 @@ public class DemoOffer {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<OfferObject> callback = new JsonBatchCallback<OfferObject>() {
// Invoked if the request was successful
public void onSuccess(OfferObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
OfferObject offerObject = new OfferObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/offers/rest/v1/offerobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE");;
client.offerobject().insert(offerObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoTransit {
@@ -70,10 +78,12 @@ public class DemoTransit {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -351,10 +361,74 @@ public class DemoTransit {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<TransitObject> callback = new JsonBatchCallback<TransitObject>() {
// Invoked if the request was successful
public void onSuccess(TransitObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
TransitObject transitObject = new TransitObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE")
.setTripType("ONE_WAY");;
client.transitobject().insert(transitObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -192,8 +194,8 @@ async function main() {
}
]
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -217,7 +219,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -245,13 +247,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -284,8 +286,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -298,4 +300,137 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"seatInfo": {
"kind": "walletobjects#eventSeat",
"seat": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "42"
}
},
"row": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "G3"
}
},
"section": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "5"
}
},
"gate": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "A"
}
}
},
"ticketHolderName": "Test ticket holder name",
"ticketNumber": "Test ticket number",
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/eventTicketObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -174,8 +176,8 @@ async function main() {
}
]
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -199,7 +201,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -227,13 +229,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -266,8 +268,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -280,4 +282,108 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"passengerName": "Test passenger name",
"reservationInfo": {
"confirmationCode": "Test confirmation code"
},
"boardingAndSeatingInfo": {
"seatNumber": "42",
"boardingGroup": "B"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/flightObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -165,8 +167,8 @@ async function main() {
}
}
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -190,7 +192,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -218,13 +220,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -257,8 +259,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -271,4 +273,117 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"genericType": "GENERIC_TYPE_UNSPECIFIED",
"hexBackgroundColor": "#4285f4",
"logo": {
"sourceUri": {
"uri": "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"
}
},
"cardTitle": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Title"
}
},
"header": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Header"
}
},
"subheader": {
"defaultValue": {
"language": "en",
"value": "Testing Generic Sub Header"
}
}
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/genericObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -160,8 +162,8 @@ async function main() {
}
]
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -185,7 +187,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -213,13 +215,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -252,8 +254,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -266,4 +268,109 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"cardNumber": "Test card number",
"cardPin": "Test card pin",
"balance": {
"kind": "walletobjects#money",
"micros": 20000000,
"currencyCode": "USD"
},
"balanceUpdateTime": {
"date": "2020-04-12T16:20:50.52Z"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/giftCardObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -165,8 +167,8 @@ async function main() {
}
]
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -190,7 +192,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -218,13 +220,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -257,8 +259,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -271,4 +273,108 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"accountId": "Test account id",
"accountName": "Test account name",
"loyaltyPoints": {
"balance": {
"string": "800"
},
"label": "Points"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/loyaltyObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -160,8 +162,8 @@ async function main() {
}
]
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -185,7 +187,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -213,13 +215,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -252,8 +254,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -266,4 +268,108 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"type": "qrCode",
"value": "Testing Offers QR Code"
},
"state": "active",
"validTimeInterval": {
"kind": "walletobjects#timeInterval",
"start": {
"date": "2023-06-12T23:20:50.52Z"
},
"end": {
"date": "2023-12-12T23:20:50.52Z"
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/offerObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -210,8 +212,8 @@ async function main() {
}
]
};
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -235,7 +237,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -263,13 +265,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -302,8 +304,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -316,4 +318,152 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = {
"id": objectId,
"classId": `${issuerId}.${classId}`,
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"passengerType": "singlePassenger",
"passengerNames": "Test passenger names",
"ticketLeg": {
"originStationCode": "LA",
"originName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated origin name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default origin name"
}
},
"destinationStationCode": "SFO",
"destinationName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated destination name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default destination name"
}
},
"departureDateTime": "2020-04-12T16:20:50.52Z",
"arrivalDateTime": "2020-04-12T20:20:50.52Z",
"fareName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated fare name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default fare name"
}
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/transitObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -310,3 +312,47 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$eventTicketObject = new Google_Service_Walletobjects_EventTicketObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/events/rest/v1/eventticketobject
$eventTicketObject->setId($objectId);
$eventTicketObject->setClassId("$issuerId.$classId");
$eventTicketObject->setState("ACTIVE");
$batch->add($service->eventticketobject->insert($eventTicketObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -292,3 +294,49 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$flightObject = new Google_Service_Walletobjects_FlightObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/boarding-passes/rest/v1/flightobject
$flightObject->setId($objectId);
$flightObject->setClassId("$issuerId.$classId");
$flightObject->setState("ACTIVE");
$flightObject->setPassengerName("NAME");
$flightObject->setReservationInfo(new Google_Service_Walletobjects_ReservationInfo());
$batch->add($service->flightobject->insert($flightObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -283,3 +285,48 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$genericObject = new Google_Service_Walletobjects_GenericObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/generic/rest/v1/genericobject
$genericObject->setId($objectId);
$genericObject->setClassId("$issuerId.$classId");
$genericObject->setCardTitle(new LocalizedString().setDefaultValue(new TranslatedString().setLanguage("en-US").setValue("TITLE")));
$genericObject->setHeader(new LocalizedString().setDefaultValue(new TranslatedString().setLanguage("en-US").setValue("HEADER")));
$batch->add($service->genericobject->insert($genericObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -278,3 +280,48 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$giftCardObject = new Google_Service_Walletobjects_GiftCardObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardobject
$giftCardObject->setId($objectId);
$giftCardObject->setClassId("$issuerId.$classId");
$giftCardObject->setState("ACTIVE");
$giftCardObject->setCardNumber("CARD_NUMBER");
$batch->add($service->giftcardobject->insert($giftCardObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -283,3 +285,47 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$loyaltyObject = new Google_Service_Walletobjects_LoyaltyObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
$loyaltyObject->setId($objectId);
$loyaltyObject->setClassId("$issuerId.$classId");
$loyaltyObject->setState("ACTIVE");
$batch->add($service->loyaltyobject->insert($loyaltyObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -278,3 +280,47 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$offerObject = new Google_Service_Walletobjects_OfferObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/offers/rest/v1/offerobject
$offerObject->setId($objectId);
$offerObject->setClassId("$issuerId.$classId");
$offerObject->setState("ACTIVE");
$batch->add($service->offerobject->insert($offerObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -328,3 +330,48 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$transitObject = new Google_Service_Walletobjects_TransitObject();
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/transit-passes/qr-code/rest/v1/transitobject
$transitObject->setId($objectId);
$transitObject->setClassId("$issuerId.$classId");
$transitObject->setState("ACTIVE");
$transitObject->setTripType("ONE_WAY");
$batch->add($service->transitobject->insert($transitObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-eventTicket-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,20 +70,20 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"eventName": {
"defaultValue": {
"language": "en-US",
"value": "Test event name"
}
},
"reviewStatus": "underReview"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"eventName": {
"defaultValue": {
"language": "en-US",
"value": "Test event name"
}
},
"reviewStatus": "underReview"
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -92,106 +95,106 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"seatInfo": {
"kind": "walletobjects#eventSeat",
"seat": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "42"
}
},
"row": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "G3"
}
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"section": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "5"
}
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"gate": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "A"
}
}
},
"ticketHolderName": "Test ticket holder name",
"ticketNumber": "Test ticket number",
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
"state": "active",
"seatInfo": {
"kind": "walletobjects#eventSeat",
"seat": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "42"
}
},
"row": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "G3"
}
},
"section": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "5"
}
},
"gate": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "A"
}
}
},
"ticketHolderName": "Test ticket holder name",
"ticketNumber": "Test ticket number",
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -202,17 +205,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"eventTicketObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"eventTicketObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -238,16 +241,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -263,20 +266,150 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"seatInfo": {
"kind": "walletobjects#eventSeat",
"seat": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "42"
}
},
"row": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "G3"
}
},
"section": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "5"
}
},
"gate": {
"kind": "walletobjects#localizedString",
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "A"
}
}
},
"ticketHolderName": "Test ticket holder name",
"ticketNumber": "Test ticket number",
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/eventTicketObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-flight-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,31 +70,31 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"destination": {
"airportIataCode": "SFO",
"gate": "C3",
"terminal": "2"
},
"flightHeader": {
"carrier": {
"carrierIataCode": "LX"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"destination": {
"airportIataCode": "SFO",
"gate": "C3",
"terminal": "2"
},
"flightNumber": "123"
},
"origin": {
"airportIataCode": "LAX",
"gate": "A2",
"terminal": "1"
},
"localScheduledDepartureDateTime": "2023-07-02T15:30:00",
"reviewStatus": "underReview"
"flightHeader": {
"carrier": {
"carrierIataCode": "LX"
},
"flightNumber": "123"
},
"origin": {
"airportIataCode": "LAX",
"gate": "A2",
"terminal": "1"
},
"localScheduledDepartureDateTime": "2023-07-02T15:30:00",
"reviewStatus": "underReview"
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -103,77 +106,77 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"passengerName": "Test passenger name",
"reservationInfo": {
"confirmationCode": "Test confirmation code"
},
"boardingAndSeatingInfo": {
"seatNumber": "42",
"boardingGroup": "B"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"passengerName": "Test passenger name",
"reservationInfo": {
"confirmationCode": "Test confirmation code"
},
"boardingAndSeatingInfo": {
"seatNumber": "42",
"boardingGroup": "B"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -184,17 +187,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"flightObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"flightObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -220,16 +223,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -245,20 +248,121 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"passengerName": "Test passenger name",
"reservationInfo": {
"confirmationCode": "Test confirmation code"
},
"boardingAndSeatingInfo": {
"seatNumber": "42",
"boardingGroup": "B"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/flightObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-generic-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,13 +70,13 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/genericClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name"
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -85,86 +88,86 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/genericObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"genericType": "GENERIC_TYPE_UNSPECIFIED",
"hexBackgroundColor": "#4285f4",
"logo": {
"sourceUri": {
"uri": "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"
}
},
"cardTitle": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Title"
}
},
"header": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Header"
}
},
"subheader": {
"defaultValue": {
"language": "en",
"value": "Testing Generic Sub Header"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"genericType": "GENERIC_TYPE_UNSPECIFIED",
"hexBackgroundColor": "#4285f4",
"logo": {
"sourceUri": {
"uri": "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"
}
},
"cardTitle": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Title"
}
},
"header": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Header"
}
},
"subheader": {
"defaultValue": {
"language": "en",
"value": "Testing Generic Sub Header"
}
}
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -175,17 +178,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"genericObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"genericObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -211,16 +214,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -236,20 +239,130 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"genericType": "GENERIC_TYPE_UNSPECIFIED",
"hexBackgroundColor": "#4285f4",
"logo": {
"sourceUri": {
"uri": "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"
}
},
"cardTitle": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Title"
}
},
"header": {
"defaultValue": {
"language": "en-US",
"value": "Testing Generic Header"
}
},
"subheader": {
"defaultValue": {
"language": "en",
"value": "Testing Generic Sub Header"
}
}
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/genericObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-giftCard-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,16 +70,16 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"merchantName": "Test merchant name",
"allowMultipleUsersPerObject": "true",
"reviewStatus": "underReview"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"merchantName": "Test merchant name",
"allowMultipleUsersPerObject": "true",
"reviewStatus": "underReview"
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -88,78 +91,78 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"cardNumber": "Test card number",
"cardPin": "Test card pin",
"balance": {
"kind": "walletobjects#money",
"micros": 20000000,
"currencyCode": "USD"
},
"balanceUpdateTime": {
"date": "2020-04-12T16:20:50.52Z"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"cardNumber": "Test card number",
"cardPin": "Test card pin",
"balance": {
"kind": "walletobjects#money",
"micros": 20000000,
"currencyCode": "USD"
},
"balanceUpdateTime": {
"date": "2020-04-12T16:20:50.52Z"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -170,17 +173,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"giftCardObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"giftCardObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -206,16 +209,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -231,20 +234,122 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"cardNumber": "Test card number",
"cardPin": "Test card pin",
"balance": {
"kind": "walletobjects#money",
"micros": 20000000,
"currencyCode": "USD"
},
"balanceUpdateTime": {
"date": "2020-04-12T16:20:50.52Z"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/giftCardObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-loyalty-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,22 +70,22 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"programName": "test program name",
"programLogo": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg"
}
},
"reviewStatus": "underReview"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"programName": "test program name",
"programLogo": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg"
}
},
"reviewStatus": "underReview"
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -94,77 +97,77 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"accountId": "Test account id",
"accountName": "Test account name",
"loyaltyPoints": {
"balance": {
"string": "800"
},
"label": "Points"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"accountId": "Test account id",
"accountName": "Test account name",
"loyaltyPoints": {
"balance": {
"string": "800"
},
"label": "Points"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -175,17 +178,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"loyaltyObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"loyaltyObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -211,16 +214,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -236,20 +239,121 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"state": "active",
"accountId": "Test account id",
"accountName": "Test account name",
"loyaltyPoints": {
"balance": {
"string": "800"
},
"label": "Points"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/loyaltyObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-offer-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,17 +70,17 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/offerClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"provider": "test provider",
"reviewStatus": "underReview",
"title": "test title",
"redemptionChannel": "online"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"provider": "test provider",
"reviewStatus": "underReview",
"title": "test title",
"redemptionChannel": "online"
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -89,77 +92,77 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/offerObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
}
}
],
"barcode": {
"type": "qrCode",
"value": "Testing Offers QR Code"
},
"state": "active",
"validTimeInterval": {
"kind": "walletobjects#timeInterval",
"start": {
"date": "2023-06-12T23:20:50.52Z"
},
"end": {
"date": "2023-12-12T23:20:50.52Z"
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"type": "qrCode",
"value": "Testing Offers QR Code"
},
"state": "active",
"validTimeInterval": {
"kind": "walletobjects#timeInterval",
"start": {
"date": "2023-06-12T23:20:50.52Z"
},
"end": {
"date": "2023-12-12T23:20:50.52Z"
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -170,17 +173,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"offerObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"offerObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -206,16 +209,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -231,20 +234,121 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"type": "qrCode",
"value": "Testing Offers QR Code"
},
"state": "active",
"validTimeInterval": {
"kind": "walletobjects#timeInterval",
"start": {
"date": "2023-06-12T23:20:50.52Z"
},
"end": {
"date": "2023-12-12T23:20:50.52Z"
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/offerObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-transit-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -67,23 +70,23 @@ http_client = AuthorizedSession(credentials)
# [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/transitClass/"
class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"reviewStatus": "underReview",
"transitType": "bus",
"logo": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png",
"description": "Test logo description"
"id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name",
"reviewStatus": "underReview",
"transitType": "bus",
"logo": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png",
"description": "Test logo description"
}
}
}
}
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -95,121 +98,121 @@ print("class POST response: ", class_response.text)
# [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/transitObject/"
object_payload = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"passengerType": "singlePassenger",
"passengerNames": "Test passenger names",
"ticketLeg": {
"originStationCode": "LA",
"originName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated origin name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default origin name"
}
},
"destinationStationCode": "SFO",
"destinationName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
"textModulesData": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated destination name"
"header": "Test text module header",
"body": "Test text module body"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default destination name"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"departureDateTime": "2020-04-12T16:20:50.52Z",
"arrivalDateTime": "2020-04-12T20:20:50.52Z",
"fareName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
"imageModulesData": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated fare name"
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default fare name"
}
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"passengerType": "singlePassenger",
"passengerNames": "Test passenger names",
"ticketLeg": {
"originStationCode": "LA",
"originName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated origin name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default origin name"
}
},
"destinationStationCode": "SFO",
"destinationName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated destination name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default destination name"
}
},
"departureDateTime": "2020-04-12T16:20:50.52Z",
"arrivalDateTime": "2020-04-12T20:20:50.52Z",
"fareName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated fare name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default fare name"
}
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -220,17 +223,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"transitObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"transitObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -256,16 +259,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -281,20 +284,165 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = {
"id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": {
"sourceUri": {
"uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"description": "Test heroImage description"
}
},
"textModulesData": [
{
"header": "Test text module header",
"body": "Test text module body"
}
],
"linksModuleData": {
"uris": [
{
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"kind": "walletobjects#uri",
"uri": "tel:6505555555",
"description": "Test link module tel description"
}
]
},
"imageModulesData": [
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
}
],
"barcode": {
"kind": "walletobjects#barcode",
"type": "qrCode",
"value": "Test QR Code"
},
"passengerType": "singlePassenger",
"passengerNames": "Test passenger names",
"ticketLeg": {
"originStationCode": "LA",
"originName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated origin name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default origin name"
}
},
"destinationStationCode": "SFO",
"destinationName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated destination name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default destination name"
}
},
"departureDateTime": "2020-04-12T16:20:50.52Z",
"arrivalDateTime": "2020-04-12T20:20:50.52Z",
"fareName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test translated fare name"
}
],
"defaultValue": {
"kind": "walletobjects#translatedString",
"language": "en-us",
"value": "Test default fare name"
}
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
}
]
}
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/transitObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]

File diff suppressed because it is too large Load Diff

View File

@@ -25,35 +25,37 @@ using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-$object_type-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Should only include alphanumeric characters, '.', '_', or '-'
*/
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
///////////////////////////////////////////////////////////////////////////////
// [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
var httpClient = new HttpClient();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
@@ -83,7 +85,7 @@ var classPayload = $class_payload;
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ;
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -139,6 +141,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
@@ -202,3 +205,49 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = $object_payload_batch;
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/$object_typeObject/\n\n";
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
}
data += "--batch_createobjectbatch--";
// Invoke the batch API calls
HttpRequestMessage objectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
objectRequest.Content = new StringContent(data);
objectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
objectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END batch]

View File

@@ -18,7 +18,10 @@
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
@@ -32,9 +35,14 @@ import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class Demo$object_type_titlecase {
public class Demo$object_type_title {
public static void main(String[] args) throws Exception {
/*
* keyFilePath - Path to service account key file from Google Cloud Console
@@ -70,10 +78,12 @@ public class Demo$object_type_titlecase {
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
String objectId = String.format("%s.%s-%s", issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
String objectId = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -230,10 +240,71 @@ public class Demo$object_type_titlecase {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload));
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<$object_type_titleObject> callback = new JsonBatchCallback<$object_type_titleObject>() {
// Invoked if the request was successful
public void onSuccess($object_type_titleObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
$object_type_titleObject $object_typeObject = new $object_type_titleObject()
// See link below for more information on required properties
// $api_url
$batch_statement;
client.$object_type_lowerobject().insert($object_typeObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}

View File

@@ -20,6 +20,7 @@ async function main() {
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]
/*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
const userId = process.env.WALLET_USER_ID || 'user-id';
let userId = process.env.WALLET_USER_ID || 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
const objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}-${classId}`;
// [END setup]
///////////////////////////////////////////////////////////////////////////////
@@ -91,8 +93,8 @@ async function main() {
// [START object]
const objectUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/$object_typeObject/';
const objectPayload = $object_payload;
let objectResponse;
try {
objectResponse = await httpClient.request({
url: objectUrl + objectId,
@@ -116,7 +118,7 @@ async function main() {
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
// Create a JWT for the object, and encode it to create a 'Save' URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
@@ -144,13 +146,13 @@ async function main() {
// [START createIssuer]
// New issuer name
const issuerName = "name";
const issuerName = 'name';
// New issuer email address
const issuerEmail = "email-address";
const issuerEmail = 'email-address';
// Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information
let issuerPayload = {
@@ -183,8 +185,8 @@ async function main() {
permissions: [
// Copy as needed for each email address that will need access
{
emailAddress: "email-address",
role: "READER | WRITER | OWNER"
emailAddress: 'email-address',
role: 'READER | WRITER | OWNER'
}
]
};
@@ -197,4 +199,46 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
let data = '';
let batchObject;
// Example: Generate three new pass objects
for (let i = 0; i < 3; i++) {
// Generate a random user ID
userId = uuidv4().replace('[^\\w.-]', '_');
// Generate an object ID with the user ID
objectId = `${issuerId}.${userId}-${classId}`;
batchObject = $object_payload_batch;
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';
data += 'POST /walletobjects/v1/$object_typeObject/\n\n';
data += JSON.stringify(batchObject) + '\n\n';
}
data += '--batch_createobjectbatch--';
// Invoke the batch API calls
let batchResponse = await httpClient.request({
url: 'https://walletobjects.googleapis.com/batch',
method: 'POST',
data: data,
headers: {
// `boundary` is the delimiter between API calls in the batch request
'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
}
});
console.log('batch POST response:', batchResponse);
// [END batch]
};

View File

@@ -22,6 +22,7 @@ require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/*
* objectId - ID for the wallet object
* - Format: `issuerId.userId`
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup]
@@ -209,3 +211,45 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
//[START batch]
// Download the PHP client library from the following URL
// https://developers.google.com/wallet/generic/resources/libraries
require __DIR__ . '/lib/Walletobjects.php';
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch#example
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setScopes("https://www.googleapis.com/auth/wallet_object.issuer");
$client->setAuthConfig($keyFilePath);
$client->setUseBatch(true);
$service = new Google_Service_Walletobjects($client);
$batch = $service->createBatch();
// Example: Generate three new pass objects
for ($i = 0; $i < 3; $i++) {
// Generate a random user ID
$userId = str_replace("[^\\w.-]", "_", uniqid());
// Generate a random object ID with the user ID
$objectId = "$issuerId.$userId-$classId";
$$object_typeObject = new Google_Service_Walletobjects_$object_type_titleObject();
// See link below for more information on required properties
// $api_url
$batch_statement
$batch->add($service->$object_type_lowerobject->insert($$object_typeObject));
}
$results = $batch->execute();
print_r($results);
// [END batch]

View File

@@ -17,8 +17,10 @@
# [START setup]
# [START imports]
import json
import os
import re
import uuid
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
@@ -43,8 +45,9 @@ CLASS_ID = os.environ.get("WALLET_CLASS_ID", "test-$object_type-class-id")
USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object
# - Format: `issuerId.userId`
# - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-'
# - `identifier` is developer-defined and unique to the user
OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth]
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials)
# [END auth]
@@ -69,8 +72,8 @@ CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/$object_typeC
class_payload = $class_payload
class_response = http_client.post(
CLASS_URL,
json=class_payload
CLASS_URL,
json=class_payload
)
print("class POST response: ", class_response.text)
# [END class]
@@ -85,12 +88,12 @@ object_payload = $object_payload
object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404:
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
# Object does not yet exist
# Send POST request to create it
object_response = http_client.post(
OBJECT_URL,
json=object_payload
)
print("object GET or POST response:", object_response.text)
# [END object]
@@ -101,17 +104,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt]
claims = {
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"$object_typeObjects": [
{
"id": OBJECT_ID
}
]
}
"iss": http_client.credentials.service_account_email,
"aud": "google",
"origins": ["www.example.com"],
"typ": "savetowallet",
"payload": {
"$object_typeObjects": [
{
"id": OBJECT_ID
}
]
}
}
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH)
@@ -137,16 +140,16 @@ ISSUER_URL = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"
# New issuer information
issuer_payload = {
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
"name": ISSUER_NAME,
"contactInfo": {
"email": ISSUER_EMAIL
}
}
# Make the POST request
issuer_response = http_client.post(
url=ISSUER_URL,
json=issuer_payload
url=ISSUER_URL,
json=issuer_payload
)
print("issuer POST response:", issuer_response.text)
@@ -162,20 +165,59 @@ permissions_url = f"https://walletobjects.googleapis.com/walletobjects/v1/permis
# New issuer permissions information
permissions_payload = {
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
"issuerId": ISSUER_ID,
"permissions": [
# Copy as needed for each email address that will need access
{
"emailAddress": "email-address",
"role": "READER | WRITER | OWNER"
},
]
}
permissions_response = http_client.put(
permissions_url,
json=permissions_payload
permissions_url,
json=permissions_payload
)
print("permissions PUT response:", permissions_response.text)
# [END updatePermissions]
###############################################################################
# Batch create Google Wallet objects from an existing class
###############################################################################
# [START batch]
# The request body will be a multiline string
# See below for more information
# https://cloud.google.com/compute/docs/api/how-tos/batch#example
data = ""
# Example: Generate three new pass objects
for _ in range(3):
# Generate a random user ID
USER_ID = str(uuid.uuid4()).replace("[^\\w.-]", "_")
# Generate an object ID with the user ID
OBJECT_ID = f"{ISSUER_ID}.{USER_ID}-{CLASS_ID}"
BATCH_OBJECT = $object_payload_batch
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/$object_typeObject/\n\n"
data += json.dumps(BATCH_OBJECT) + "\n\n"
data += "--batch_createobjectbatch--"
# Invoke the batch API calls
response = http_client.post(
"https://walletobjects.googleapis.com/batch",
data=data,
headers={
# `boundary` is the delimiter between API calls in the batch request
"Content-Type": "multipart/mixed; boundary=batch_createobjectbatch"
})
print(response.content.decode("UTF-8"))
# [END batch]