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 .DS_Store
.vscode .vscode
*.code-workspace *.code-workspace
testing/
# Node.js # Node.js
node_modules node_modules
@@ -15,12 +16,18 @@ build
local.properties local.properties
.classpath .classpath
.project .project
java/lib/
# See: https://developers.google.com/wallet/generic/resources/libraries
java/lib/libwalletobjects_public_java_lib_v1.jar
# Python # Python
*.pyc *.pyc
__pycache__ __pycache__
.venv/ .venv/
Pipfile.lock Pipfile.lock
*.yapf
.python-version
# .NET # .NET
bin bin
@@ -32,6 +39,9 @@ obj
vendor vendor
composer.lock composer.lock
# See: https://developers.google.com/wallet/generic/resources/libraries
php/lib/Walletobjects.php
# Ruby # Ruby
Gemfile.lock 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: This project contains samples for using the [Google Wallet REST APIs](https://developers.google.com/wallet/) in the following languages:
- Java - Java
- C# - C#
- JavaScript (Node.js) - JavaScript (Node.js)
- PHP - PHP
- Python - Python
@@ -19,4 +19,4 @@ Each sample demonstrates the following:
## Contributing ## 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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-eventTicket-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -96,7 +98,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -268,6 +270,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -331,3 +334,165 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-flight-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -109,7 +111,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -245,6 +247,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -308,3 +311,129 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-generic-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -87,7 +89,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -236,6 +238,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -299,3 +302,142 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-giftCard-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -90,7 +92,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -227,6 +229,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -290,3 +293,130 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-loyalty-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -98,7 +100,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -234,6 +236,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -297,3 +300,129 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-offer-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -91,7 +93,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -228,6 +230,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -291,3 +294,130 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-transit-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -99,7 +101,7 @@ var classPayload = new
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -290,6 +292,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -353,3 +356,184 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<RootNamespace>wallet_rest_samples</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <RootNamespace>wallet_rest_samples</RootNamespace>
<Nullable>disable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -10,11 +10,15 @@ repositories {
} }
dependencies { 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:java-jwt:3.19.1'
implementation 'com.auth0:jwks-rsa:0.9.0' implementation 'com.auth0:jwks-rsa:0.9.0'
implementation 'com.google.apis:google-api-services-oauth2:v1-rev20190313-1.30.3' 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.auth:google-auth-library-oauth2-http:1.10.0'
implementation 'com.google.guava:guava:r05' implementation 'com.squareup.okhttp3:okhttp:4.3.1'
implementation 'com.google.api-client:google-api-client:1.19.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 distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists 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 zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists 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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with 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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" 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. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 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 [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 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." location of your Java installation."
fi fi
else 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. 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 Please set the JAVA_HOME variable in your environment to match the
@@ -106,80 +140,101 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD=$( ulimit -H -n ) ||
MAX_FD="$MAX_FD_LIMIT" warn "Could not query maximum file descriptor limit"
fi esac
ulimit -n $MAX_FD case $MAX_FD in #(
if [ $? -ne 0 ] ; then '' | soft) :;; #(
warn "Could not set maximum file descriptor limit: $MAX_FD" *)
fi ulimit -n "$MAX_FD" ||
else warn "Could not set maximum file descriptor limit to $MAX_FD"
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" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --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 # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 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" "$@" exec "$JAVACMD" "$@"

14
java/gradlew.bat vendored
View File

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

View File

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

View File

