forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore_purchase.go
562 lines (508 loc) · 17.9 KB
/
core_purchase.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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// Copyright 2018 The Nakama Authors
//
// 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.
package server
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"encoding/gob"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/heroiclabs/nakama-common/api"
"github.com/heroiclabs/nakama/v3/iap"
"github.com/jackc/pgtype"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
var ErrPurchasesListInvalidCursor = errors.New("purchases list cursor invalid")
var httpc = &http.Client{Timeout: 5 * time.Second}
func ValidatePurchasesApple(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, password, receipt string) (*api.ValidatePurchaseResponse, error) {
validation, raw, err := iap.ValidateReceiptApple(ctx, httpc, receipt, password)
if err != nil {
var vErr *iap.ValidationError
if err != context.Canceled {
if errors.As(err, &vErr) {
logger.Error("Error validating Apple receipt", zap.Error(vErr.Err), zap.Int("status_code", vErr.StatusCode), zap.String("payload", vErr.Payload))
return nil, vErr.Err
} else {
logger.Error("Error validating Apple receipt", zap.Error(err))
}
}
return nil, err
}
if validation.Status != iap.AppleReceiptIsValid {
if validation.IsRetryable == true {
return nil, status.Error(codes.Unavailable, "Apple IAP verification is currently unavailable. Try again later.")
}
return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Invalid Receipt. Status: %d", validation.Status))
}
env := api.ValidatedPurchase_PRODUCTION
if validation.Environment == iap.AppleSandboxEnvironment {
env = api.ValidatedPurchase_SANDBOX
}
storagePurchases := make([]*storagePurchase, 0, len(validation.Receipt.InApp))
for _, purchase := range validation.Receipt.InApp {
pt, err := strconv.Atoi(purchase.PurchaseDateMs)
if err != nil {
return nil, err
}
storagePurchases = append(storagePurchases, &storagePurchase{
userID: userID,
store: api.ValidatedPurchase_APPLE_APP_STORE,
productId: purchase.ProductID,
transactionId: purchase.TransactionId,
rawResponse: string(raw),
purchaseTime: parseMillisecondUnixTimestamp(pt),
environment: env,
})
}
purchases, err := storePurchases(ctx, db, storagePurchases)
if err != nil {
return nil, err
}
validatedPurchases := make([]*api.ValidatedPurchase, 0, len(purchases))
for _, p := range purchases {
validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
ProductId: p.productId,
TransactionId: p.transactionId,
Store: p.store,
PurchaseTime: ×tamppb.Timestamp{Seconds: p.purchaseTime.Unix()},
CreateTime: ×tamppb.Timestamp{Seconds: p.createTime.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: p.updateTime.Unix()},
ProviderResponse: string(raw),
Environment: p.environment,
})
}
return &api.ValidatePurchaseResponse{
ValidatedPurchases: validatedPurchases,
}, nil
}
func ValidatePurchaseGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, config *IAPGoogleConfig, receipt string) (*api.ValidatePurchaseResponse, error) {
_, gReceipt, raw, err := iap.ValidateReceiptGoogle(ctx, httpc, config.ClientEmail, config.PrivateKey, receipt)
if err != nil {
var vErr *iap.ValidationError
if err != context.Canceled {
if errors.As(err, &vErr) {
logger.Error("Error validating Google receipt", zap.Error(vErr.Err), zap.Int("status_code", vErr.StatusCode), zap.String("payload", vErr.Payload))
return nil, vErr.Err
} else {
logger.Error("Error validating Google receipt", zap.Error(err))
}
}
return nil, err
}
purchases, err := storePurchases(ctx, db, []*storagePurchase{
{
userID: userID,
store: api.ValidatedPurchase_GOOGLE_PLAY_STORE,
productId: gReceipt.ProductID,
transactionId: gReceipt.PurchaseToken,
rawResponse: string(raw),
purchaseTime: parseMillisecondUnixTimestamp(int(gReceipt.PurchaseTime)),
environment: api.ValidatedPurchase_UNKNOWN,
},
})
if err != nil {
if err != context.Canceled {
logger.Error("Error storing Google receipt", zap.Error(err))
}
return nil, err
}
validatedPurchases := make([]*api.ValidatedPurchase, 0, len(purchases))
for _, p := range purchases {
validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
ProductId: p.productId,
TransactionId: p.transactionId,
Store: p.store,
PurchaseTime: ×tamppb.Timestamp{Seconds: p.purchaseTime.Unix()},
CreateTime: ×tamppb.Timestamp{Seconds: p.createTime.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: p.updateTime.Unix()},
ProviderResponse: string(raw),
Environment: p.environment,
})
}
return &api.ValidatePurchaseResponse{
ValidatedPurchases: validatedPurchases,
}, nil
}
func ValidatePurchaseHuawei(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, config *IAPHuaweiConfig, inAppPurchaseData, signature string) (*api.ValidatePurchaseResponse, error) {
validation, data, raw, err := iap.ValidateReceiptHuawei(ctx, httpc, config.PublicKey, config.ClientID, config.ClientSecret, inAppPurchaseData, signature)
if err != nil {
var vErr *iap.ValidationError
if err != context.Canceled {
if errors.As(err, &vErr) {
logger.Error("Error validating Huawei receipt", zap.Error(vErr.Err), zap.Int("status_code", vErr.StatusCode), zap.String("payload", vErr.Payload))
return nil, vErr.Err
} else {
logger.Error("Error validating Huawei receipt", zap.Error(err))
}
}
return nil, err
}
if validation.ResponseCode != strconv.Itoa(iap.HuaweiReceiptIsValid) {
return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Invalid Receipt. Code: %s", validation.ResponseCode))
}
env := api.ValidatedPurchase_PRODUCTION
if data.PurchaseType == iap.HuaweiSandboxPurchaseType {
env = api.ValidatedPurchase_SANDBOX
}
purchases, err := storePurchases(ctx, db, []*storagePurchase{
{
userID: userID,
store: api.ValidatedPurchase_HUAWEI_APP_GALLERY,
productId: validation.PurchaseTokenData.ProductId,
transactionId: validation.PurchaseTokenData.PurchaseToken,
rawResponse: string(raw),
purchaseTime: parseMillisecondUnixTimestamp(int(data.PurchaseTime)),
environment: env,
},
})
if err != nil {
if err != context.Canceled {
logger.Error("Error storing Huawei receipt", zap.Error(err))
}
return nil, err
}
validatedPurchases := make([]*api.ValidatedPurchase, 0, len(purchases))
for _, p := range purchases {
validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
ProductId: p.productId,
TransactionId: p.transactionId,
Store: p.store,
PurchaseTime: ×tamppb.Timestamp{Seconds: p.purchaseTime.Unix()},
CreateTime: ×tamppb.Timestamp{Seconds: p.createTime.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: p.updateTime.Unix()},
ProviderResponse: string(raw),
Environment: p.environment,
})
}
return &api.ValidatePurchaseResponse{
ValidatedPurchases: validatedPurchases,
}, nil
}
type purchasesListCursor struct {
TransactionId string
PurchaseTime *timestamppb.Timestamp
UserId string
IsNext bool
}
func GetPurchaseByTransactionID(ctx context.Context, logger *zap.Logger, db *sql.DB, transactionID string) (string, *api.ValidatedPurchase, error) {
query := `
SELECT
user_id,
transaction_id,
product_id,
store,
raw_response,
purchase_time,
create_time,
update_time,
environment
FROM
purchase
WHERE
transaction_id = $1
`
var userID uuid.UUID
var transactionId string
var productId string
var store api.ValidatedPurchase_Store
var rawResponse string
var purchaseTime pgtype.Timestamptz
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
var environment api.ValidatedPurchase_Environment
if err := db.QueryRowContext(ctx, query, transactionID).Scan(&userID, &transactionId, &productId, &store, &rawResponse, &purchaseTime, &createTime, &updateTime, &environment); err != nil {
logger.Error("Error retrieving purchase.", zap.Error(err))
return "", nil, err
}
return userID.String(), &api.ValidatedPurchase{
ProductId: productId,
TransactionId: transactionID,
Store: store,
ProviderResponse: rawResponse,
PurchaseTime: ×tamppb.Timestamp{Seconds: purchaseTime.Time.Unix()},
CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()},
Environment: environment,
}, nil
}
func ListPurchases(ctx context.Context, logger *zap.Logger, db *sql.DB, userID string, limit int, cursor string) (*api.PurchaseList, error) {
var incomingCursor *purchasesListCursor
if cursor != "" {
cb, err := base64.URLEncoding.DecodeString(cursor)
if err != nil {
return nil, ErrPurchasesListInvalidCursor
}
incomingCursor = &purchasesListCursor{}
if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil {
return nil, ErrPurchasesListInvalidCursor
}
if userID != "" && userID != incomingCursor.UserId {
// userID filter was set and has changed, cursor is now invalid
return nil, ErrPurchasesListInvalidCursor
}
}
comparationOp := "<="
sortConf := "DESC"
if incomingCursor != nil && !incomingCursor.IsNext {
comparationOp = ">"
sortConf = "ASC"
}
params := make([]interface{}, 0, 4)
predicateConf := ""
if incomingCursor != nil {
if userID == "" {
predicateConf = fmt.Sprintf(" WHERE (user_id, purchase_time, transaction_id) %s ($1, $2, $3)", comparationOp)
} else {
predicateConf = fmt.Sprintf(" WHERE user_id = $1 AND (purchase_time, transaction_id) %s ($2, $3)", comparationOp)
}
params = append(params, incomingCursor.UserId, incomingCursor.PurchaseTime.AsTime(), incomingCursor.TransactionId)
} else {
if userID != "" {
predicateConf = " WHERE user_id = $1"
params = append(params, userID)
}
}
if limit > 0 {
params = append(params, limit+1)
} else {
params = append(params, 101) // Default limit to 100 purchases if not set
}
query := fmt.Sprintf(`
SELECT
user_id,
transaction_id,
product_id,
store,
raw_response,
purchase_time,
create_time,
update_time,
environment
FROM
purchase
%s
ORDER BY purchase_time %s LIMIT $%v`, predicateConf, sortConf, len(params))
rows, err := db.QueryContext(ctx, query, params...)
if err != nil {
logger.Error("Error retrieving purchases.", zap.Error(err))
return nil, err
}
defer rows.Close()
var nextCursor *purchasesListCursor
var prevCursor *purchasesListCursor
purchases := make([]*api.ValidatedPurchase, 0, limit)
for rows.Next() {
var userID uuid.UUID
var transactionId string
var productId string
var store api.ValidatedPurchase_Store
var rawResponse string
var purchaseTime pgtype.Timestamptz
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
var environment api.ValidatedPurchase_Environment
if err = rows.Scan(&userID, &transactionId, &productId, &store, &rawResponse, &purchaseTime, &createTime, &updateTime, &environment); err != nil {
logger.Error("Error retrieving purchases.", zap.Error(err))
return nil, err
}
if len(purchases) >= limit {
nextCursor = &purchasesListCursor{
TransactionId: transactionId,
PurchaseTime: timestamppb.New(purchaseTime.Time),
UserId: userID.String(),
IsNext: true,
}
break
}
purchase := &api.ValidatedPurchase{
ProductId: productId,
TransactionId: transactionId,
Store: store,
PurchaseTime: ×tamppb.Timestamp{Seconds: purchaseTime.Time.Unix()},
CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()},
ProviderResponse: rawResponse,
Environment: environment,
}
purchases = append(purchases, purchase)
if incomingCursor != nil && prevCursor == nil {
prevCursor = &purchasesListCursor{
TransactionId: transactionId,
PurchaseTime: timestamppb.New(purchaseTime.Time),
UserId: userID.String(),
IsNext: false,
}
}
}
if err = rows.Err(); err != nil {
logger.Error("Error retrieving purchases.", zap.Error(err))
return nil, err
}
if incomingCursor != nil && !incomingCursor.IsNext {
if nextCursor != nil && prevCursor != nil {
nextCursor, nextCursor.IsNext, prevCursor, prevCursor.IsNext = prevCursor, prevCursor.IsNext, nextCursor, nextCursor.IsNext
} else if nextCursor != nil {
nextCursor, prevCursor = nil, nextCursor
prevCursor.IsNext = !prevCursor.IsNext
} else if prevCursor != nil {
nextCursor, prevCursor = prevCursor, nil
nextCursor.IsNext = !nextCursor.IsNext
}
for i, j := 0, len(purchases)-1; i < j; i, j = i+1, j-1 {
purchases[i], purchases[j] = purchases[j], purchases[i]
}
}
var nextCursorStr string
if nextCursor != nil {
cursorBuf := new(bytes.Buffer)
if err := gob.NewEncoder(cursorBuf).Encode(nextCursor); err != nil {
logger.Error("Error creating purchases list cursor", zap.Error(err))
return nil, err
}
nextCursorStr = base64.URLEncoding.EncodeToString(cursorBuf.Bytes())
}
var prevCursorStr string
if prevCursor != nil {
cursorBuf := new(bytes.Buffer)
if err := gob.NewEncoder(cursorBuf).Encode(prevCursor); err != nil {
logger.Error("Error creating purchases list cursor", zap.Error(err))
return nil, err
}
prevCursorStr = base64.URLEncoding.EncodeToString(cursorBuf.Bytes())
}
return &api.PurchaseList{ValidatedPurchases: purchases, Cursor: nextCursorStr, PrevCursor: prevCursorStr}, nil
}
type storagePurchase struct {
userID uuid.UUID
store api.ValidatedPurchase_Store
productId string
transactionId string
rawResponse string
purchaseTime time.Time
createTime time.Time // Set by storePurchases
updateTime time.Time // Set by storePurchases
environment api.ValidatedPurchase_Environment
seenBefore bool // Set by storePurchases
}
func storePurchases(ctx context.Context, db *sql.DB, purchases []*storagePurchase) ([]*storagePurchase, error) {
if len(purchases) < 1 {
return nil, errors.New("expects at least one receipt")
}
statements := make([]string, 0, len(purchases))
params := make([]interface{}, 0, len(purchases)*7)
transactionIDsToPurchase := make(map[string]*storagePurchase)
offset := 0
for _, purchase := range purchases {
statement := fmt.Sprintf("($%d, $%d, $%d, $%d, $%d, $%d, $%d)", offset+1, offset+2, offset+3, offset+4, offset+5, offset+6, offset+7)
offset += 7
statements = append(statements, statement)
params = append(params, purchase.userID, purchase.store, purchase.transactionId, purchase.productId, purchase.purchaseTime, purchase.rawResponse, purchase.environment)
transactionIDsToPurchase[purchase.transactionId] = purchase
}
query := `
INSERT
INTO
purchase
(
user_id,
store,
transaction_id,
product_id,
purchase_time,
raw_response,
environment
)
VALUES
` + strings.Join(statements, ", ") + `
ON CONFLICT
(transaction_id)
DO
NOTHING
RETURNING
transaction_id, create_time, update_time
`
insertedTransactionIDs := make(map[string]struct{})
rows, err := db.QueryContext(ctx, query, params...)
if err != nil {
return nil, err
}
for rows.Next() {
// Newly inserted purchases
var transactionId string
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
if err = rows.Scan(&transactionId, &createTime, &updateTime); err != nil {
rows.Close()
return nil, err
}
storedPurchase, _ := transactionIDsToPurchase[transactionId]
storedPurchase.createTime = createTime.Time
storedPurchase.updateTime = updateTime.Time
storedPurchase.seenBefore = false
insertedTransactionIDs[storedPurchase.transactionId] = struct{}{}
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
// Go over purchases that have not been inserted (already exist in the DB) and fetch createTime and updateTime
if len(transactionIDsToPurchase) > len(insertedTransactionIDs) {
seenIDs := make([]string, 0, len(transactionIDsToPurchase))
for tID, _ := range transactionIDsToPurchase {
if _, ok := insertedTransactionIDs[tID]; !ok {
seenIDs = append(seenIDs, tID)
}
}
rows, err = db.QueryContext(ctx, "SELECT transaction_id, create_time, update_time FROM purchase WHERE transaction_id IN ($1)", strings.Join(seenIDs, ", "))
if err != nil {
return nil, err
}
for rows.Next() {
// Already seen purchases
var transactionId string
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
if err = rows.Scan(&transactionId, &createTime, &updateTime); err != nil {
rows.Close()
return nil, err
}
storedPurchase, _ := transactionIDsToPurchase[transactionId]
storedPurchase.createTime = createTime.Time
storedPurchase.updateTime = updateTime.Time
storedPurchase.seenBefore = true
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
}
storedPurchases := make([]*storagePurchase, 0, len(transactionIDsToPurchase))
for _, purchase := range transactionIDsToPurchase {
storedPurchases = append(storedPurchases, purchase)
}
return storedPurchases, nil
}
func parseMillisecondUnixTimestamp(t int) time.Time {
return time.Unix(0, 0).Add(time.Duration(t) * time.Millisecond)
}