forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle_refund_scheduler.go
254 lines (216 loc) · 8.32 KB
/
google_refund_scheduler.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
// 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 (
"context"
"database/sql"
"encoding/json"
"github.com/gofrs/uuid"
"github.com/heroiclabs/nakama-common/api"
"github.com/heroiclabs/nakama/v3/iap"
"go.uber.org/atomic"
"go.uber.org/zap"
"google.golang.org/protobuf/types/known/timestamppb"
"strconv"
"sync"
"time"
)
type GoogleRefundScheduler interface {
Start(runtime *Runtime)
Pause()
Resume()
Stop()
}
type LocalGoogleRefundScheduler struct {
sync.Mutex
logger *zap.Logger
db *sql.DB
config Config
active *atomic.Uint32
fnPurchaseRefund RuntimePurchaseNotificationGoogleFunction
fnSubscriptionRefund RuntimeSubscriptionNotificationGoogleFunction
ctx context.Context
ctxCancelFn context.CancelFunc
}
func NewGoogleRefundScheduler(logger *zap.Logger, db *sql.DB, config Config) GoogleRefundScheduler {
ctx, ctxCancelFn := context.WithCancel(context.Background())
return &LocalGoogleRefundScheduler{
logger: logger,
db: db,
config: config,
active: atomic.NewUint32(1),
ctx: ctx,
ctxCancelFn: ctxCancelFn,
}
}
func (g *LocalGoogleRefundScheduler) Start(runtime *Runtime) {
g.fnPurchaseRefund = runtime.PurchaseNotificationGoogle()
g.fnSubscriptionRefund = runtime.SubscriptionNotificationGoogle()
if !g.config.GetIAP().Google.Enabled() {
return
}
period := g.config.GetIAP().Google.RefundCheckPeriodMin
if period != 0 {
go func() {
ticker := time.NewTicker(time.Duration(period) * time.Minute)
defer ticker.Stop()
for {
select {
case <-g.ctx.Done():
return
case <-ticker.C:
if g.active.Load() != 1 {
continue
}
voidedReceipts, err := iap.ListVoidedReceiptsGoogle(g.ctx, httpc, g.config.GetIAP().Google.ClientEmail, g.config.GetIAP().Google.PrivateKey, g.config.GetIAP().Google.PackageName)
if err != nil {
g.logger.Error("Failed to get IAP Google voided receipts", zap.Error(err))
continue
}
for _, vr := range voidedReceipts {
switch vr.Kind {
case "androidpublisher#productPurchase":
purchase, err := getPurchaseByTransactionId(g.ctx, g.db, vr.PurchaseToken)
if err != nil && err != sql.ErrNoRows {
g.logger.Warn("Failed to find purchase for Google refund callback", zap.Error(err), zap.String("purchase_token", vr.PurchaseToken))
continue
}
if purchase.RefundTime.Seconds != 0 {
// Purchase refund already handled, skip it.
continue
}
refundTimeInt, err := strconv.ParseInt(vr.VoidedTimeMillis, 10, 64)
if err != nil {
g.logger.Error("Failed to parse Google purchase voided time", zap.Error(err), zap.String("voided_time", vr.VoidedTimeMillis))
continue
}
refundTime := parseMillisecondUnixTimestamp(refundTimeInt)
sPurchase := &storagePurchase{
userID: uuid.Must(uuid.FromString(purchase.UserId)),
store: purchase.Store,
productId: purchase.ProductId,
transactionId: purchase.TransactionId,
purchaseTime: purchase.PurchaseTime.AsTime(),
createTime: purchase.CreateTime.AsTime(),
updateTime: purchase.UpdateTime.AsTime(),
refundTime: refundTime,
environment: purchase.Environment,
}
dbPurchases, err := upsertPurchases(g.ctx, g.db, []*storagePurchase{sPurchase})
if err != nil {
g.logger.Error("Failed to upsert Google voided purchase", zap.Error(err), zap.String("purchase_token", vr.PurchaseToken))
continue
}
dbPurchase := dbPurchases[0]
validatedPurchase := &api.ValidatedPurchase{
UserId: dbPurchase.userID.String(),
ProductId: dbPurchase.productId,
TransactionId: dbPurchase.transactionId,
Store: dbPurchase.store,
PurchaseTime: timestamppb.New(dbPurchase.purchaseTime),
CreateTime: timestamppb.New(dbPurchase.createTime),
UpdateTime: timestamppb.New(dbPurchase.updateTime),
RefundTime: timestamppb.New(refundTime),
Environment: purchase.Environment,
}
json, err := json.Marshal(vr)
if err != nil {
g.logger.Error("Failed to marshal Google voided purchase.", zap.Error(err))
continue
}
if g.fnPurchaseRefund != nil {
if err = g.fnPurchaseRefund(g.ctx, validatedPurchase, string(json)); err != nil {
g.logger.Warn("Failed to invoke Google purchase refund hook", zap.Error(err))
}
}
case "androidpublisher#subscriptionPurchase":
subscription, err := getSubscriptionByOriginalTransactionId(g.ctx, g.db, vr.PurchaseToken)
if err != nil {
if err != sql.ErrNoRows {
g.logger.Error("Failed to find subscription for Google refund callback", zap.Error(err), zap.String("transaction_id", vr.PurchaseToken))
}
continue
}
if subscription.RefundTime.Seconds != 0 {
// Subscription refund already handled, skip it.
continue
}
refundTimeInt, err := strconv.ParseInt(vr.VoidedTimeMillis, 10, 64)
if err != nil {
g.logger.Error("Failed to parse Google subscription voided time", zap.Error(err), zap.String("voided_time", vr.VoidedTimeMillis))
continue
}
refundTime := parseMillisecondUnixTimestamp(refundTimeInt)
sSubscription := &storageSubscription{
originalTransactionId: subscription.OriginalTransactionId,
userID: uuid.Must(uuid.FromString(subscription.UserId)),
store: subscription.Store,
productId: subscription.ProductId,
purchaseTime: subscription.PurchaseTime.AsTime(),
createTime: subscription.CreateTime.AsTime(),
updateTime: subscription.UpdateTime.AsTime(),
refundTime: refundTime,
environment: subscription.Environment,
expireTime: subscription.ExpiryTime.AsTime(),
}
err = upsertSubscription(g.ctx, g.db, sSubscription)
if err != nil {
g.logger.Error("Failed to upsert Google voided subscription", zap.Error(err), zap.String("purchase_token", vr.PurchaseToken))
continue
}
active := false
if sSubscription.expireTime.After(time.Now()) {
active = true
}
validatedSubscription := &api.ValidatedSubscription{
UserId: sSubscription.userID.String(),
ProductId: sSubscription.productId,
OriginalTransactionId: sSubscription.originalTransactionId,
Store: sSubscription.store,
PurchaseTime: timestamppb.New(sSubscription.purchaseTime),
CreateTime: timestamppb.New(sSubscription.createTime),
UpdateTime: timestamppb.New(sSubscription.updateTime),
Environment: sSubscription.environment,
ExpiryTime: timestamppb.New(sSubscription.expireTime),
RefundTime: timestamppb.New(refundTime),
Active: active,
}
json, err := json.Marshal(vr)
if err != nil {
g.logger.Error("Failed to marshal Google voided purchase.", zap.Error(err))
continue
}
if g.fnSubscriptionRefund != nil {
if err = g.fnSubscriptionRefund(g.ctx, validatedSubscription, string(json)); err != nil {
g.logger.Warn("Failed to invoke Google subscription refund hook", zap.Error(err))
}
}
default:
g.logger.Warn("Unhandled IAP Google voided receipt kind", zap.String("kind", vr.Kind))
}
}
}
}
}()
}
}
func (g *LocalGoogleRefundScheduler) Pause() {
g.active.Store(0)
}
func (g *LocalGoogleRefundScheduler) Resume() {
g.active.Store(1)
}
func (g *LocalGoogleRefundScheduler) Stop() {
g.ctxCancelFn()
}