forked from awa/go-iap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.go
244 lines (202 loc) · 8.41 KB
/
validator.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
package playstore
import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
"fmt"
"net/http"
"time"
"google.golang.org/api/option"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
androidpublisher "google.golang.org/api/androidpublisher/v3"
)
//go:generate mockgen -destination=mocks/playstore.go -package=mocks github.com/awa/go-iap/playstore IABProduct,IABSubscription
// The IABProduct type is an interface for product service
type IABProduct interface {
VerifyProduct(context.Context, string, string, string) (*androidpublisher.ProductPurchase, error)
AcknowledgeProduct(context.Context, string, string, string, string) error
ConsumeProduct(context.Context, string, string, string, string) error
GetVoidedPurchase(ctx context.Context, packageName string, startTimeInMilliseconds int64, endTimeInMilliseconds int64, maxResults int64, voidedType int64, paginationToken string) (voidedPurchases []*androidpublisher.VoidedPurchase, nextPageToken string, err error)
}
// The IABSubscription type is an interface for subscription service
type IABSubscription interface {
AcknowledgeSubscription(context.Context, string, string, string, *androidpublisher.SubscriptionPurchasesAcknowledgeRequest) error
VerifySubscription(context.Context, string, string, string) (*androidpublisher.SubscriptionPurchase, error)
CancelSubscription(context.Context, string, string, string) error
RefundSubscription(context.Context, string, string, string) error
RevokeSubscription(context.Context, string, string, string) error
}
// The Client type implements VerifySubscription method
type Client struct {
service *androidpublisher.Service
}
// New returns http client which includes the credentials to access androidpublisher API.
// You should create a service account for your project at
// https://console.developers.google.com and download a JSON key file to set this argument.
func New(jsonKey []byte) (*Client, error) {
c := &http.Client{Timeout: 10 * time.Second}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, c)
conf, err := google.JWTConfigFromJSON(jsonKey, androidpublisher.AndroidpublisherScope)
if err != nil {
return nil, err
}
val := conf.Client(ctx).Transport.(*oauth2.Transport)
_, err = val.Source.Token()
if err != nil {
return nil, err
}
service, err := androidpublisher.NewService(ctx, option.WithHTTPClient(conf.Client(ctx)))
if err != nil {
return nil, err
}
return &Client{service}, err
}
// NewWithClient returns http client which includes the custom http client.
func NewWithClient(jsonKey []byte, cli *http.Client) (*Client, error) {
if cli == nil {
return nil, fmt.Errorf("client is nil")
}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, cli)
conf, err := google.JWTConfigFromJSON(jsonKey, androidpublisher.AndroidpublisherScope)
if err != nil {
return nil, err
}
service, err := androidpublisher.NewService(ctx, option.WithHTTPClient(conf.Client(ctx)))
if err != nil {
return nil, err
}
return &Client{service}, err
}
// AcknowledgeSubscription acknowledges a subscription purchase.
func (c *Client) AcknowledgeSubscription(
ctx context.Context,
packageName string,
subscriptionID string,
token string,
req *androidpublisher.SubscriptionPurchasesAcknowledgeRequest,
) error {
ps := androidpublisher.NewPurchasesSubscriptionsService(c.service)
err := ps.Acknowledge(packageName, subscriptionID, token, req).Context(ctx).Do()
return err
}
// VerifySubscription verifies subscription status
func (c *Client) VerifySubscription(
ctx context.Context,
packageName string,
subscriptionID string,
token string,
) (*androidpublisher.SubscriptionPurchase, error) {
ps := androidpublisher.NewPurchasesSubscriptionsService(c.service)
result, err := ps.Get(packageName, subscriptionID, token).Context(ctx).Do()
return result, err
}
// VerifyProduct verifies product status
func (c *Client) VerifyProduct(
ctx context.Context,
packageName string,
productID string,
token string,
) (*androidpublisher.ProductPurchase, error) {
ps := androidpublisher.NewPurchasesProductsService(c.service)
result, err := ps.Get(packageName, productID, token).Context(ctx).Do()
return result, err
}
func (c *Client) AcknowledgeProduct(ctx context.Context, packageName, productID, token, developerPayload string) error {
ps := androidpublisher.NewPurchasesProductsService(c.service)
acknowledgeRequest := &androidpublisher.ProductPurchasesAcknowledgeRequest{DeveloperPayload: developerPayload}
err := ps.Acknowledge(packageName, productID, token, acknowledgeRequest).Context(ctx).Do()
return err
}
func (c *Client) ConsumeProduct(ctx context.Context, packageName, productID, token, developerPayload string) error {
ps := androidpublisher.NewPurchasesProductsService(c.service)
err := ps.Consume(packageName, productID, token).Context(ctx).Do()
return err
}
// GetVoidedPurchase https://developers.google.com/android-publisher/voided-purchases
func (c *Client) GetVoidedPurchase(ctx context.Context, packageName string, startTimeInMilliseconds int64, endTimeInMilliseconds int64, maxResults int64, voidedType int64, paginationToken string) (voidedPurchases []*androidpublisher.VoidedPurchase, nextPageToken string, err error) {
ps := androidpublisher.NewPurchasesVoidedpurchasesService(c.service)
req := ps.List(packageName)
if startTimeInMilliseconds > 0 {
//By default, startTime is set to 30 days ago
req.StartTime(startTimeInMilliseconds)
}
if endTimeInMilliseconds > 0 {
//By default, endTime is set to the current time.
req.EndTime(endTimeInMilliseconds)
}
if paginationToken != "" {
req.Token(paginationToken)
}
if maxResults > 0 {
//By default, this value is 1000.
//Note that the maximum value for this parameter is also 1000.
req.MaxResults(maxResults)
}
if voidedType > 0 {
//0: only voided in-app purchases will be returned.
//1: both voided in-app purchases and voided subscription purchases will be returned.
//Default value is 0.
req.Type(1)
}
resp, err := req.Context(ctx).Do()
if err != nil {
return nil, "", err
}
if resp.TokenPagination != nil {
nextPageToken = resp.TokenPagination.NextPageToken
}
return resp.VoidedPurchases, nextPageToken, nil
}
// CancelSubscription cancels a user's subscription purchase.
func (c *Client) CancelSubscription(ctx context.Context, packageName string, subscriptionID string, token string) error {
ps := androidpublisher.NewPurchasesSubscriptionsService(c.service)
err := ps.Cancel(packageName, subscriptionID, token).Context(ctx).Do()
return err
}
// RefundSubscription refunds a user's subscription purchase, but the subscription remains valid
// until its expiration time and it will continue to recur.
func (c *Client) RefundSubscription(ctx context.Context, packageName string, subscriptionID string, token string) error {
ps := androidpublisher.NewPurchasesSubscriptionsService(c.service)
err := ps.Refund(packageName, subscriptionID, token).Context(ctx).Do()
return err
}
// RevokeSubscription refunds and immediately revokes a user's subscription purchase.
// Access to the subscription will be terminated immediately and it will stop recurring.
func (c *Client) RevokeSubscription(ctx context.Context, packageName string, subscriptionID string, token string) error {
ps := androidpublisher.NewPurchasesSubscriptionsService(c.service)
err := ps.Revoke(packageName, subscriptionID, token).Context(ctx).Do()
return err
}
// VerifySignature verifies in app billing signature.
// You need to prepare a public key for your Android app's in app billing
// at https://play.google.com/apps/publish/
func VerifySignature(base64EncodedPublicKey string, receipt []byte, signature string) (isValid bool, err error) {
// prepare public key
decodedPublicKey, err := base64.StdEncoding.DecodeString(base64EncodedPublicKey)
if err != nil {
return false, fmt.Errorf("failed to decode public key")
}
publicKeyInterface, err := x509.ParsePKIXPublicKey(decodedPublicKey)
if err != nil {
return false, fmt.Errorf("failed to parse public key")
}
publicKey, _ := publicKeyInterface.(*rsa.PublicKey)
// generate hash value from receipt
hasher := sha1.New()
hasher.Write(receipt)
hashedReceipt := hasher.Sum(nil)
// decode signature
decodedSignature, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return false, fmt.Errorf("failed to decode signature")
}
// verify
if err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, hashedReceipt, decodedSignature); err != nil {
return false, nil
}
return true, nil
}