-
Notifications
You must be signed in to change notification settings - Fork 124
/
demo_giftcard.go
326 lines (286 loc) · 9.67 KB
/
demo_giftcard.go
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
/*
* Copyright 2023 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]
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
oauthJwt "golang.org/x/oauth2/jwt"
"google.golang.org/api/option"
"google.golang.org/api/walletobjects/v1"
"io"
"log"
"os"
"strings"
)
// [END imports]
// [END setup]
type demoGiftcard struct {
credentials *oauthJwt.Config
service *walletobjects.Service
}
// [START auth]
// Create authenticated HTTP client using a service account file.
func (d *demoGiftcard) auth() {
credentialsFile := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
b, _ := os.ReadFile(credentialsFile)
credentials, err := google.JWTConfigFromJSON(b, walletobjects.WalletObjectIssuerScope)
if err != nil {
fmt.Println(err)
log.Fatalf("Unable to load credentials: %v", err)
}
d.credentials = credentials
d.service, _ = walletobjects.NewService(context.Background(), option.WithCredentialsFile(credentialsFile))
}
// [END auth]
// [START createClass]
// Create a class.
func (d *demoGiftcard) createClass(issuerId, classSuffix string) {
giftcardClass := new(walletobjects.GiftCardClass)
giftcardClass.Id = fmt.Sprintf("%s.%s", issuerId, classSuffix)
giftcardClass.IssuerName = "Issuer name"
giftcardClass.ReviewStatus = "UNDER_REVIEW"
res, err := d.service.Giftcardclass.Insert(giftcardClass).Do()
if err != nil {
log.Fatalf("Unable to insert class: %v", err)
} else {
fmt.Printf("Class insert id:\n%v\n", res.Id)
}
}
// [END createClass]
// [START createObject]
// Create an object.
func (d *demoGiftcard) createObject(issuerId, classSuffix, objectSuffix string) {
giftcardObject := new(walletobjects.GiftCardObject)
giftcardObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix)
giftcardObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix)
giftcardObject.State = "ACTIVE"
giftcardObject.CardNumber = "Card number"
giftcardObject.Pin = "1234"
giftcardObject.Balance = &walletobjects.Money{
Micros: 20000000,
CurrencyCode: "USD",
}
giftcardObject.BalanceUpdateTime = &walletobjects.DateTime{
Date: "2023-12-12T23:20:50.52Z",
}
giftcardObject.HeroImage = &walletobjects.Image{
SourceUri: &walletobjects.ImageUri{
Uri: "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
},
}
giftcardObject.Barcode = &walletobjects.Barcode{
Type: "QR_CODE",
Value: "QR code",
}
giftcardObject.Locations = []*walletobjects.LatLongPoint{
&walletobjects.LatLongPoint{
Latitude: 37.424015499999996,
Longitude: -122.09259560000001,
},
}
giftcardObject.LinksModuleData = &walletobjects.LinksModuleData{
Uris: []*walletobjects.Uri{
&walletobjects.Uri{
Id: "LINK_MODULE_URI_ID",
Uri: "http://maps.google.com/",
Description: "Link module URI description",
},
&walletobjects.Uri{
Id: "LINK_MODULE_TEL_ID",
Uri: "tel:6505555555",
Description: "Link module tel description",
},
},
}
giftcardObject.ImageModulesData = []*walletobjects.ImageModuleData{
&walletobjects.ImageModuleData{
Id: "IMAGE_MODULE_ID",
MainImage: &walletobjects.Image{
SourceUri: &walletobjects.ImageUri{
Uri: "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
},
},
},
}
giftcardObject.TextModulesData = []*walletobjects.TextModuleData{
&walletobjects.TextModuleData{
Body: "Text module body",
Header: "Text module header",
Id: "TEXT_MODULE_ID",
},
}
res, err := d.service.Giftcardobject.Insert(giftcardObject).Do()
if err != nil {
log.Fatalf("Unable to insert object: %v", err)
} else {
fmt.Printf("Object insert id:\n%s\n", res.Id)
}
}
// [END createObject]
// [START expireObject]
// Expire an object.
//
// Sets the object's state to Expired. If the valid time interval is
// already set, the pass will expire automatically up to 24 hours after.
func (d *demoGiftcard) expireObject(issuerId, objectSuffix string) {
giftcardObject := &walletobjects.GiftCardObject{
State: "EXPIRED",
}
res, err := d.service.Giftcardobject.Patch(fmt.Sprintf("%s.%s", issuerId, objectSuffix), giftcardObject).Do()
if err != nil {
log.Fatalf("Unable to patch object: %v", err)
} else {
fmt.Printf("Object expiration id:\n%s\n", res.Id)
}
}
// [END expireObject]
// [START jwtNew]
// Generate a signed JWT that creates a new pass class and object.
//
// 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.
func (d *demoGiftcard) createJwtNewObjects(issuerId, classSuffix, objectSuffix string) {
giftcardObject := new(walletobjects.GiftCardObject)
giftcardObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix)
giftcardObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix)
giftcardObject.State = "ACTIVE"
giftcardObject.CardNumber = "Card number"
giftcardJson, _ := json.Marshal(giftcardObject)
var payload map[string]any
json.Unmarshal([]byte(fmt.Sprintf(`
{
"giftcardObjects": [%s]
}
`, giftcardJson)), &payload)
claims := jwt.MapClaims{
"iss": d.credentials.Email,
"aud": "google",
"origins": []string{"www.example.com"},
"typ": "savetowallet",
"payload": payload,
}
// The service account credentials are used to sign the JWT
key, _ := jwt.ParseRSAPrivateKeyFromPEM(d.credentials.PrivateKey)
token, _ := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key)
fmt.Println("Add to Google Wallet link")
fmt.Println("https://pay.google.com/gp/v/save/" + token)
}
// [END jwtNew]
// [START jwtExisting]
// Generate a signed JWT that references an existing pass object.
// When the user opens the "Add to Google Wallet" URL and saves the pass to
// their wallet, the pass objects defined in the JWT are added to the
// user's Google Wallet app. This allows the user to save multiple pass
// objects in one API call.
func (d *demoGiftcard) createJwtExistingObjects(issuerId string, classSuffix string, objectSuffix string) {
var payload map[string]interface{}
json.Unmarshal([]byte(fmt.Sprintf(`
{
"eventTicketObjects": [{
"id": "%s.EVENT_OBJECT_SUFFIX",
"classId": "%s.EVENT_CLASS_SUFFIX"
}],
"flightObjects": [{
"id": "%s.FLIGHT_OBJECT_SUFFIX",
"classId": "%s.FLIGHT_CLASS_SUFFIX"
}],
"genericObjects": [{
"id": "%s.GENERIC_OBJECT_SUFFIX",
"classId": "%s.GENERIC_CLASS_SUFFIX"
}],
"giftCardObjects": [{
"id": "%s.GIFT_CARD_OBJECT_SUFFIX",
"classId": "%s.GIFT_CARD_CLASS_SUFFIX"
}],
"loyaltyObjects": [{
"id": "%s.LOYALTY_OBJECT_SUFFIX",
"classId": "%s.LOYALTY_CLASS_SUFFIX"
}],
"giftcardObjects": [{
"id": "%s.OFFER_OBJECT_SUFFIX",
"classId": "%s.OFFER_CLASS_SUFFIX"
}],
"transitObjects": [{
"id": "%s.TRANSIT_OBJECT_SUFFIX",
"classId": "%s.TRANSIT_CLASS_SUFFIX"
}]
}
`, issuerId)), &payload)
claims := jwt.MapClaims{
"iss": d.credentials.Email,
"aud": "google",
"origins": []string{"www.example.com"},
"typ": "savetowallet",
"payload": payload,
}
// The service account credentials are used to sign the JWT
key, _ := jwt.ParseRSAPrivateKeyFromPEM(d.credentials.PrivateKey)
token, _ := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key)
fmt.Println("Add to Google Wallet link")
fmt.Println("https://pay.google.com/gp/v/save/" + token)
}
// [END jwtExisting]
// [START batch]
// Batch create Google Wallet objects from an existing class.
func (d *demoGiftcard) batchCreateObjects(issuerId, classSuffix string) {
data := ""
for i := 0; i < 3; i++ {
objectSuffix := strings.ReplaceAll(uuid.New().String(), "-", "_")
giftcardObject := new(walletobjects.GiftCardObject)
giftcardObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix)
giftcardObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix)
giftcardObject.State = "ACTIVE"
giftcardObject.CardNumber = "Card number"
giftcardJson, _ := json.Marshal(giftcardObject)
batchObject := fmt.Sprintf("%s", giftcardJson)
data += "--batch_createobjectbatch\n"
data += "Content-Type: application/json\n\n"
data += "POST /walletobjects/v1/giftCardObject\n\n"
data += batchObject + "\n\n"
}
data += "--batch_createobjectbatch--"
res, err := d.credentials.Client(oauth2.NoContext).Post("https://walletobjects.googleapis.com/batch", "multipart/mixed; boundary=batch_createobjectbatch", bytes.NewBuffer([]byte(data)))
if err != nil {
fmt.Println(err)
} else {
b, _ := io.ReadAll(res.Body)
fmt.Printf("Batch insert response:\n%s\n", b)
}
}
// [END batch]
func main() {
issuerId := os.Getenv("WALLET_ISSUER_ID")
classSuffix := strings.ReplaceAll(uuid.New().String(), "-", "_")
objectSuffix := fmt.Sprintf("%s-%s", strings.ReplaceAll(uuid.New().String(), "-", "_"), classSuffix)
d := demoGiftcard{}
d.auth()
d.createClass(issuerId, classSuffix)
d.createObject(issuerId, classSuffix, objectSuffix)
d.expireObject(issuerId, objectSuffix)
d.createJwtNewObjects(issuerId, classSuffix, objectSuffix)
d.createJwtExistingObjects(issuerId, classSuffix, objectSuffix)
d.batchCreateObjects(issuerId, classSuffix)
}