Merge pull request #30 from ncalteen/main

Catch Java exception and update .NET class structure
This commit is contained in:
Nick Alteen
2022-09-07 09:34:36 -04:00
committed by GitHub
26 changed files with 3387 additions and 3053 deletions

View File

@@ -26,334 +26,105 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-eventTicket-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketClass/";
var classPayload = new
class DemoEventTicket
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
eventName = new
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-eventTicket-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
defaultValue = new
{
language = "en-US",
value = "Test event name"
}
},
reviewStatus = "underReview"
};
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
string classContent = await classResponse.Content.ReadAsStringAsync();
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
Console.WriteLine($"class POST response: {classContent}");
// [END class]
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
async static void CreateEventTicketClass()
{
sourceUri = new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketClass/";
var classPayload = 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
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
eventName = 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
defaultValue = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
language = "en-US",
value = "Test event name"
}
}
}
},
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
}
},
reviewStatus = "underReview"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
eventTicketObjects = new object[]
async static void CreateEventTicketObject()
{
new
{
id = objectId
}
}
});
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -471,28 +242,284 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/eventTicketObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
eventTicketObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateEventTicketObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -26,311 +26,118 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-flight-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/flightClass/";
var classPayload = new
class DemoFlight
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
destination = new
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-flight-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
airportIataCode = "SFO",
gate = "C3",
terminal = "2"
},
flightHeader = new
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
async static void CreateFlightClass()
{
carrier = new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/flightClass/";
var classPayload = new
{
carrierIataCode = "LX"
},
flightNumber = "123"
},
origin = new
{
airportIataCode = "LAX",
gate = "A2",
terminal = "1"
},
localScheduledDepartureDateTime = "2023-07-02T15:30:00",
reviewStatus = "underReview"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/";
var objectPayload = 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
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
destination = new
{
kind = "walletobjects#uri",
uri = "http://maps.google.com/",
description = "Test link module uri description"
airportIataCode = "SFO",
gate = "C3",
terminal = "2"
},
new
flightHeader = new
{
kind = "walletobjects#uri",
uri = "tel:6505555555",
description = "Test link module tel description"
}
}
},
imageModulesData = new object[]
{
new
{
mainImage = new
{
kind = "walletobjects#image",
sourceUri = new
carrier = 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
}
carrierIataCode = "LX"
},
flightNumber = "123"
},
origin = new
{
airportIataCode = "LAX",
gate = "A2",
terminal = "1"
},
localScheduledDepartureDateTime = "2023-07-02T15:30:00",
reviewStatus = "underReview"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
flightObjects = new object[]
async static void CreateFlightObject()
{
new
{
id = objectId
}
}
});
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/flightObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -412,28 +219,248 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/flightObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
flightObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateFlightObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -26,302 +26,96 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-generic-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/genericClass/";
var classPayload = new
class DemoGeneric
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name"
};
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
string classContent = await classResponse.Content.ReadAsStringAsync();
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-generic-class-id";
Console.WriteLine($"class POST response: {classContent}");
// [END class]
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/genericObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
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"
}
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
genericObjects = new object[]
async static void CreateGenericClass()
{
new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/genericClass/";
var classPayload = new
{
id = objectId
}
id = $"{issuerId}.{classId}",
issuerName = "test issuer name"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
async static void CreateGenericObject()
{
email = issuerEmail
}
};
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/genericObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -416,28 +210,261 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/genericObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
genericObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateGenericObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -26,293 +26,99 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-giftCard-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardClass/";
var classPayload = new
class DemoGiftCard
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
merchantName = "Test merchant name",
allowMultipleUsersPerObject = "true",
reviewStatus = "underReview"
};
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
string classContent = await classResponse.Content.ReadAsStringAsync();
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-giftCard-class-id";
Console.WriteLine($"class POST response: {classContent}");
// [END class]
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
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
}
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
giftCardObjects = new object[]
async static void CreateGiftCardClass()
{
new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardClass/";
var classPayload = new
{
id = objectId
}
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
merchantName = "Test merchant name",
allowMultipleUsersPerObject = "true",
reviewStatus = "underReview"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
async static void CreateGiftCardObject()
{
email = issuerEmail
}
};
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/giftCardObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -395,28 +201,249 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/giftCardObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
giftCardObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateGiftCardObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -26,300 +26,107 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-loyalty-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyClass/";
var classPayload = new
class DemoLoyalty
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
programName = "test program name",
programLogo = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg"
}
},
reviewStatus = "underReview"
};
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
string classContent = await classResponse.Content.ReadAsStringAsync();
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-loyalty-class-id";
Console.WriteLine($"class POST response: {classContent}");
// [END class]
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
sourceUri = new
{
uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
description = "Test heroImage description"
}
},
textModulesData = new object[]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
async static void CreateLoyaltyClass()
{
new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyClass/";
var classPayload = 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
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
programName = "test program name",
programLogo = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
uri = "http://farm8.staticflickr.com/7340/11177041185_a61a7f2139_o.jpg"
}
}
}
},
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
}
},
reviewStatus = "underReview"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
loyaltyObjects = new object[]
async static void CreateLoyaltyObject()
{
new
{
id = objectId
}
}
});
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/loyaltyObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -401,28 +208,248 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/loyaltyObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
loyaltyObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateLoyaltyObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -26,294 +26,100 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-offer-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/offerClass/";
var classPayload = new
class DemoOffer
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
provider = "test provider",
reviewStatus = "underReview",
title = "test title",
redemptionChannel = "online"
};
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
string classContent = await classResponse.Content.ReadAsStringAsync();
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-offer-class-id";
Console.WriteLine($"class POST response: {classContent}");
// [END class]
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/offerObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
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
}
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
offerObjects = new object[]
async static void CreateOfferClass()
{
new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/offerClass/";
var classPayload = new
{
id = objectId
}
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
provider = "test provider",
reviewStatus = "underReview",
title = "test title",
redemptionChannel = "online"
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
async static void CreateOfferObject()
{
email = issuerEmail
}
};
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/offerObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -396,28 +202,249 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/offerObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
offerObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateOfferObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -26,356 +26,108 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-transit-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/transitClass/";
var classPayload = new
class DemoTransit
{
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
reviewStatus = "underReview",
transitType = "bus",
logo = new
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-transit-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png",
description = "Test logo description"
}
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/transitObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
heroImage = new
async static void CreateTransitClass()
{
sourceUri = new
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/transitClass/";
var classPayload = 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
id = $"{issuerId}.{classId}",
issuerName = "test issuer name",
reviewStatus = "underReview",
transitType = "bus",
logo = new
{
kind = "walletobjects#image",
sourceUri = new
{
kind = "walletobjects#uri",
uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
description = "Test image module description"
uri = "https://live.staticflickr.com/65535/48690277162_cd05f03f4d_o.png",
description = "Test logo 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
}
};
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
};
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
transitObjects = new object[]
async static void CreateTransitObject()
{
new
{
id = objectId
}
}
});
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// The request body will be a multiline string
// See below for more information
// https://cloud.google.com/compute/docs/api/how-tos/batch//example
string data = "";
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++)
{
// Generate a random user ID
userId = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = new
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/transitObject/";
var objectPayload = new
{
id = objectId,
classId = $"{issuerId}.{classId}",
@@ -512,28 +264,303 @@ for (int i = 0; i < 3; i++)
}
};
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/transitObject/\n\n";
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
static void CreateJWTSaveURL()
{
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
transitObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreateTransitObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -135,6 +135,9 @@ public class DemoEventTicket {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/" + objectId);
String objectPayload = String.format(
@@ -231,24 +234,31 @@ public class DemoEventTicket {
+ " ]"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -146,6 +146,9 @@ public class DemoFlight {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/flightObject/" + objectId);
String objectPayload = String.format(
@@ -213,24 +216,31 @@ public class DemoFlight {
+ " ]"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -128,6 +128,9 @@ public class DemoGeneric {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/genericObject/" + objectId);
String objectPayload = String.format(
@@ -204,24 +207,31 @@ public class DemoGeneric {
+ " }"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -131,6 +131,9 @@ public class DemoGiftCard {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/giftCardObject/" + objectId);
String objectPayload = String.format(
@@ -199,24 +202,31 @@ public class DemoGiftCard {
+ " ]"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -137,6 +137,9 @@ public class DemoLoyalty {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/loyaltyObject/" + objectId);
String objectPayload = String.format(
@@ -204,24 +207,31 @@ public class DemoLoyalty {
+ " ]"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -132,6 +132,9 @@ public class DemoOffer {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/offerObject/" + objectId);
String objectPayload = String.format(
@@ -199,24 +202,31 @@ public class DemoOffer {
+ " ]"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -138,6 +138,9 @@ public class DemoTransit {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/transitObject/" + objectId);
String objectPayload = String.format(
@@ -249,24 +252,31 @@ public class DemoTransit {
+ " ]"
+ "}", objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////

View File

@@ -320,97 +320,97 @@ async function main() {
// 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": [
"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": [
{
"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": [
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"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
"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';

View File

@@ -302,68 +302,68 @@ async function main() {
// 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": [
"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": [
{
"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": [
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"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
"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';

View File

@@ -293,77 +293,77 @@ async function main() {
// 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": [
"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": [
{
"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": [
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"mainImage": {
"kind": "walletobjects#image",
"sourceUri": {
"kind": "walletobjects#uri",
"uri": "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
"description": "Test image module 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"
}
}
};
data += '--batch_createobjectbatch\n';
data += 'Content-Type: application/json\n\n';

View File

@@ -288,69 +288,69 @@ async function main() {
// 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": [
"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": [
{
"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": [
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
{
"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
"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';

View File

@@ -293,68 +293,68 @@ async function main() {
// 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": [
"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": [
{
"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"
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
"label": "Points"
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
"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';

View File

@@ -288,68 +288,68 @@ async function main() {
// 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": [
"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": [
{
"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"
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
"end": {
"date": "2023-12-12T23:20:50.52Z"
}
},
"locations": [
{
"kind": "walletobjects#latLongPoint",
"latitude": 37.424015499999996,
"longitude": -122.09259560000001
"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';

View File

@@ -338,112 +338,112 @@ async function main() {
// 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": [
"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": [
{
"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"
}
"kind": "walletobjects#uri",
"uri": "http://maps.google.com/",
"description": "Test link module uri description"
},
"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
"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';

View File

@@ -1,6 +1,7 @@
{
"dependencies": {
"google-auth-library": ">=5.9.2",
"jsonwebtoken": ">=8.5.1"
"google-auth-library": "^5.9.2",
"jsonwebtoken": "^8.5.1",
"uuidv4": "^6.2.13"
}
}

View File

@@ -1,7 +1,7 @@
{
"require": {
"google/auth": "^1.18",
"guzzlehttp/guzzle": "*",
"google/apiclient": "^2.12"
}
"require": {
"google/auth": "^1.18",
"guzzlehttp/guzzle": "*",
"google/apiclient": "^2.12"
}
}

View File

@@ -425,12 +425,20 @@ def indent(text, spaces):
return text.replace("\n", "\n" + (" " * spaces))
def format_filename_dotnet(object_type_name):
"""Format .cs filename for .NET"""
return f"Demo{object_type_name[0].upper()}{object_type_name[1:]}.cs"
def format_payload_dotnet(unformatted_payload):
"""Format JSON payloads for .NET syntax"""
formatted_output = []
unformatted_payload = (unformatted_payload.replace(' "', " ").replace(
'": ', " = ").replace(" string = ", " @string = ").replace("]", "}"))
unformatted_payload = unformatted_payload.replace(' "', " ")
unformatted_payload = unformatted_payload.replace('": ', " = ")
unformatted_payload = unformatted_payload.replace(" string = ",
" @string = ")
unformatted_payload = unformatted_payload.replace("]", "}")
for line in unformatted_payload.split("\n"):
_indent = len(line) - len(line.lstrip(" "))
@@ -443,30 +451,37 @@ def format_payload_dotnet(unformatted_payload):
return "\n".join(formatted_output)
def format_batch_payload(unformatted_payload):
"""Format batch request payloads with additional indentation."""
def format_payload_java(unformatted_payload):
"""Format JSON payloads for Java syntax"""
formatted_payload = unformatted_payload.replace('"', '\\"')
formatted_payload = formatted_payload.replace("\n", '"\n + "')
formatted_payload = '\n "' + formatted_payload + '"'
return formatted_payload
def format_with_offset(unformatted_payload, offset):
"""Format request payloads with additional indentation offset."""
formatted_payload = [unformatted_payload.split("\n")[0]]
formatted_payload += [" " + x for x in unformatted_payload.split("\n")[1:]]
formatted_payload += [
(" " * offset) + x for x in unformatted_payload.split("\n")[1:]
]
return "\n".join(formatted_payload)
lang_config = {
"java": {
"ext":
"java",
"class_id":
"%s.%s",
"object_id":
"%s",
"formatter":
lambda s: '\n "' + s.replace('"', '\\"').replace(
"\n", '"\n + "') + '"',
"filename":
lambda s: f"src/main/java/Demo{s[0].upper()}{s[1:]}.java",
"indent":
2,
"continuation_indent":
4,
"ext": "java",
"class_id": "%s.%s",
"object_id": "%s",
"formatter": format_payload_java,
"filename": lambda s: f"src/main/java/Demo{s[0].upper()}{s[1:]}.java",
"indent": 2,
"continuation_indent": 4,
"object_indent_offset": 0,
"class_indent_offset": 0,
"batch_indent_offset": 0,
"batch_set_statements": {
"generic": [
".setId(objectId)",
@@ -516,6 +531,9 @@ lang_config = {
"object_id": "OBJECT_ID",
"indent": 4,
"continuation_indent": 4,
"object_indent_offset": 0,
"class_indent_offset": 0,
"batch_indent_offset": 4,
"filename": lambda s: f"demo_{s.lower()}.py",
"batch_set_statements": {
"generic": [],
@@ -533,7 +551,9 @@ lang_config = {
"object_id": "objectId",
"indent": 2,
"continuation_indent": 4,
"formatter": lambda s: indent(s, 2),
"object_indent_offset": 2,
"class_indent_offset": 2,
"batch_indent_offset": 4,
"filename": lambda s: f"demo-{s.lower()}.js",
"batch_set_statements": {
"generic": [],
@@ -551,6 +571,9 @@ lang_config = {
"object_id": '"{$objectId}"',
"indent": 2,
"continuation_indent": 4,
"object_indent_offset": 0,
"class_indent_offset": 0,
"batch_indent_offset": 0,
"filename": lambda s: f"demo_{s.lower()}.php",
"batch_set_statements": {
"generic": [
@@ -596,20 +619,16 @@ lang_config = {
},
},
"dotnet": {
"ext":
"cs",
"class_id":
'$"{issuerId}.{classId}"',
"object_id":
"objectId",
"formatter":
format_payload_dotnet,
"filename":
lambda s: f"Demo{object_type[0].upper()}{object_type[1:]}.cs",
"indent":
2,
"continuation_indent":
4,
"ext": "cs",
"class_id": '$"{issuerId}.{classId}"',
"object_id": "objectId",
"formatter": format_payload_dotnet,
"filename": format_filename_dotnet,
"indent": 2,
"continuation_indent": 4,
"object_indent_offset": 4,
"class_indent_offset": 4,
"batch_indent_offset": 6,
"batch_set_statements": {
"generic": [],
"offer": [],
@@ -625,6 +644,11 @@ lang_config = {
"class_id": "\"issuer-id.class-id\"",
"object_id": "\"issuer-id.user-id\"",
"filename": lambda s: f"demo_{s.lower()}.http",
"indent": 2,
"continuation_indent": 2,
"object_indent_offset": 0,
"class_indent_offset": 0,
"batch_indent_offset": 0,
"batch_set_statements": {
"generic": [],
"offer": [],
@@ -649,10 +673,23 @@ for lang, config in lang_config.items():
# JSON payloads
for name, value in content.items():
if name == "$object_payload":
payload_offset = config.get("object_indent_offset", 0)
else:
payload_offset = config.get("class_indent_offset", 0)
batch_offset = config.get("batch_indent_offset", 0)
payload = json.dumps(value, indent=config.get("indent", 2))
if "formatter" in config:
payload = config["formatter"](payload)
batch_payload = format_batch_payload(payload)
if batch_offset > 0:
batch_payload = format_with_offset(payload, batch_offset)
else:
batch_payload = payload
if payload_offset > 0:
payload = format_with_offset(payload, payload_offset)
output = output.replace(f"{name}_batch", batch_payload)
output = output.replace(name, payload)

View File

@@ -26,228 +26,255 @@ using Newtonsoft.Json;
// [END imports]
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-$object_type-class-id";
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
ServiceAccountCredential credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/$object_typeClass/";
var classPayload = $class_payload;
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/$object_typeObject/";
var objectPayload = $object_payload;
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
class Demo$object_type_title
{
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
static string keyFilePath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? "/path/to/key.json";
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
/*
* issuerId - The issuer ID being used in this request
* - Environment variable: WALLET_ISSUER_ID
*/
static string issuerId = Environment.GetEnvironmentVariable("WALLET_ISSUER_ID") ?? "issuer-id";
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
static string classId = Environment.GetEnvironmentVariable("WALLET_CLASS_ID") ?? "test-$object_type-class-id";
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
$object_typeObjects = new object[]
/*
* userId - Developer-defined ID for the user, such as an email address
* - Environment variable: WALLET_USER_ID
*/
static string userId = Environment.GetEnvironmentVariable("WALLET_USER_ID") ?? "user-id";
/*
* objectId - ID for the wallet object
* - Format: `issuerId.identifier`
* - Should only include alphanumeric characters, '.', '_', or '-'
* - `identifier` is developer-defined and unique to the user
*/
static string objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
// [END setup]
static ServiceAccountCredential credentials;
static HttpClient httpClient;
async static void Auth()
{
new
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
credentials = (ServiceAccountCredential)GoogleCredential.FromFile(keyFilePath)
.CreateScoped(new[] { "https://www.googleapis.com/auth/wallet_object.issuer" })
.UnderlyingCredential;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
await credentials.GetAccessTokenForRequestAsync()
);
// [END auth]
}
async static void Create$object_type_titleClass()
{
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
string classUrl = "https://walletobjects.googleapis.com/walletobjects/v1/$object_typeClass/";
var classPayload = $class_payload;
HttpRequestMessage classRequest = new HttpRequestMessage(HttpMethod.Post, classUrl);
classRequest.Content = new StringContent(JsonConvert.SerializeObject(classPayload));
HttpResponseMessage classResponse = httpClient.Send(classRequest);
string classContent = await classResponse.Content.ReadAsStringAsync();
Console.WriteLine($"class POST response: {classContent}");
// [END class]
}
async static void Create$object_type_titleObject()
{
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
// [START object]
string objectUrl = "https://walletobjects.googleapis.com/walletobjects/v1/$object_typeObject/";
var objectPayload = $object_payload;
HttpRequestMessage objectRequest = new HttpRequestMessage(HttpMethod.Get, $"{objectUrl}{objectId}");
HttpResponseMessage objectResponse = httpClient.Send(objectRequest);
if (objectResponse.StatusCode == HttpStatusCode.NotFound)
{
id = objectId
// Object does not yet exist
// Send POST request to create it
objectRequest = new HttpRequestMessage(HttpMethod.Post, objectUrl);
objectRequest.Content = new StringContent(JsonConvert.SerializeObject(objectPayload));
objectResponse = httpClient.Send(objectRequest);
}
string objectContent = await objectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"object GET or POST response: {objectContent}");
// [END object]
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
string issuerName = "name";
// New issuer email address
string issuerEmail = "email-address";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
static void CreateJWTSaveURL()
{
email = issuerEmail
}
};
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
// [START jwt]
JwtPayload claims = new JwtPayload();
claims.Add("iss", credentials.Id);
claims.Add("aud", "google");
claims.Add("origins", new string[] { "www.example.com" });
claims.Add("typ", "savetowallet");
claims.Add("payload", new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
$object_typeObjects = new object[]
{
new
{
id = objectId
}
}
});
RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
JwtSecurityToken jwt = new JwtSecurityToken(new JwtHeader(signingCredentials), claims);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
string saveUrl = $"https://pay.google.com/gp/v/save/{token}";
Console.WriteLine(saveUrl);
// [END jwt]
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
async static void CreateIssuerAccount()
{
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
// [START createIssuer]
// New issuer name
string issuerName = "name";
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects from an existing class
///////////////////////////////////////////////////////////////////////////////
// New issuer email address
string issuerEmail = "email-address";
// [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 = "";
// Issuer API endpoint
string issuerUrl = "https://walletobjects.googleapis.com/walletobjects/v1/issuer";
// 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.-]", "_");
// New issuer information
var issuerPayload = new
{
name = issuerName,
contactInfo = new
{
email = issuerEmail
}
};
// Generate an object ID with the user ID
objectId = $"{issuerId}.{new Regex(@"[^\w.-]", RegexOptions.Compiled).Replace(userId, "_")}-{classId}";
var batchObject = $object_payload_batch;
HttpRequestMessage issuerRequest = new HttpRequestMessage(HttpMethod.Post, issuerUrl);
issuerRequest.Content = new StringContent(JsonConvert.SerializeObject(issuerPayload));
HttpResponseMessage issuerResponse = httpClient.Send(issuerRequest);
data += "--batch_createobjectbatch\n";
data += "Content-Type: application/json\n\n";
data += "POST /walletobjects/v1/$object_typeObject/\n\n";
Console.WriteLine($"issuer POST response: {await issuerResponse.Content.ReadAsStringAsync()}");
// [END createIssuer]
}
data += JsonConvert.SerializeObject(batchObject) + "\n\n";
async static void UpdateIssuerAccountPermissions()
{
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
string permissionsUrl = $"https://walletobjects.googleapis.com/walletobjects/v1/permissions/{issuerId}";
// New issuer permissions information
var permissionsPayload = new
{
issuerId = issuerId,
permissions = new object[]
{
// Copy as needed for each email address that will need access
new
{
emailAddress = "email-address",
role = "READER | WRITER | OWNER"
}
}
};
HttpRequestMessage permissionsRequest = new HttpRequestMessage(HttpMethod.Put, permissionsUrl);
permissionsRequest.Content = new StringContent(JsonConvert.SerializeObject(permissionsPayload));
HttpResponseMessage permissionsResponse = httpClient.Send(permissionsRequest);
Console.WriteLine($"permissions PUT response: {await permissionsResponse.Content.ReadAsStringAsync()}");
// [END updatePermissions]
}
async static void BatchCreate$object_type_titleObjects()
{
///////////////////////////////////////////////////////////////////////////////
// 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 batchObjectRequest = new HttpRequestMessage(
HttpMethod.Post,
"https://walletobjects.googleapis.com/batch");
batchObjectRequest.Content = new StringContent(data);
batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed");
batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
// `boundary` is the delimiter between API calls in the batch request
new NameValueHeaderValue("boundary", "batch_createobjectbatch"));
HttpResponseMessage batchObjectResponse = httpClient.Send(batchObjectRequest);
string batchObjectContent = await batchObjectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"batch POST response: {batchObjectContent}");
// [END batch]
}
}
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

@@ -124,28 +124,38 @@ public class Demo$object_type_title {
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/$object_typeObject/" + objectId);
String objectPayload = String.format($object_payload, objectId, issuerId, classId);
// Create and send the request
HttpRequest objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
HttpResponse objectResponse = objectRequest.execute();
if (objectResponse.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
}
System.out.println("object GET or POST response: " + objectResponse.parseAsString());
System.out.println("object GET response: " + objectResponse.parseAsString());
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 404) {
// Object does not yet exist
// Send POST request to create it
// Convert body to JSON
JsonParser objectParser = GsonFactory.getDefaultInstance().createJsonParser(objectPayload);
GenericJson objectJson = objectParser.parseAndClose(GenericJson.class);
HttpContent objectBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), objectJson);
// Create and send the request
objectRequest = httpRequestFactory.buildPostRequest(objectUrl, objectBody);
objectResponse = objectRequest.execute();
System.out.println("object POST response: " + objectResponse.parseAsString());
} else {
// Something else went wrong
throw ex;
}
}
// [END object]
///////////////////////////////////////////////////////////////////////////////