@@ -18,7 +18,10 @@
// [START imports] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,9 +35,14 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoEventticket { public class DemoEventTicket {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
@@ -70,10 +78,12 @@ public class DemoEventticket {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -333,10 +343,73 @@ public class DemoEventticket {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoFlight { public class DemoFlight {
@@ -70,10 +78,12 @@ public class DemoFlight {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -315,10 +325,75 @@ public class DemoFlight {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoGeneric { public class DemoGeneric {
@@ -70,10 +78,12 @@ public class DemoGeneric {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -306,10 +316,74 @@ public class DemoGeneric {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,9 +35,14 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoGiftcard { public class DemoGiftCard {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
@@ -70,10 +78,12 @@ public class DemoGiftcard {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -301,10 +311,74 @@ public class DemoGiftcard {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoLoyalty { public class DemoLoyalty {
@@ -70,10 +78,12 @@ public class DemoLoyalty {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -306,10 +316,73 @@ public class DemoLoyalty {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoOffer { public class DemoOffer {
@@ -70,10 +78,12 @@ public class DemoOffer {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -301,10 +311,73 @@ public class DemoOffer {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,6 +35,11 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class DemoTransit { public class DemoTransit {
@@ -70,10 +78,12 @@ public class DemoTransit {
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -351,10 +361,74 @@ public class DemoTransit {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -192,8 +194,8 @@ async function main() {
} }
] ]
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -217,7 +219,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -245,13 +247,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -284,8 +286,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -298,4 +300,137 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -174,8 +176,8 @@ async function main() {
} }
] ]
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -199,7 +201,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -227,13 +229,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -266,8 +268,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -280,4 +282,108 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -165,8 +167,8 @@ async function main() {
} }
} }
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -190,7 +192,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -218,13 +220,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -257,8 +259,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -271,4 +273,117 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -160,8 +162,8 @@ async function main() {
} }
] ]
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -185,7 +187,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -213,13 +215,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -252,8 +254,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -266,4 +268,109 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -165,8 +167,8 @@ async function main() {
} }
] ]
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -190,7 +192,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -218,13 +220,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -257,8 +259,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -271,4 +273,108 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -160,8 +162,8 @@ async function main() {
} }
] ]
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -185,7 +187,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -213,13 +215,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -252,8 +254,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -266,4 +268,108 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -210,8 +212,8 @@ async function main() {
} }
] ]
}; };
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -235,7 +237,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -263,13 +265,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -302,8 +304,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -316,4 +318,152 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -310,3 +312,47 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -292,3 +294,49 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -283,3 +285,48 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -278,3 +280,48 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -283,3 +285,47 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -278,3 +280,47 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -328,3 +330,48 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,20 +70,20 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name", "issuerName": "test issuer name",
"eventName": { "eventName": {
"defaultValue": { "defaultValue": {
"language": "en-US", "language": "en-US",
"value": "Test event name" "value": "Test event name"
} }
}, },
"reviewStatus": "underReview" "reviewStatus": "underReview"
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -92,106 +95,106 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"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": { "textModulesData": [
"kind": "walletobjects#localizedString", {
"defaultValue": { "header": "Test text module header",
"kind": "walletobjects#translatedString", "body": "Test text module body"
"language": "en-us", }
"value": "G3" ],
} "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": { "imageModulesData": [
"kind": "walletobjects#localizedString", {
"defaultValue": { "mainImage": {
"kind": "walletobjects#translatedString", "kind": "walletobjects#image",
"language": "en-us", "sourceUri": {
"value": "5" "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": { "state": "active",
"kind": "walletobjects#localizedString", "seatInfo": {
"defaultValue": { "kind": "walletobjects#eventSeat",
"kind": "walletobjects#translatedString", "seat": {
"language": "en-us", "kind": "walletobjects#localizedString",
"value": "A" "defaultValue": {
} "kind": "walletobjects#translatedString",
} "language": "en-us",
}, "value": "42"
"ticketHolderName": "Test ticket holder name", }
"ticketNumber": "Test ticket number", },
"locations": [ "row": {
{ "kind": "walletobjects#localizedString",
"kind": "walletobjects#latLongPoint", "defaultValue": {
"latitude": 37.424015499999996, "kind": "walletobjects#translatedString",
"longitude": -122.09259560000001 "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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -202,17 +205,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"eventTicketObjects": [ "eventTicketObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,31 +70,31 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name", "issuerName": "test issuer name",
"destination": { "destination": {
"airportIataCode": "SFO", "airportIataCode": "SFO",
"gate": "C3", "gate": "C3",
"terminal": "2" "terminal": "2"
},
"flightHeader": {
"carrier": {
"carrierIataCode": "LX"
}, },
"flightNumber": "123" "flightHeader": {
}, "carrier": {
"origin": { "carrierIataCode": "LX"
"airportIataCode": "LAX", },
"gate": "A2", "flightNumber": "123"
"terminal": "1" },
}, "origin": {
"localScheduledDepartureDateTime": "2023-07-02T15:30:00", "airportIataCode": "LAX",
"reviewStatus": "underReview" "gate": "A2",
"terminal": "1"
},
"localScheduledDepartureDateTime": "2023-07-02T15:30:00",
"reviewStatus": "underReview"
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -103,77 +106,77 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"description": "Test image module description"
} }
} },
} "textModulesData": [
], {
"barcode": { "header": "Test text module header",
"kind": "walletobjects#barcode", "body": "Test text module body"
"type": "qrCode", }
"value": "Test QR Code" ],
}, "linksModuleData": {
"state": "active", "uris": [
"passengerName": "Test passenger name", {
"reservationInfo": { "kind": "walletobjects#uri",
"confirmationCode": "Test confirmation code" "uri": "http://maps.google.com/",
}, "description": "Test link module uri description"
"boardingAndSeatingInfo": { },
"seatNumber": "42", {
"boardingGroup": "B" "kind": "walletobjects#uri",
}, "uri": "tel:6505555555",
"locations": [ "description": "Test link module tel description"
{ }
"kind": "walletobjects#latLongPoint", ]
"latitude": 37.424015499999996, },
"longitude": -122.09259560000001 "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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -184,17 +187,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"flightObjects": [ "flightObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,13 +70,13 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/genericClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/genericClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name" "issuerName": "test issuer name"
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -85,86 +88,86 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/genericObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/genericObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"description": "Test image module 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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -175,17 +178,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"genericObjects": [ "genericObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,16 +70,16 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name", "issuerName": "test issuer name",
"merchantName": "Test merchant name", "merchantName": "Test merchant name",
"allowMultipleUsersPerObject": "true", "allowMultipleUsersPerObject": "true",
"reviewStatus": "underReview" "reviewStatus": "underReview"
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -88,78 +91,78 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"description": "Test image module description"
} }
} },
} "textModulesData": [
], {
"barcode": { "header": "Test text module header",
"kind": "walletobjects#barcode", "body": "Test text module body"
"type": "qrCode", }
"value": "Test QR Code" ],
}, "linksModuleData": {
"cardNumber": "Test card number", "uris": [
"cardPin": "Test card pin", {
"balance": { "kind": "walletobjects#uri",
"kind": "walletobjects#money", "uri": "http://maps.google.com/",
"micros": 20000000, "description": "Test link module uri description"
"currencyCode": "USD" },
}, {
"balanceUpdateTime": { "kind": "walletobjects#uri",
"date": "2020-04-12T16:20:50.52Z" "uri": "tel:6505555555",
}, "description": "Test link module tel description"
"locations": [ }
{ ]
"kind": "walletobjects#latLongPoint", },
"latitude": 37.424015499999996, "imageModulesData": [
"longitude": -122.09259560000001 {
} "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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -170,17 +173,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"giftCardObjects": [ "giftCardObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,22 +70,22 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name", "issuerName": "test issuer name",
"programName": "test program name", "programName": "test program name",
"programLogo": { "programLogo": {
"kind": "walletobjects#image", "kind": "walletobjects#image",
"sourceUri": { "sourceUri": {
"kind": "walletobjects#uri", "kind": "walletobjects#uri",
"uri": "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg" "uri": "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg"
} }
}, },
"reviewStatus": "underReview" "reviewStatus": "underReview"
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -94,77 +97,77 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"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" "textModulesData": [
}, {
"locations": [ "header": "Test text module header",
{ "body": "Test text module body"
"kind": "walletobjects#latLongPoint", }
"latitude": 37.424015499999996, ],
"longitude": -122.09259560000001 "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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -175,17 +178,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"loyaltyObjects": [ "loyaltyObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,17 +70,17 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/offerClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/offerClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name", "issuerName": "test issuer name",
"provider": "test provider", "provider": "test provider",
"reviewStatus": "underReview", "reviewStatus": "underReview",
"title": "test title", "title": "test title",
"redemptionChannel": "online" "redemptionChannel": "online"
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -89,77 +92,77 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/offerObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/offerObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"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": { "textModulesData": [
"date": "2023-12-12T23:20:50.52Z" {
} "header": "Test text module header",
}, "body": "Test text module body"
"locations": [ }
{ ],
"kind": "walletobjects#latLongPoint", "linksModuleData": {
"latitude": 37.424015499999996, "uris": [
"longitude": -122.09259560000001 {
} "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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -170,17 +173,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"offerObjects": [ "offerObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -67,23 +70,23 @@ http_client = AuthorizedSession(credentials)
# [START class] # [START class]
CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/transitClass/" CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/transitClass/"
class_payload = { class_payload = {
"id": f"{ISSUER_ID}.{CLASS_ID}", "id": f"{ISSUER_ID}.{CLASS_ID}",
"issuerName": "test issuer name", "issuerName": "test issuer name",
"reviewStatus": "underReview", "reviewStatus": "underReview",
"transitType": "bus", "transitType": "bus",
"logo": { "logo": {
"kind": "walletobjects#image", "kind": "walletobjects#image",
"sourceUri": { "sourceUri": {
"kind": "walletobjects#uri", "kind": "walletobjects#uri",
"uri": "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png", "uri": "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png",
"description": "Test logo description" "description": "Test logo description"
}
} }
}
} }
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -95,121 +98,121 @@ print("class POST response: ", class_response.text)
# [START object] # [START object]
OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/transitObject/" OBJECT_URL = "https://walletobjects.googleapis.com/walletobjects/v1/transitObject/"
object_payload = { object_payload = {
"id": OBJECT_ID, "id": OBJECT_ID,
"classId": f"{ISSUER_ID}.{CLASS_ID}", "classId": f"{ISSUER_ID}.{CLASS_ID}",
"heroImage": { "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": { "sourceUri": {
"kind": "walletobjects#uri", "uri": "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg", "description": "Test heroImage description"
"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", "textModulesData": [
"destinationName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{ {
"kind": "walletobjects#translatedString", "header": "Test text module header",
"language": "en-us", "body": "Test text module body"
"value": "Test translated destination name"
} }
], ],
"defaultValue": { "linksModuleData": {
"kind": "walletobjects#translatedString", "uris": [
"language": "en-us", {
"value": "Test default destination name" "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", "imageModulesData": [
"arrivalDateTime": "2020-04-12T20:20:50.52Z",
"fareName": {
"kind": "walletobjects#localizedString",
"translatedValues": [
{ {
"kind": "walletobjects#translatedString", "mainImage": {
"language": "en-us", "kind": "walletobjects#image",
"value": "Test translated fare name" "sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module description"
}
}
} }
], ],
"defaultValue": { "barcode": {
"kind": "walletobjects#translatedString", "kind": "walletobjects#barcode",
"language": "en-us", "type": "qrCode",
"value": "Test default fare name" "value": "Test QR Code"
} },
} "passengerType": "singlePassenger",
}, "passengerNames": "Test passenger names",
"locations": [ "ticketLeg": {
{ "originStationCode": "LA",
"kind": "walletobjects#latLongPoint", "originName": {
"latitude": 37.424015499999996, "kind": "walletobjects#localizedString",
"longitude": -122.09259560000001 "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) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -220,17 +223,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"transitObjects": [ "transitObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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; using Newtonsoft.Json;
// [END imports] // [END imports]
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS * - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/ */
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json"; string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/* /*
* issuerId - The issuer ID being used in this request * issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID * - Environment variable: WALLET_ISSUER_ID
*/ */
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id"; string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/* /*
* classId - Developer-defined ID for the wallet class * classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID * - Environment variable: WALLET_CLASS_ID
*/ */
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-$object_type-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 * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - Environment variable: WALLET_USER_ID
*/ */
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id"; string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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}"; string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup] // [END setup]
@@ -62,14 +64,14 @@ string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Rep
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// [START auth] // [START auth]
var credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath) ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" }) .CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential; .UnderlyingCredential;
var httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Bearer",
await credentials.GetAccessTokenForRequestAsync() await credentials.GetAccessTokenForRequestAsync()
); );
// [END auth] // [END auth]
@@ -83,7 +85,7 @@ var classPayload = $class_payload;
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl); HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload)); classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest); ; HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync(); string classContent = await classResponse.Content.ReadAsStringAsync();
@@ -139,6 +141,7 @@ SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgo
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims); JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt); string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}"; string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl); Console.WriteLine(saveUrl);
// [END jwt] // [END jwt]
@@ -202,3 +205,49 @@ HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}"); Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions] // [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] // [START imports]
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; 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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*; import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson; import com.google.api.client.json.GenericJson;
@@ -32,9 +35,14 @@ import com.google.common.collect.Lists;
import java.io.*; import java.io.*;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.*; 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] // [END imports]
public class Demo$object_type_titlecase { public class Demo$object_type_title {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
/* /*
* keyFilePath - Path to service account key file from Google Cloud Console * 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -230,10 +240,71 @@ public class Demo$object_type_titlecase {
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest( HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl, permissionsUrl,
new JsonHttpContent(new GsonFactory(), permissionsPayload)); new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute(); HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString()); System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions] // [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] // [START imports]
const { GoogleAuth } = require('google-auth-library'); const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports] // [END imports]
/* /*
@@ -44,14 +45,15 @@ async function main() {
* userId - Developer-defined ID for the user, such as an email address * userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID * - 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 * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - 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] // [END setup]
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -91,8 +93,8 @@ async function main() {
// [START object] // [START object]
const objectUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/$object_typeObject/'; const objectUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/$object_typeObject/';
const objectPayload = $object_payload; const objectPayload = $object_payload;
let objectResponse; let objectResponse;
try { try {
objectResponse = await httpClient.request({ objectResponse = await httpClient.request({
url: objectUrl + objectId, url: objectUrl + objectId,
@@ -116,7 +118,7 @@ async function main() {
// [END object] // [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] // [START jwt]
@@ -144,13 +146,13 @@ async function main() {
// [START createIssuer] // [START createIssuer]
// New issuer name // New issuer name
const issuerName = "name"; const issuerName = 'name';
// New issuer email address // New issuer email address
const issuerEmail = "email-address"; const issuerEmail = 'email-address';
// Issuer API endpoint // Issuer API endpoint
const issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer"; const issuerUrl = 'https://walletobjects.googleapis.com/walletobjects/v1/issuer';
// New issuer information // New issuer information
let issuerPayload = { let issuerPayload = {
@@ -183,8 +185,8 @@ async function main() {
permissions: [ permissions: [
// Copy as needed for each email address that will need access // Copy as needed for each email address that will need access
{ {
emailAddress: "email-address", emailAddress: 'email-address',
role: "READER | WRITER | OWNER" role: 'READER | WRITER | OWNER'
} }
] ]
}; };
@@ -197,4 +199,46 @@ async function main() {
console.log('permissions PUT response:', permissionsResponse); console.log('permissions PUT response:', permissionsResponse);
// [END updatePermissions] // [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 Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Client as Google_Client;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ClientException;
@@ -54,8 +55,9 @@ $userId = getenv('WALLET_USER_ID') ?: 'user-id';
/* /*
* objectId - ID for the wallet object * objectId - ID for the wallet object
* - Format: `issuerId.userId` * - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-' * - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/ */
$objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}"; $objectId = "{$issuerId}." . preg_replace('/[^\w.-]/i', '_', $userId) . "-{$classId}";
// [END setup] // [END setup]
@@ -209,3 +211,45 @@ $permissionsResponse = $httpClient->put(
echo 'permissions PUT response: ' . $permissionsResponse->getBody(); echo 'permissions PUT response: ' . $permissionsResponse->getBody();
// [END updatePermissions] // [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 setup]
# [START imports] # [START imports]
import json
import os import os
import re import re
import uuid
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account 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") USER_ID = os.environ.get("WALLET_USER_ID", "test@example.com")
# objectId - ID for the wallet object # objectId - ID for the wallet object
# - Format: `issuerId.userId` # - Format: `issuerId.identifier`
# - Should only include alphanumeric characters, '.', '_', or '-' # - 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) OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [END setup] # [END setup]
@@ -54,8 +57,8 @@ OBJECT_ID = "%s.%s-%s" % (ISSUER_ID, re.sub(r"[^\w.-]", "_", USER_ID), CLASS_ID)
# [START auth] # [START auth]
credentials = service_account.Credentials.from_service_account_file( credentials = service_account.Credentials.from_service_account_file(
KEY_FILE_PATH, KEY_FILE_PATH,
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"]) scopes=["https://www.googleapis.com/auth/wallet_object.issuer"])
http_client = AuthorizedSession(credentials) http_client = AuthorizedSession(credentials)
# [END auth] # [END auth]
@@ -69,8 +72,8 @@ CLASS_URL = "https://walletobjects.googleapis.com/walletobjects/v1/$object_typeC
class_payload = $class_payload class_payload = $class_payload
class_response = http_client.post( class_response = http_client.post(
CLASS_URL, CLASS_URL,
json=class_payload json=class_payload
) )
print("class POST response: ", class_response.text) print("class POST response: ", class_response.text)
# [END class] # [END class]
@@ -85,12 +88,12 @@ object_payload = $object_payload
object_response = http_client.get(OBJECT_URL + OBJECT_ID) object_response = http_client.get(OBJECT_URL + OBJECT_ID)
if object_response.status_code == 404: if object_response.status_code == 404:
# Object does not yet exist # Object does not yet exist
# Send POST request to create it # Send POST request to create it
object_response = http_client.post( object_response = http_client.post(
OBJECT_URL, OBJECT_URL,
json=object_payload json=object_payload
) )
print("object GET or POST response:", object_response.text) print("object GET or POST response:", object_response.text)
# [END object] # [END object]
@@ -101,17 +104,17 @@ print("object GET or POST response:", object_response.text)
# [START jwt] # [START jwt]
claims = { claims = {
"iss": http_client.credentials.service_account_email, "iss": http_client.credentials.service_account_email,
"aud": "google", "aud": "google",
"origins": ["www.example.com"], "origins": ["www.example.com"],
"typ": "savetowallet", "typ": "savetowallet",
"payload": { "payload": {
"$object_typeObjects": [ "$object_typeObjects": [
{ {
"id": OBJECT_ID "id": OBJECT_ID
} }
] ]
} }
} }
signer = crypt.RSASigner.from_service_account_file(KEY_FILE_PATH) 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 # New issuer information
issuer_payload = { issuer_payload = {
"name": ISSUER_NAME, "name": ISSUER_NAME,
"contactInfo": { "contactInfo": {
"email": ISSUER_EMAIL "email": ISSUER_EMAIL
} }
} }
# Make the POST request # Make the POST request
issuer_response = http_client.post( issuer_response = http_client.post(
url=ISSUER_URL, url=ISSUER_URL,
json=issuer_payload json=issuer_payload
) )
print("issuer POST response:", issuer_response.text) 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 # New issuer permissions information
permissions_payload = { permissions_payload = {
"issuerId": ISSUER_ID, "issuerId": ISSUER_ID,
"permissions": [ "permissions": [
# Copy as needed for each email address that will need access # Copy as needed for each email address that will need access
{ {
"emailAddress": "email-address", "emailAddress": "email-address",
"role": "READER | WRITER | OWNER" "role": "READER | WRITER | OWNER"
}, },
] ]
} }
permissions_response = http_client.put( permissions_response = http_client.put(
permissions_url, permissions_url,
json=permissions_payload json=permissions_payload
) )
print("permissions PUT response:", permissions_response.text) print("permissions PUT response:", permissions_response.text)
# [END updatePermissions] # [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]