forked from google-wallet/rest-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemoGiftCard.java
More file actions
507 lines (463 loc) · 21.2 KB
/
Copy pathDemoGiftCard.java
File metadata and controls
507 lines (463 loc) · 21.2 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/*
* 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.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.*;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.walletobjects.Walletobjects;
import com.google.api.services.walletobjects.model.*;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;
// [END imports]
/** Demo class for creating and managing Gift cards in Google Wallet. */
public class DemoGiftCard {
/**
* Path to service account key file from Google Cloud Console. Environment variable:
* GOOGLE_APPLICATION_CREDENTIALS.
*/
public static String keyFilePath;
/** Service account credentials for Google Wallet APIs. */
public static GoogleCredentials credentials;
/** Google Wallet service client. */
public static Walletobjects service;
public DemoGiftCard() {
keyFilePath =
System.getenv().getOrDefault("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/key.json");
}
// [END setup]
// [START auth]
/**
* Create authenticated HTTP client using a service account file.
*
* @throws Exception
*/
public void Auth() throws Exception {
String scope = "https://www.googleapis.com/auth/wallet_object.issuer";
credentials =
GoogleCredentials.fromStream(new FileInputStream(keyFilePath))
.createScoped(Arrays.asList(scope));
credentials.refresh();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
service =
new Walletobjects.Builder(
httpTransport,
GsonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credentials))
.setApplicationName("APPLICATION_NAME")
.build();
}
// [END auth]
// [START class]
/**
* Create a class via the API. This can also be done in the Google Pay and Wallet console.
*
* @param issuerId The issuer ID being used for this request.
* @param classSuffix Developer-defined unique ID for this pass class.
* @return The pass class ID: "{issuerId}.{classSuffix}"
* @throws IOException
*/
public String CreateGiftCardClass(String issuerId, String classSuffix) throws IOException {
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardclass
GiftCardClass giftCardClass =
new GiftCardClass()
.setId(String.format("%s.%s", issuerId, classSuffix))
.setIssuerName("Issuer name")
.setReviewStatus("UNDER_REVIEW");
try {
GiftCardClass response = service.giftcardclass().insert(giftCardClass).execute();
System.out.println("Class insert response");
System.out.println(response.toPrettyString());
return response.getId();
} catch (GoogleJsonResponseException ex) {
if (ex.getStatusCode() == 409) {
System.out.println(String.format("Class %s.%s already exists", issuerId, classSuffix));
return String.format("%s.%s", issuerId, classSuffix);
}
// Something else went wrong
ex.printStackTrace();
return ex.getMessage();
}
}
// [END class]
// [START object]
/**
* Create an object via the API.
*
* @param issuerId The issuer ID being used for this request.
* @param classSuffix Developer-defined unique ID for this pass class.
* @param userId Developer-defined user ID for this object.
* @return The pass object ID: "{issuerId}.{userId}"
* @throws IOException
*/
public String CreateGiftCardObject(String issuerId, String classSuffix, String userId)
throws IOException {
// Generate the object ID
// Should only include alphanumeric characters, '.', '_', or '-'
String newUserId = userId.replaceAll("[^\\w.-]", "_");
String objectId = String.format("%s.%s", issuerId, newUserId);
try {
// Check if the object exists
GiftCardObject response = service.giftcardobject().get(objectId).execute();
System.out.println("Object get response");
System.out.println(response.toPrettyString());
return response.getId();
} catch (GoogleJsonResponseException ex) {
if (ex.getStatusCode() != 404) {
// Something else went wrong
ex.printStackTrace();
return ex.getMessage();
}
}
// Object doesn't exist, create it now
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardobject
GiftCardObject giftCardObject =
new GiftCardObject()
.setId(objectId)
.setClassId(String.format("%s.%s", issuerId, classSuffix))
.setState("ACTIVE")
.setHeroImage(
new Image()
.setSourceUri(
new ImageUri()
.setUri(
"https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"))
.setContentDescription(
new LocalizedString()
.setDefaultValue(
new TranslatedString()
.setLanguage("en-US")
.setValue("Hero image description"))))
.setTextModulesData(
Arrays.asList(
new TextModuleData()
.setHeader("Text module header")
.setBody("Text module body")
.setId("TEXT_MODULE_ID")))
.setLinksModuleData(
new LinksModuleData()
.setUris(
Arrays.asList(
new Uri()
.setUri("http://maps.google.com/")
.setDescription("Link module URI description")
.setId("LINK_MODULE_URI_ID"),
new Uri()
.setUri("tel:6505555555")
.setDescription("Link module tel description")
.setId("LINK_MODULE_TEL_ID"))))
.setImageModulesData(
Arrays.asList(
new ImageModuleData()
.setMainImage(
new Image()
.setSourceUri(
new ImageUri()
.setUri(
"http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"))
.setContentDescription(
new LocalizedString()
.setDefaultValue(
new TranslatedString()
.setLanguage("en-US")
.setValue("Image module description"))))
.setId("IMAGE_MODULE_ID")))
.setBarcode(new Barcode().setType("QR_CODE").setValue("QR code value"))
.setLocations(
Arrays.asList(
new LatLongPoint()
.setLatitude(37.424015499999996)
.setLongitude(-122.09259560000001)))
.setCardNumber("Card number")
.setPin("1234")
.setBalance(new Money().setMicros(20000000L).setCurrencyCode("USD"))
.setBalanceUpdateTime(new DateTime().setDate("2020-04-12T16:20:50.52-04:00"));
GiftCardObject response = service.giftcardobject().insert(giftCardObject).execute();
System.out.println("Object insert response");
System.out.println(response.toPrettyString());
return response.getId();
}
// [END object]
// [START jwt]
/**
* Generate a signed JWT that creates a new pass class and object.
*
* <p>When the user opens the "Add to Google Wallet" URL and saves the pass to their wallet, the
* pass class and object defined in the JWT are created. This allows you to create multiple pass
* classes and objects in one API call when the user saves the pass to their wallet.
*
* @param issuerId The issuer ID being used for this request.
* @param classSuffix Developer-defined unique ID for this pass class.
* @param userId Developer-defined user ID for this object.
* @return An "Add to Google Wallet" link.
*/
public String CreateJWTSaveURL(String issuerId, String classSuffix, String userId) {
// Generate the object ID
// Should only include alphanumeric characters, '.', '_', or '-'
String newUserId = userId.replaceAll("[^\\w.-]", "_");
String objectId = String.format("%s.%s", issuerId, newUserId);
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardclass
GiftCardClass giftCardClass =
new GiftCardClass()
.setId(String.format("%s.%s", issuerId, classSuffix))
.setIssuerName("Issuer name")
.setReviewStatus("UNDER_REVIEW");
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardobject
GiftCardObject giftCardObject =
new GiftCardObject()
.setId(objectId)
.setClassId(String.format("%s.%s", issuerId, classSuffix))
.setState("ACTIVE")
.setHeroImage(
new Image()
.setSourceUri(
new ImageUri()
.setUri(
"https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"))
.setContentDescription(
new LocalizedString()
.setDefaultValue(
new TranslatedString()
.setLanguage("en-US")
.setValue("Hero image description"))))
.setTextModulesData(
Arrays.asList(
new TextModuleData()
.setHeader("Text module header")
.setBody("Text module body")
.setId("TEXT_MODULE_ID")))
.setLinksModuleData(
new LinksModuleData()
.setUris(
Arrays.asList(
new Uri()
.setUri("http://maps.google.com/")
.setDescription("Link module URI description")
.setId("LINK_MODULE_URI_ID"),
new Uri()
.setUri("tel:6505555555")
.setDescription("Link module tel description")
.setId("LINK_MODULE_TEL_ID"))))
.setImageModulesData(
Arrays.asList(
new ImageModuleData()
.setMainImage(
new Image()
.setSourceUri(
new ImageUri()
.setUri(
"http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"))
.setContentDescription(
new LocalizedString()
.setDefaultValue(
new TranslatedString()
.setLanguage("en-US")
.setValue("Image module description"))))
.setId("IMAGE_MODULE_ID")))
.setBarcode(new Barcode().setType("QR_CODE").setValue("QR code value"))
.setLocations(
Arrays.asList(
new LatLongPoint()
.setLatitude(37.424015499999996)
.setLongitude(-122.09259560000001)))
.setCardNumber("Card number")
.setPin("1234")
.setBalance(new Money().setMicros(20000000L).setCurrencyCode("USD"))
.setBalanceUpdateTime(new DateTime().setDate("2020-04-12T16:20:50.52-04:00"));
// Create the JWT as a HashMap object
HashMap<String, Object> claims = new HashMap<String, Object>();
claims.put("iss", ((ServiceAccountCredentials) credentials).getClientEmail());
claims.put("aud", "google");
claims.put("origins", Arrays.asList("www.example.com"));
claims.put("typ", "savetowallet");
// Create the Google Wallet payload and add to the JWT
HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put("giftCardClasses", Arrays.asList(giftCardClass));
payload.put("giftCardObjects", Arrays.asList(giftCardObject));
claims.put("payload", payload);
// The service account credentials are used to sign the JWT
Algorithm algorithm =
Algorithm.RSA256(
null, (RSAPrivateKey) ((ServiceAccountCredentials) credentials).getPrivateKey());
String token = JWT.create().withPayload(claims).sign(algorithm);
System.out.println("Add to Google Wallet link");
System.out.println(String.format("https://pay.google.com/gp/v/save/%s", token));
return String.format("https://pay.google.com/gp/v/save/%s", token);
}
// [END jwt]
// [START createIssuer]
/**
* Create a new Google Wallet issuer account.
*
* @param issuerName The issuer's name.
* @param issuerEmail The issuer's email address.
* @throws IOException
*/
public void CreateIssuerAccount(String issuerName, String issuerEmail) throws IOException {
// New issuer information
Issuer issuer =
new Issuer()
.setName(issuerName)
.setContactInfo(new IssuerContactInfo().setEmail(issuerEmail));
Issuer response = service.issuer().insert(issuer).execute();
System.out.println("Issuer insert response");
System.out.println(response.toPrettyString());
}
// [END createIssuer]
// [START updatePermissions]
/**
* Update permissions for an existing Google Wallet issuer account. <strong>Warning:</strong> This
* operation overwrites all existing permissions!
*
* <p>Example permissions list argument below. Copy the add entry as needed for each email address
* that will need access. Supported values for role are: 'READER', 'WRITER', and 'OWNER'
*
* <pre><code>
* ArrayList<Permission> permissions = new ArrayList<Permission>();
* permissions.add(new Permission().setEmailAddress("emailAddress").setRole("OWNER"));
* </code></pre>
*
* @param issuerId The issuer ID being used for this request.
* @param permissions The list of email addresses and roles to assign.
* @throws IOException
*/
public void UpdateIssuerAccountPermissions(String issuerId, ArrayList<Permission> permissions)
throws IOException {
Permissions response =
service
.permissions()
.update(
Long.parseLong(issuerId),
new Permissions().setIssuerId(Long.parseLong(issuerId)).setPermissions(permissions))
.execute();
System.out.println("Issuer permissions update response");
System.out.println(response.toPrettyString());
}
// [END updatePermissions]
// [START batch]
/**
* Batch create Google Wallet objects from an existing class.
*
* @param issuerId The issuer ID being used for this request.
* @param classSuffix Developer-defined unique ID for this pass class.
* @throws IOException
*/
public void BatchCreateGiftCardObjects(String issuerId, String classSuffix) throws IOException {
// Create the batch request client
BatchRequest batch = service.batch(new HttpCredentialsAdapter(credentials));
// The callback will be invoked for each request in the batch
JsonBatchCallback<GiftCardObject> callback =
new JsonBatchCallback<GiftCardObject>() {
// Invoked if the request was successful
public void onSuccess(GiftCardObject response, HttpHeaders responseHeaders) {
System.out.println(response.toString());
}
// Invoked if the request failed
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
// Example: Generate three new pass objects
for (int i = 0; i < 3; i++) {
// Generate a random user ID
String userId = UUID.randomUUID().toString().replaceAll("[^\\w.-]", "_");
// Generate a random object ID with the user ID
// Should only include alphanumeric characters, '.', '_', or '-'
String objectId = String.format("%s.%s", issuerId, userId);
// See link below for more information on required properties
// https://developers.google.com/wallet/retail/gift-cards/rest/v1/giftcardobject
GiftCardObject giftCardObject =
new GiftCardObject()
.setId(objectId)
.setClassId(String.format("%s.%s", issuerId, classSuffix))
.setState("ACTIVE")
.setHeroImage(
new Image()
.setSourceUri(
new ImageUri()
.setUri(
"https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"))
.setContentDescription(
new LocalizedString()
.setDefaultValue(
new TranslatedString()
.setLanguage("en-US")
.setValue("Hero image description"))))
.setTextModulesData(
Arrays.asList(
new TextModuleData()
.setHeader("Text module header")
.setBody("Text module body")
.setId("TEXT_MODULE_ID")))
.setLinksModuleData(
new LinksModuleData()
.setUris(
Arrays.asList(
new Uri()
.setUri("http://maps.google.com/")
.setDescription("Link module URI description")
.setId("LINK_MODULE_URI_ID"),
new Uri()
.setUri("tel:6505555555")
.setDescription("Link module tel description")
.setId("LINK_MODULE_TEL_ID"))))
.setImageModulesData(
Arrays.asList(
new ImageModuleData()
.setMainImage(
new Image()
.setSourceUri(
new ImageUri()
.setUri(
"http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"))
.setContentDescription(
new LocalizedString()
.setDefaultValue(
new TranslatedString()
.setLanguage("en-US")
.setValue("Image module description"))))
.setId("IMAGE_MODULE_ID")))
.setBarcode(new Barcode().setType("QR_CODE").setValue("QR code value"))
.setLocations(
Arrays.asList(
new LatLongPoint()
.setLatitude(37.424015499999996)
.setLongitude(-122.09259560000001)))
.setCardNumber("Card number")
.setPin("1234")
.setBalance(new Money().setMicros(20000000L).setCurrencyCode("USD"))
.setBalanceUpdateTime(new DateTime().setDate("2020-04-12T16:20:50.52-04:00"));
service.giftcardobject().insert(giftCardObject).queue(batch, callback);
}
// Invoke the batch API calls
batch.execute();
}
// [END batch]
}