forked from google-wallet/rest-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemoEventTicket.java
More file actions
425 lines (371 loc) · 16 KB
/
Copy pathDemoEventTicket.java
File metadata and controls
425 lines (371 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START setup]
// [START imports]
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.common.collect.Lists;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// Only include if you are using the Google Wallet client library
// https://developers.google.com/wallet/retail/loyalty-cards/resources/libraries
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
// [END imports]
public class DemoEventTicket {
public static void main(String[] args) throws Exception {
/*
* keyFilePath - Path to service account key file from Google Cloud Console
* - Environment variable: GOOGLE_APPLICATION_CREDENTIALS
*/
final String keyFilePath = System.getenv().getOrDefault(
"GOOGLE_APPLICATION_CREDENTIALS",
"/path/to/key.json");
/*
* issuerId - The issuer ID being updated in this request
* - Environment variable: WALLET_ISSUER_ID
*/
String issuerId = System.getenv().getOrDefault(
"WALLET_ISSUER_ID",
"issuer-id");
/*
* classId - Developer-defined ID for the wallet class
* - Environment variable: WALLET_CLASS_ID
*/
String classId = System.getenv().getOrDefault(
"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 = System.getenv().getOrDefault(
"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 = String.format("%s.%s-%s",
issuerId, userId.replaceAll("[^\\w.-]", "_"), classId);
// [END setup]
///////////////////////////////////////////////////////////////////////////////
// Create authenticated HTTP client, using service account file.
///////////////////////////////////////////////////////////////////////////////
// [START auth]
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(keyFilePath))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/wallet_object.issuer"));
credentials.refresh();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory httpRequestFactory = httpTransport.createRequestFactory(new HttpCredentialsAdapter(credentials));
// [END auth]
///////////////////////////////////////////////////////////////////////////////
// Create a class via the API (this can also be done in the business console).
///////////////////////////////////////////////////////////////////////////////
// [START class]
GenericUrl classUrl = new GenericUrl("https://walletobjects.googleapis.com/walletobjects/v1/eventTicketClass/");
String classPayload = String.format(
"{"
+ " \"id\": \"%s.%s\","
+ " \"issuerName\": \"test issuer name\","
+ " \"eventName\": {"
+ " \"defaultValue\": {"
+ " \"language\": \"en-US\","
+ " \"value\": \"Test event name\""
+ " }"
+ " },"
+ " \"reviewStatus\": \"underReview\""
+ "}", issuerId, classId);
// Convert body to JSON
JsonParser classParser = GsonFactory.getDefaultInstance().createJsonParser(classPayload);
GenericJson classJson = classParser.parseAndClose(GenericJson.class);
HttpContent classBody = new JsonHttpContent(GsonFactory.getDefaultInstance(), classJson);
// Create and send the request
HttpRequest classRequest = httpRequestFactory.buildPostRequest(classUrl, classBody);
HttpResponse classResponse = classRequest.execute();
System.out.println("class POST response:" + classResponse.parseAsString());
// [END class]
///////////////////////////////////////////////////////////////////////////////
// Create an object via the API.
///////////////////////////////////////////////////////////////////////////////
// [START object]
HttpRequest objectRequest;
HttpResponse objectResponse;
GenericUrl objectUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/eventTicketObject/" + objectId);
String objectPayload = String.format(
"{"
+ " \"id\": \"%s\","
+ " \"classId\": \"%s.%s\","
+ " \"heroImage\": {"
+ " \"sourceUri\": {"
+ " \"uri\": \"https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg\","
+ " \"description\": \"Test heroImage description\""
+ " }"
+ " },"
+ " \"textModulesData\": ["
+ " {"
+ " \"header\": \"Test text module header\","
+ " \"body\": \"Test text module body\""
+ " }"
+ " ],"
+ " \"linksModuleData\": {"
+ " \"uris\": ["
+ " {"
+ " \"kind\": \"walletobjects#uri\","
+ " \"uri\": \"http://maps.google.com/\","
+ " \"description\": \"Test link module uri description\""
+ " },"
+ " {"
+ " \"kind\": \"walletobjects#uri\","
+ " \"uri\": \"tel:6505555555\","
+ " \"description\": \"Test link module tel description\""
+ " }"
+ " ]"
+ " },"
+ " \"imageModulesData\": ["
+ " {"
+ " \"mainImage\": {"
+ " \"kind\": \"walletobjects#image\","
+ " \"sourceUri\": {"
+ " \"kind\": \"walletobjects#uri\","
+ " \"uri\": \"http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg\","
+ " \"description\": \"Test image module description\""
+ " }"
+ " }"
+ " }"
+ " ],"
+ " \"barcode\": {"
+ " \"kind\": \"walletobjects#barcode\","
+ " \"type\": \"qrCode\","
+ " \"value\": \"Test QR Code\""
+ " },"
+ " \"state\": \"active\","
+ " \"seatInfo\": {"
+ " \"kind\": \"walletobjects#eventSeat\","
+ " \"seat\": {"
+ " \"kind\": \"walletobjects#localizedString\","
+ " \"defaultValue\": {"
+ " \"kind\": \"walletobjects#translatedString\","
+ " \"language\": \"en-us\","
+ " \"value\": \"42\""
+ " }"
+ " },"
+ " \"row\": {"
+ " \"kind\": \"walletobjects#localizedString\","
+ " \"defaultValue\": {"
+ " \"kind\": \"walletobjects#translatedString\","
+ " \"language\": \"en-us\","
+ " \"value\": \"G3\""
+ " }"
+ " },"
+ " \"section\": {"
+ " \"kind\": \"walletobjects#localizedString\","
+ " \"defaultValue\": {"
+ " \"kind\": \"walletobjects#translatedString\","
+ " \"language\": \"en-us\","
+ " \"value\": \"5\""
+ " }"
+ " },"
+ " \"gate\": {"
+ " \"kind\": \"walletobjects#localizedString\","
+ " \"defaultValue\": {"
+ " \"kind\": \"walletobjects#translatedString\","
+ " \"language\": \"en-us\","
+ " \"value\": \"A\""
+ " }"
+ " }"
+ " },"
+ " \"ticketHolderName\": \"Test ticket holder name\","
+ " \"ticketNumber\": \"Test ticket number\","
+ " \"locations\": ["
+ " {"
+ " \"kind\": \"walletobjects#latLongPoint\","
+ " \"latitude\": 37.424015499999996,"
+ " \"longitude\": -122.09259560000001"
+ " }"
+ " ]"
+ "}", objectId, issuerId, classId);
try {
// Create and send the request
objectRequest = httpRequestFactory.buildGetRequest(objectUrl);
objectResponse = objectRequest.execute();
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]
///////////////////////////////////////////////////////////////////////////////
// Create a JWT for the object, and encode it to create a "Save" URL.
///////////////////////////////////////////////////////////////////////////////
// [START jwt]
HashMap<String, String> objectIdMap = new HashMap<String, String>();
objectIdMap.put("id", objectId);
HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put("eventTicketObjects", new ArrayList<>(Arrays.asList(objectIdMap)));
HashMap<String, Object> claims = new HashMap<String, Object>();
claims.put("iss", ((ServiceAccountCredentials) credentials).getClientEmail());
claims.put("aud", "google");
claims.put("origins", new ArrayList<>(Arrays.asList("www.example.com")));
claims.put("typ", "savetowallet");
claims.put("payload", payload);
Algorithm algorithm = Algorithm.RSA256(
null,
(RSAPrivateKey) ((ServiceAccountCredentials) credentials).getPrivateKey());
String token = JWT.create()
.withPayload(claims)
.sign(algorithm);
String saveUrl = "https://pay.google.com/gp/v/save/" + token;
System.out.println(saveUrl);
// [END jwt]
///////////////////////////////////////////////////////////////////////////////
// Create a new Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START createIssuer]
// New issuer name
final String issuerName = "name";
// New issuer email address
final String issuerEmail = "email-address";
// Issuer API endpoint
GenericUrl issuerUrl = new GenericUrl("https://walletobjects.googleapis.com/walletobjects/v1/issuer");
// New issuer information
HashMap<String, Object> issuerPayload = new HashMap<String, Object>() {
{
put("name", issuerName);
put("contactInfo", new HashMap<String, String>() {
{
put("email", issuerEmail);
}
});
}
};
HttpRequest issuerRequest = httpRequestFactory.buildPostRequest(
issuerUrl,
new JsonHttpContent(GsonFactory.getDefaultInstance(), issuerPayload));
HttpResponse issuerResponse = issuerRequest.execute();
System.out.println("issuer POST response: " + issuerResponse.parseAsString());
// [END createIssuer]
///////////////////////////////////////////////////////////////////////////////
// Update permissions for an existing Google Wallet issuer account
///////////////////////////////////////////////////////////////////////////////
// [START updatePermissions]
// Permissions API endpoint
GenericUrl permissionsUrl = new GenericUrl(
"https://walletobjects.googleapis.com/walletobjects/v1/permissions/" + issuerId);
ArrayList<HashMap<String, String>> permissions = new ArrayList<>();
// Copy as needed for each email address that will need access
permissions.add(new HashMap<String, String>() {
{
put("emailAddress", "email-address");
put("role", "READER | WRITER | OWNER");
}
});
// New issuer permissions information
HashMap<String, Object> permissionsPayload = new HashMap<String, Object>() {
{
put("issuerId", issuerId);
put("permissions", permissions);
}
};
HttpRequest permissionsRequest = httpRequestFactory.buildPutRequest(
permissionsUrl,
new JsonHttpContent(GsonFactory.getDefaultInstance(), permissionsPayload));
HttpResponse permissionsResponse = permissionsRequest.execute();
System.out.println("permissions PUT response: " + permissionsResponse.parseAsString());
// [END updatePermissions]
///////////////////////////////////////////////////////////////////////////////
// Batch create Google Wallet objects
///////////////////////////////////////////////////////////////////////////////
// [START batch]
// Note: This example requires version 1.23 or higher of the
// `com.google.api-client` library.
// https://developers.google.com/api-client-library/java
try {
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the Wallet API client
Walletobjects client = new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("APPLICATION_NAME")
.build();
// Create the batch request client
BatchRequest batch = client.batch(requestInitializer);
// The callback will be invoked for each request in the batch
JsonBatchCallback<EventTicketObject> callback = new JsonBatchCallback<EventTicketObject>() {
// Invoked if the request was successful
public void onSuccess(EventTicketObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
userId = UUID.randomUUID()
.toString()
.replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
objectId = String.format("%s.%s-%s", issuerId, userId, classId);
EventTicketObject eventTicketObject = new EventTicketObject()
// See link below for more information on required properties
// https://developers.google.com/wallet/tickets/events/rest/v1/eventticketobject
.setId(objectId)
.setClassId(classId)
.setState("ACTIVE");;
client.eventticketobject().insert(eventTicketObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// [END batch]
}
}