forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core_purchase.go
159 lines (139 loc) · 5.48 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
// Copyright 2017 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 (
"database/sql"
"nakama/pkg/iap"
"errors"
"encoding/json"
"github.com/satori/go.uuid"
"go.uber.org/zap"
)
type PurchaseService struct {
logger *zap.Logger
db *sql.DB
AppleClient *iap.AppleClient
GoogleClient *iap.GoogleClient
}
func NewPurchaseService(jsonLogger *zap.Logger, multiLogger *zap.Logger, db *sql.DB, config *PurchaseConfig) *PurchaseService {
ac, err := iap.NewAppleClient(config.Apple.Password, config.Apple.Production, config.Apple.TimeoutMs)
if err != nil {
multiLogger.Warn("Skip initialising Apple in-app purchase provider", zap.String("reason", err.Error()))
} else {
if config.Apple.Production {
multiLogger.Info("Apple in-app purchase environment is set to Production priority.")
} else {
multiLogger.Info("Apple in-app purchase environment is set to Sandbox priority.")
}
multiLogger.Info("Successfully initiated Apple in-app purchase provider.")
}
gc, err := iap.NewGoogleClient(config.Google.PackageName, config.Google.ServiceKeyFilePath, config.Google.TimeoutMs)
if err != nil {
multiLogger.Warn("Skip initialising Google in-app purchase provider", zap.String("reason", err.Error()))
}
return &PurchaseService{
logger: jsonLogger,
db: db,
AppleClient: ac,
GoogleClient: gc,
}
}
func (p *PurchaseService) ValidateApplePurchase(userID uuid.UUID, purchase *iap.ApplePurchase) *iap.PurchaseVerifyResponse {
r, appleReceipt := p.AppleClient.Verify(purchase)
if !r.Success {
return r
}
//TODO: Improvement - Process more than one in-app receipts
inAppReceipt := appleReceipt.InApp[0]
p.checkUser(userID, r, 1, inAppReceipt.TransactionID)
if r.Success && !r.SeenBefore {
err := p.savePurchase(userID.Bytes(), 1, inAppReceipt.ProductID, inAppReceipt.TransactionID, purchase.ReceiptData, r.Data)
if err != nil {
r.Success = false
r.Message = errors.New("Failed to validate purchase against ledger.")
jsonPurchase, _ := json.Marshal(purchase)
p.logger.Error("Could not save Apple purchase", zap.String("receipt", string(jsonPurchase)), zap.String("provider_resp", r.Data), zap.Error(err))
}
}
return r
}
func (p *PurchaseService) ValidateGooglePurchaseProduct(userID uuid.UUID, purchase *iap.GooglePurchase) *iap.PurchaseVerifyResponse {
r, _ := p.GoogleClient.VerifyProduct(purchase)
if !r.Success {
return r
}
p.checkUser(userID, r, 0, purchase.PurchaseToken)
if r.Success && !r.SeenBefore {
jsonPurchase, _ := json.Marshal(purchase)
err := p.savePurchase(userID.Bytes(), 0, purchase.ProductId, purchase.PurchaseToken, string(jsonPurchase), r.Data)
if err != nil {
r.Success = false
r.Message = errors.New("Failed to validate purchase against ledger.")
p.logger.Error("Could not save Google product purchase", zap.String("receipt", string(jsonPurchase)), zap.String("provider_resp", r.Data), zap.Error(err))
}
}
return r
}
func (p *PurchaseService) ValidateGooglePurchaseSubscription(userID uuid.UUID, purchase *iap.GooglePurchase) *iap.PurchaseVerifyResponse {
r, _ := p.GoogleClient.VerifySubscription(purchase)
if !r.Success {
return r
}
p.checkUser(userID, r, 0, purchase.PurchaseToken)
if r.Success && !r.SeenBefore {
jsonPurchase, _ := json.Marshal(purchase)
err := p.savePurchase(userID.Bytes(), 0, purchase.ProductId, purchase.PurchaseToken, string(jsonPurchase), r.Data)
if err != nil {
r.Success = false
r.Message = errors.New("Failed to validate purchase against ledger.")
p.logger.Error("Could not save Google subscription purchase", zap.String("receipt", string(jsonPurchase)), zap.String("provider_resp", r.Data), zap.Error(err))
}
}
return r
}
func (p *PurchaseService) checkUser(userID uuid.UUID, r *iap.PurchaseVerifyResponse, provider int, receiptID string) {
var purchaseUserID []byte
err := p.db.QueryRow("SELECT user_id FROM purchase WHERE provider = $1 AND receipt_id = $2", provider, receiptID).Scan(&purchaseUserID)
if err != nil {
if err != sql.ErrNoRows {
r.Success = false
r.Message = errors.New("Failed to validate purchase against ledger.")
p.logger.Error(r.Message.Error(), zap.Error(err))
}
}
// We've not seen this transaction
if len(purchaseUserID) == 0 {
r.Success = true
r.SeenBefore = false
r.Message = nil
} else { // We've seen this transaction
if uuid.Equal(userID, uuid.FromBytesOrNil(purchaseUserID)) {
r.Success = true
r.SeenBefore = true
r.Message = nil
} else {
r.Success = false
r.SeenBefore = true
r.Message = errors.New("Transaction already registered to a different user")
}
}
}
func (p *PurchaseService) savePurchase(userID []byte, provider int, productID string, receiptID string, rawPurchase string, rawReceipt string) error {
createdAt := nowMs()
_, err := p.db.Exec(`
INSERT INTO purchase (user_id, provider, product_id, receipt_id, receipt, provider_resp, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
userID, provider, productID, receiptID, rawPurchase, rawReceipt, createdAt)
return err
}