forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore_subscription.go
1210 lines (1072 loc) · 40.5 KB
/
core_subscription.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 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"
"crypto/ecdsa"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid/v5"
"github.com/heroiclabs/nakama-common/api"
"github.com/heroiclabs/nakama/v3/iap"
"github.com/jackc/pgconn"
"github.com/jackc/pgerrcode"
"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 ErrSubscriptionsListInvalidCursor = errors.New("subscriptions list cursor invalid")
var ErrSubscriptionNotFound = errors.New("subscription not found")
type subscriptionsListCursor struct {
OriginalTransactionId string
PurchaseTime *timestamppb.Timestamp
UserId string
IsNext bool
}
func ListSubscriptions(ctx context.Context, logger *zap.Logger, db *sql.DB, userID string, limit int, cursor string) (*api.SubscriptionList, error) {
var incomingCursor *subscriptionsListCursor
if cursor != "" {
cb, err := base64.URLEncoding.DecodeString(cursor)
if err != nil {
return nil, ErrSubscriptionsListInvalidCursor
}
incomingCursor = &subscriptionsListCursor{}
if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil {
return nil, ErrSubscriptionsListInvalidCursor
}
if userID != "" && userID != incomingCursor.UserId {
// userID filter was set and has changed, cursor is now invalid
return nil, ErrSubscriptionsListInvalidCursor
}
}
comparisonOp := "<="
sortConf := "DESC"
if incomingCursor != nil && !incomingCursor.IsNext {
comparisonOp = ">"
sortConf = "ASC"
}
params := make([]interface{}, 0, 4)
predicateConf := ""
if incomingCursor != nil {
if userID == "" {
predicateConf = fmt.Sprintf(" WHERE (user_id, purchase_time, original_transaction_id) %s ($1, $2, $3)", comparisonOp)
} else {
predicateConf = fmt.Sprintf(" WHERE user_id = $1 AND (purchase_time, original_transaction_id) %s ($2, $3)", comparisonOp)
}
params = append(params, incomingCursor.UserId, incomingCursor.PurchaseTime.AsTime(), incomingCursor.OriginalTransactionId)
} 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 subscriptions if not set
}
query := fmt.Sprintf(`
SELECT
original_transaction_id,
user_id,
product_id,
store,
purchase_time,
create_time,
update_time,
expire_time,
refund_time,
environment,
raw_response,
raw_notification
FROM
subscription
%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 subscriptions.", zap.Error(err))
return nil, err
}
defer rows.Close()
var nextCursor *purchasesListCursor
var prevCursor *purchasesListCursor
subscriptions := make([]*api.ValidatedSubscription, 0, limit)
for rows.Next() {
var originalTransactionId string
var dbUserID uuid.UUID
var productId string
var store api.StoreProvider
var purchaseTime pgtype.Timestamptz
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
var expireTime pgtype.Timestamptz
var refundTime pgtype.Timestamptz
var environment api.StoreEnvironment
var rawResponse string
var rawNotification string
if err = rows.Scan(&originalTransactionId, &dbUserID, &productId, &store, &purchaseTime, &createTime, &updateTime, &expireTime, &refundTime, &environment, &rawResponse, &rawNotification); err != nil {
logger.Error("Error retrieving subscriptions.", zap.Error(err))
return nil, err
}
if len(subscriptions) >= limit {
nextCursor = &purchasesListCursor{
TransactionId: originalTransactionId,
PurchaseTime: timestamppb.New(purchaseTime.Time),
UserId: dbUserID.String(),
IsNext: true,
}
break
}
active := false
if expireTime.Time.After(time.Now()) {
active = true
}
if refundTime.Time.Unix() > 0 {
active = false
}
suid := dbUserID.String()
if dbUserID.IsNil() {
suid = ""
}
subscription := &api.ValidatedSubscription{
UserId: suid,
ProductId: productId,
OriginalTransactionId: originalTransactionId,
Store: store,
PurchaseTime: timestamppb.New(purchaseTime.Time),
CreateTime: timestamppb.New(createTime.Time),
UpdateTime: timestamppb.New(updateTime.Time),
ExpiryTime: timestamppb.New(expireTime.Time),
RefundTime: timestamppb.New(refundTime.Time),
Active: active,
Environment: environment,
ProviderResponse: rawResponse,
ProviderNotification: rawNotification,
}
subscriptions = append(subscriptions, subscription)
if incomingCursor != nil && prevCursor == nil {
prevCursor = &purchasesListCursor{
TransactionId: originalTransactionId,
PurchaseTime: timestamppb.New(purchaseTime.Time),
UserId: dbUserID.String(),
IsNext: false,
}
}
}
if err = rows.Err(); err != nil {
logger.Error("Error retrieving subscriptions.", 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(subscriptions)-1; i < j; i, j = i+1, j-1 {
subscriptions[i], subscriptions[j] = subscriptions[j], subscriptions[i]
}
}
var nextCursorStr string
if nextCursor != nil {
cursorBuf := new(bytes.Buffer)
if err := gob.NewEncoder(cursorBuf).Encode(nextCursor); err != nil {
logger.Error("Error creating subscriptions 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 subscriptions list cursor", zap.Error(err))
return nil, err
}
prevCursorStr = base64.URLEncoding.EncodeToString(cursorBuf.Bytes())
}
return &api.SubscriptionList{ValidatedSubscriptions: subscriptions, Cursor: nextCursorStr, PrevCursor: prevCursorStr}, nil
}
func ValidateSubscriptionApple(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, password, receipt string, persist bool) (*api.ValidateSubscriptionResponse, error) {
validation, rawResponse, err := iap.ValidateReceiptApple(ctx, httpc, receipt, password)
if err != nil {
if err != context.Canceled {
var vErr *iap.ValidationError
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
} else {
logger.Error("Error validating Apple receipt", zap.Error(err))
}
}
return nil, err
}
if validation.Status != iap.AppleReceiptIsValid {
if validation.IsRetryable {
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.StoreEnvironment_PRODUCTION
if validation.Environment == iap.AppleSandboxEnvironment {
env = api.StoreEnvironment_SANDBOX
}
var found bool
var receiptInfo iap.ValidateReceiptAppleResponseLatestReceiptInfo
for _, latestReceiptInfo := range validation.LatestReceiptInfo {
if latestReceiptInfo.ExpiresDateMs == "" {
// Not a subscription, skip.
continue
}
receiptInfo = latestReceiptInfo
found = true
}
if !found {
// Receipt is for a purchase (or otherwise has no subscriptions for any reason) so ValidatePurchaseApple should be used instead.
return nil, status.Error(codes.FailedPrecondition, "Purchase Receipt. Use the appropriate function instead.")
}
purchaseTime, err := strconv.ParseInt(receiptInfo.OriginalPurchaseDateMs, 10, 64)
if err != nil {
return nil, err
}
expireTimeInt, err := strconv.ParseInt(receiptInfo.ExpiresDateMs, 10, 64)
if err != nil {
return nil, err
}
expireTime := parseMillisecondUnixTimestamp(expireTimeInt)
active := false
if expireTime.After(time.Now()) {
active = true
}
storageSub := &storageSubscription{
userID: userID,
store: api.StoreProvider_APPLE_APP_STORE,
productId: receiptInfo.ProductId,
originalTransactionId: receiptInfo.OriginalTransactionId,
purchaseTime: parseMillisecondUnixTimestamp(purchaseTime),
environment: env,
expireTime: expireTime,
rawResponse: string(rawResponse),
}
validatedSub := &api.ValidatedSubscription{
UserId: storageSub.userID.String(),
ProductId: storageSub.productId,
OriginalTransactionId: storageSub.originalTransactionId,
Store: api.StoreProvider_APPLE_APP_STORE,
PurchaseTime: timestamppb.New(storageSub.purchaseTime),
Environment: env,
Active: active,
ExpiryTime: timestamppb.New(storageSub.expireTime),
ProviderResponse: storageSub.rawResponse,
ProviderNotification: storageSub.rawNotification,
}
if !persist {
return &api.ValidateSubscriptionResponse{ValidatedSubscription: validatedSub}, nil
}
if err = upsertSubscription(ctx, db, storageSub); err != nil {
return nil, err
}
suid := storageSub.userID.String()
if storageSub.userID.IsNil() {
suid = ""
}
validatedSub.UserId = suid
validatedSub.CreateTime = timestamppb.New(storageSub.createTime)
validatedSub.UpdateTime = timestamppb.New(storageSub.updateTime)
validatedSub.ProviderResponse = storageSub.rawResponse
validatedSub.ProviderNotification = storageSub.rawNotification
return &api.ValidateSubscriptionResponse{ValidatedSubscription: validatedSub}, nil
}
func ValidateSubscriptionGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, config *IAPGoogleConfig, receipt string, persist bool) (*api.ValidateSubscriptionResponse, error) {
gResponse, gReceipt, rawResponse, err := iap.ValidateSubscriptionReceiptGoogle(ctx, httpc, config.ClientEmail, config.PrivateKey, receipt)
if err != nil {
if err != context.Canceled {
var vErr *iap.ValidationError
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
} else {
logger.Error("Error validating Google receipt", zap.Error(err))
}
}
return nil, err
}
purchaseEnv := api.StoreEnvironment_PRODUCTION
if gResponse.PurchaseType == 0 {
purchaseEnv = api.StoreEnvironment_SANDBOX
}
expireTimeInt, err := strconv.ParseInt(gResponse.ExpiryTimeMillis, 10, 64)
if err != nil {
return nil, err
}
expireTime := parseMillisecondUnixTimestamp(expireTimeInt)
active := false
if expireTime.After(time.Now()) {
active = true
}
storageSub := &storageSubscription{
originalTransactionId: gReceipt.PurchaseToken,
userID: userID,
store: api.StoreProvider_GOOGLE_PLAY_STORE,
productId: gReceipt.ProductID,
purchaseTime: parseMillisecondUnixTimestamp(gReceipt.PurchaseTime),
environment: purchaseEnv,
expireTime: expireTime,
rawResponse: string(rawResponse),
}
if gResponse.LinkedPurchaseToken != "" {
// https://medium.com/androiddevelopers/implementing-linkedpurchasetoken-correctly-to-prevent-duplicate-subscriptions-82dfbf7167da
storageSub.originalTransactionId = gResponse.LinkedPurchaseToken
}
validatedSub := &api.ValidatedSubscription{
UserId: userID.String(),
ProductId: storageSub.productId,
OriginalTransactionId: storageSub.originalTransactionId,
Store: storageSub.store,
PurchaseTime: timestamppb.New(storageSub.purchaseTime),
Environment: storageSub.environment,
Active: active,
ExpiryTime: timestamppb.New(storageSub.expireTime),
ProviderResponse: storageSub.rawResponse,
ProviderNotification: storageSub.rawNotification,
}
if !persist {
return &api.ValidateSubscriptionResponse{ValidatedSubscription: validatedSub}, nil
}
if err = upsertSubscription(ctx, db, storageSub); err != nil {
return nil, err
}
suid := storageSub.userID.String()
if storageSub.userID.IsNil() {
suid = ""
}
validatedSub.UserId = suid
validatedSub.CreateTime = timestamppb.New(storageSub.createTime)
validatedSub.UpdateTime = timestamppb.New(storageSub.updateTime)
validatedSub.ProviderResponse = storageSub.rawResponse
validatedSub.ProviderNotification = storageSub.rawNotification
return &api.ValidateSubscriptionResponse{ValidatedSubscription: validatedSub}, nil
}
func GetSubscriptionByProductId(ctx context.Context, logger *zap.Logger, db *sql.DB, userID, productID string) (*api.ValidatedSubscription, error) {
var originalTransactionId string
var dbUserID uuid.UUID
var dbProductID string
var store api.StoreProvider
var purchaseTime pgtype.Timestamptz
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
var expireTime pgtype.Timestamptz
var environment api.StoreEnvironment
var rawResponse string
var rawNotification string
if err := db.QueryRowContext(ctx, `
SELECT
original_transaction_id,
user_id,
product_id,
store,
purchase_time,
create_time,
update_time,
expire_time,
environment,
raw_response,
raw_notification
FROM
subscription
WHERE
user_id = $1 AND
product_id = $2
`, userID, productID).Scan(&originalTransactionId, &dbUserID, &dbProductID, &store, &purchaseTime, &createTime, &updateTime, &expireTime, &environment, &rawResponse, &rawNotification); err != nil {
if err == sql.ErrNoRows {
return nil, ErrSubscriptionNotFound
}
logger.Error("Failed to get subscription", zap.Error(err))
return nil, err
}
active := false
if expireTime.Time.After(time.Now()) {
active = true
}
suid := dbUserID.String()
if dbUserID.IsNil() {
suid = ""
}
return &api.ValidatedSubscription{
UserId: suid,
ProductId: productID,
OriginalTransactionId: originalTransactionId,
Store: store,
PurchaseTime: timestamppb.New(purchaseTime.Time),
CreateTime: timestamppb.New(createTime.Time),
UpdateTime: timestamppb.New(updateTime.Time),
Environment: environment,
ExpiryTime: timestamppb.New(expireTime.Time),
Active: active,
ProviderResponse: rawResponse,
ProviderNotification: rawNotification,
}, nil
}
func getSubscriptionByOriginalTransactionId(ctx context.Context, db *sql.DB, originalTransactionId string) (*api.ValidatedSubscription, error) {
var (
dbUserId uuid.UUID
dbStore api.StoreProvider
dbOriginalTransactionId string
dbCreateTime pgtype.Timestamptz
dbUpdateTime pgtype.Timestamptz
dbExpireTime pgtype.Timestamptz
dbPurchaseTime pgtype.Timestamptz
dbRefundTime pgtype.Timestamptz
dbProductId string
dbEnvironment api.StoreEnvironment
dbRawResponse string
dbRawNotification string
)
err := db.QueryRowContext(ctx, `
SELECT
user_id,
store,
original_transaction_id,
create_time,
update_time,
expire_time,
purchase_time,
refund_time,
product_id,
environment,
raw_response,
raw_notification
FROM subscription
WHERE original_transaction_id = $1
`, originalTransactionId).Scan(&dbUserId, &dbStore, &dbOriginalTransactionId, &dbCreateTime, &dbUpdateTime, &dbExpireTime, &dbPurchaseTime, &dbRefundTime, &dbProductId, &dbEnvironment, &dbRawResponse, &dbRawNotification)
if err != nil {
return nil, err
}
active := false
if dbExpireTime.Time.After(time.Now()) && dbRefundTime.Time.Unix() == 0 {
active = true
}
suid := dbUserId.String()
if dbUserId.IsNil() {
suid = ""
}
return &api.ValidatedSubscription{
UserId: suid,
ProductId: dbProductId,
OriginalTransactionId: dbOriginalTransactionId,
Store: dbStore,
PurchaseTime: timestamppb.New(dbPurchaseTime.Time),
CreateTime: timestamppb.New(dbCreateTime.Time),
UpdateTime: timestamppb.New(dbUpdateTime.Time),
Environment: dbEnvironment,
ExpiryTime: timestamppb.New(dbExpireTime.Time),
RefundTime: timestamppb.New(dbRefundTime.Time),
ProviderResponse: dbRawResponse,
ProviderNotification: dbRawNotification,
Active: active,
}, nil
}
type storageSubscription struct {
originalTransactionId string
userID uuid.UUID
store api.StoreProvider
productId string
purchaseTime time.Time
createTime time.Time // Set by upsertSubscription
updateTime time.Time // Set by upsertSubscription
refundTime time.Time
environment api.StoreEnvironment
expireTime time.Time
rawResponse string
rawNotification string
}
func upsertSubscription(ctx context.Context, db *sql.DB, sub *storageSubscription) error {
if sub.refundTime.IsZero() {
// Refund time not set, init as default value.
sub.refundTime = time.Unix(0, 0)
}
query := `
INSERT
INTO
subscription
(
user_id,
store,
original_transaction_id,
product_id,
purchase_time,
environment,
expire_time,
raw_response,
raw_notification,
refund_time
)
VALUES
($1, $2, $3, $4, $5, $6, $7, to_jsonb(coalesce(nullif($8, ''), '{}')), to_jsonb(coalesce(nullif($9, ''), '{}')), $10)
ON CONFLICT
(original_transaction_id)
DO
UPDATE SET
expire_time = $7,
update_time = now(),
raw_response = coalesce(to_jsonb(nullif($8, '')), subscription.raw_response::jsonb),
raw_notification = coalesce(to_jsonb(nullif($9, '')), subscription.raw_notification::jsonb),
refund_time = coalesce($10, subscription.refund_time)
RETURNING
user_id, create_time, update_time, expire_time, refund_time, raw_response, raw_notification
`
var (
userID uuid.UUID
createTime pgtype.Timestamptz
updateTime pgtype.Timestamptz
expireTime pgtype.Timestamptz
refundTime pgtype.Timestamptz
rawResponse string
rawNotification string
)
if err := db.QueryRowContext(ctx, query, sub.userID, sub.store, sub.originalTransactionId, sub.productId, sub.purchaseTime, sub.environment, sub.expireTime, sub.rawResponse, sub.rawNotification, sub.refundTime).Scan(&userID, &createTime, &updateTime, &expireTime, &refundTime, &rawResponse, &rawNotification); err != nil {
return err
}
sub.userID = userID
sub.createTime = createTime.Time
sub.updateTime = updateTime.Time
sub.expireTime = expireTime.Time
sub.refundTime = refundTime.Time
sub.rawResponse = rawResponse
sub.rawNotification = rawNotification
return nil
}
const AppleRootPEM = `
-----BEGIN CERTIFICATE-----
MIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwS
QXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9u
IEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcN
MTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBS
b290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9y
aXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49
AgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtf
TjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517
IDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySr
MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gA
MGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4
at+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM
6BgD56KyKA==
-----END CERTIFICATE-----
`
type appleNotificationSignedPayload struct {
SignedPayload string `json:"signedPayload"`
}
type appleNotificationPayload struct {
NotificationType string `json:"notificationType"`
Subtype string `json:"subtype"`
Version string `json:"version"`
Data appleNotificationData `json:"data"`
SignedDate int64 `json:"signedDate"`
}
type appleNotificationData struct {
Environment string `json:"string"`
BundleId string `json:"bundleId"`
BundleVersion string `json:"bundleVersion"`
SignedTransactionInfo string `json:"signedTransactionInfo"`
SignedRenewalInfo string `json:"signedRenewalInfo"`
}
type appleNotificationTransactionInfo struct {
AppAccountToken string `json:"appAccountToken"`
BundleId string `json:"bundleId"`
Environment string `json:"environment"`
TransactionId string `json:"transactionId"`
OriginalTransactionId string `json:"originalTransactionId"`
ProductId string `json:"productId"`
ExpiresDateMs int64 `json:"expiresDate"`
RevocationDateMs int64 `json:"revocationDate"`
OriginalPurchaseDateMs int64 `json:"originalPurchaseDate"`
PurchaseDateMs int64 `json:"purchaseDate"`
}
//nolint:unused
func extractApplePublicKeyFromToken(tokenStr string) (*ecdsa.PublicKey, error) {
tokenArr := strings.Split(tokenStr, ".")
headerByte, err := base64.RawStdEncoding.DecodeString(tokenArr[0])
if err != nil {
return nil, err
}
type Header struct {
Alg string `json:"alg"`
X5c []string `json:"x5c"`
}
var header Header
err = json.Unmarshal(headerByte, &header)
if err != nil {
return nil, err
}
certByte, err := base64.StdEncoding.DecodeString(header.X5c[0])
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(certByte)
if err != nil {
return nil, err
}
switch pk := cert.PublicKey.(type) {
case *ecdsa.PublicKey:
return pk, nil
default:
return nil, errors.New("appstore public key must be of type ecdsa.PublicKey")
}
}
const AppleNotificationTypeRefund = "REFUND"
// Store providers notification callback handler functions
func appleNotificationHandler(logger *zap.Logger, db *sql.DB, purchaseNotificationCallback RuntimePurchaseNotificationAppleFunction, subscriptionNotificationCallback RuntimeSubscriptionNotificationAppleFunction) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
logger.Error("Failed to decode App Store notification body", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
var applePayload *appleNotificationSignedPayload
if err := json.Unmarshal(body, &applePayload); err != nil {
logger.Error("Failed to unmarshal App Store notification", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
tokens := strings.Split(applePayload.SignedPayload, ".")
if len(tokens) < 3 {
logger.Error("Unexpected App Store notification JWS token length")
w.WriteHeader(http.StatusInternalServerError)
return
}
seg := tokens[0]
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
headerByte, err := base64.StdEncoding.DecodeString(seg)
if err != nil {
logger.Error("Failed to decode Apple notification JWS header", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
type Header struct {
Alg string `json:"alg"`
X5c []string `json:"x5c"`
}
var header Header
if err = json.Unmarshal(headerByte, &header); err != nil {
logger.Error("Failed to unmarshal Apple notification JWS header", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
certs := make([][]byte, 0)
for _, encodedCert := range header.X5c {
cert, err := base64.StdEncoding.DecodeString(encodedCert)
if err != nil {
logger.Error("Failed to decode Apple notification JWS header certificate", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
certs = append(certs, cert)
}
rootCert := x509.NewCertPool()
ok := rootCert.AppendCertsFromPEM([]byte(AppleRootPEM))
if !ok {
logger.Error("Failed to parse Apple root certificate", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
interCert, err := x509.ParseCertificate(certs[1])
if err != nil {
logger.Error("Failed to parse Apple notification intermediate certificate", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
intermedia := x509.NewCertPool()
intermedia.AddCert(interCert)
cert, err := x509.ParseCertificate(certs[2])
if err != nil {
logger.Error("Failed to parse Apple notification certificate", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
opts := x509.VerifyOptions{
Roots: rootCert,
Intermediates: intermedia,
}
_, err = cert.Verify(opts)
if err != nil {
logger.Error("Failed to validate Apple notification signature", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
seg = tokens[1]
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
jsonPayload, err := base64.StdEncoding.DecodeString(seg)
if err != nil {
logger.Error("Failed to base64 decode App Store notification payload", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
var notificationPayload *appleNotificationPayload
if err = json.Unmarshal(jsonPayload, ¬ificationPayload); err != nil {
logger.Error("Failed to json unmarshal App Store notification payload", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
tokens = strings.Split(notificationPayload.Data.SignedTransactionInfo, ".")
if len(tokens) < 3 {
logger.Error("Unexpected App Store notification SignedTransactionInfo JWS token length")
w.WriteHeader(http.StatusInternalServerError)
return
}
seg = tokens[1]
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
jsonPayload, err = base64.StdEncoding.DecodeString(seg)
if err != nil {
logger.Error("Failed to base64 decode App Store notification payload", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
var signedTransactionInfo *appleNotificationTransactionInfo
if err = json.Unmarshal(jsonPayload, &signedTransactionInfo); err != nil {
logger.Error("Failed to json unmarshal App Store notification SignedTransactionInfo JWS token", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
logger.Debug("Apple IAP notification received", zap.Any("notification_payload", signedTransactionInfo))
uid := uuid.Nil
if signedTransactionInfo.AppAccountToken != "" {
tokenUID, err := uuid.FromString(signedTransactionInfo.AppAccountToken)
if err != nil {
logger.Warn("App Store subscription notification AppAccountToken is an invalid uuid", zap.String("app_account_token", signedTransactionInfo.AppAccountToken), zap.Error(err), zap.String("payload", string(body)))
} else {
uid = tokenUID
}
}
env := api.StoreEnvironment_PRODUCTION
if notificationPayload.Data.Environment == iap.AppleSandboxEnvironment {
env = api.StoreEnvironment_SANDBOX
}
ctx := context.Background()
if signedTransactionInfo.ExpiresDateMs != 0 {
// Notification regarding a subscription.
if uid.IsNil() {
// No user ID was found in receipt, lookup a validated subscription.
s, err := getSubscriptionByOriginalTransactionId(ctx, db, signedTransactionInfo.OriginalTransactionId)
if err != nil {
// User validated subscription not found.
if err != sql.ErrNoRows {
logger.Error("Failed to get subscription by original transaction id", zap.Error(err))
}
w.WriteHeader(http.StatusInternalServerError) // Return error to keep retrying.
return
}
uid = uuid.Must(uuid.FromString(s.UserId))
}
sub := &storageSubscription{
userID: uid,
originalTransactionId: signedTransactionInfo.OriginalTransactionId,
store: api.StoreProvider_APPLE_APP_STORE,
productId: signedTransactionInfo.ProductId,
purchaseTime: parseMillisecondUnixTimestamp(signedTransactionInfo.OriginalPurchaseDateMs),
environment: env,
expireTime: parseMillisecondUnixTimestamp(signedTransactionInfo.ExpiresDateMs),
rawNotification: string(body),
refundTime: parseMillisecondUnixTimestamp(signedTransactionInfo.RevocationDateMs),
}
if err = upsertSubscription(ctx, db, sub); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation && strings.Contains(pgErr.Message, "user_id") {
// User id was not found, ignore this notification
w.WriteHeader(http.StatusOK)
return
}
logger.Error("Failed to store App Store notification subscription data", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
active := false
if sub.expireTime.After(time.Now()) && sub.refundTime.Unix() == 0 {
active = true
}
var suid string
if !sub.userID.IsNil() {
suid = sub.userID.String()
}
if strings.ToUpper(notificationPayload.NotificationType) == AppleNotificationTypeRefund {
validatedSub := &api.ValidatedSubscription{
UserId: suid,
ProductId: sub.productId,
OriginalTransactionId: sub.originalTransactionId,
Store: api.StoreProvider_APPLE_APP_STORE,
PurchaseTime: timestamppb.New(sub.purchaseTime),
CreateTime: timestamppb.New(sub.createTime),
UpdateTime: timestamppb.New(sub.updateTime),
Environment: env,
ExpiryTime: timestamppb.New(sub.expireTime),
RefundTime: timestamppb.New(sub.refundTime),
ProviderResponse: sub.rawResponse,
ProviderNotification: sub.rawNotification,
Active: active,
}
if subscriptionNotificationCallback != nil {
if err = subscriptionNotificationCallback(ctx, validatedSub, string(body)); err != nil {
logger.Error("Error invoking Apple subscription refund runtime function", zap.Error(err))
w.WriteHeader(http.StatusOK)
return
}
}
}
} else {
// Notification regarding a purchase.
if uid.IsNil() {
// No user ID was found in receipt, lookup a validated subscription.
p, err := GetPurchaseByTransactionId(ctx, db, signedTransactionInfo.TransactionId)
if err != nil {
// User validated purchase not found.
if err != sql.ErrNoRows {
logger.Error("Failed to get purchase by transaction id", zap.Error(err))
}
w.WriteHeader(http.StatusInternalServerError) // Return error to keep retrying.
return
}
uid = uuid.Must(uuid.FromString(p.UserId))
}
if strings.ToUpper(notificationPayload.NotificationType) == AppleNotificationTypeRefund {
purchase := &storagePurchase{
userID: uid,
store: api.StoreProvider_APPLE_APP_STORE,
productId: signedTransactionInfo.ProductId,
transactionId: signedTransactionInfo.TransactionId,
purchaseTime: parseMillisecondUnixTimestamp(signedTransactionInfo.PurchaseDateMs),
refundTime: parseMillisecondUnixTimestamp(signedTransactionInfo.RevocationDateMs),
environment: env,
}
dbPurchases, err := upsertPurchases(ctx, db, []*storagePurchase{purchase})
if err != nil {
logger.Error("Failed to store App Store notification purchase data")
w.WriteHeader(http.StatusInternalServerError)
return
}
if purchaseNotificationCallback != nil {
dbPurchase := dbPurchases[0]
suid := dbPurchase.userID.String()
if dbPurchase.userID.IsNil() {
suid = ""
}