forked from smartwalle/alipay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alipay.go
241 lines (205 loc) · 5.61 KB
/
alipay.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
package alipay
import (
"crypto"
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
"github.com/smartwalle/alipay/encoding"
)
type AliPay struct {
appId string
apiDomain string
notifyVerifyDomain string
//partnerId string
privateKey []byte
AliPayPublicKey []byte
Client *http.Client
SignType string
}
func New(appId, aliPublicKey, privateKey string, isProduction bool) (client *AliPay) {
client = &AliPay{}
client.appId = appId
//client.partnerId = partnerId
client.privateKey = encoding.ParsePrivateKey(privateKey)
client.AliPayPublicKey = encoding.ParsePublicKey(aliPublicKey)
client.Client = http.DefaultClient
if isProduction {
client.apiDomain = K_ALI_PAY_PRODUCTION_API_URL
client.notifyVerifyDomain = K_ALI_PAY_PRODUCTION_MAPI_URL
} else {
client.apiDomain = K_ALI_PAY_SANDBOX_API_URL
client.notifyVerifyDomain = K_ALI_PAY_SANDBOX_API_URL
}
client.SignType = K_SIGN_TYPE_RSA2
return client
}
func (this *AliPay) URLValues(param AliPayParam) (value url.Values, err error) {
var p = url.Values{}
p.Add("app_id", this.appId)
p.Add("method", param.APIName())
p.Add("format", K_FORMAT)
p.Add("charset", K_CHARSET)
p.Add("sign_type", this.SignType)
p.Add("timestamp", time.Now().Format(K_TIME_FORMAT))
p.Add("version", K_VERSION)
if len(param.ExtJSONParamName()) > 0 {
p.Add(param.ExtJSONParamName(), param.ExtJSONParamValue())
}
var ps = param.Params()
if ps != nil {
for key, value := range ps {
p.Add(key, value)
}
}
var hash crypto.Hash
if this.SignType == K_SIGN_TYPE_RSA {
hash = crypto.SHA1
} else {
hash = crypto.SHA256
}
sign, err := signWithPKCS1v15(p, this.privateKey, hash)
if err != nil {
return nil, err
}
p.Add("sign", sign)
return p, nil
}
func (this *AliPay) doRequest(method string, param AliPayParam, results interface{}) (err error) {
var buf io.Reader
if param != nil {
p, err := this.URLValues(param)
if err != nil {
return err
}
buf = strings.NewReader(p.Encode())
}
req, err := http.NewRequest(method, this.apiDomain, buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", K_CONTENT_TYPE_FORM)
resp, err := this.Client.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return err
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if len(this.AliPayPublicKey) > 0 {
var dataStr = string(data)
var rootNodeName = strings.Replace(param.APIName(), ".", "_", -1) + k_RESPONSE_SUFFIX
var rootIndex = strings.LastIndex(dataStr, rootNodeName)
var errorIndex = strings.LastIndex(dataStr, k_ERROR_RESPONSE)
var content string
var sign string
if rootIndex > 0 {
content, sign = parserJSONSource(dataStr, rootNodeName, rootIndex)
} else if errorIndex > 0 {
content, sign = parserJSONSource(dataStr, k_ERROR_RESPONSE, errorIndex)
} else {
return nil
}
if sign != "" {
if ok, err := verifyData([]byte(content), this.SignType, sign, this.AliPayPublicKey); ok == false {
return err
}
}
}
err = json.Unmarshal(data, results)
if err != nil {
return err
}
return err
}
func (this *AliPay) DoRequest(method string, param AliPayParam, results interface{}) (err error) {
return this.doRequest(method, param, results)
}
func (this *AliPay) VerifySign(data url.Values) (ok bool, err error) {
return verifySign(data, this.AliPayPublicKey)
}
func parserJSONSource(rawData string, nodeName string, nodeIndex int) (content string, sign string) {
var dataStartIndex = nodeIndex + len(nodeName) + 2
var signIndex = strings.LastIndex(rawData, "\""+k_SIGN_NODE_NAME+"\"")
var dataEndIndex = signIndex - 1
var indexLen = dataEndIndex - dataStartIndex
if indexLen < 0 {
return "", ""
}
content = rawData[dataStartIndex:dataEndIndex]
var signStartIndex = signIndex + len(k_SIGN_NODE_NAME) + 4
sign = rawData[signStartIndex:]
var signEndIndex = strings.LastIndex(sign, "\"}")
sign = sign[:signEndIndex]
return content, sign
}
func signWithPKCS1v15(param url.Values, privateKey []byte, hash crypto.Hash) (s string, err error) {
if param == nil {
param = make(url.Values, 0)
}
var pList = make([]string, 0, 0)
for key := range param {
var value = strings.TrimSpace(param.Get(key))
if len(value) > 0 {
pList = append(pList, key+"="+value)
}
}
sort.Strings(pList)
var src = strings.Join(pList, "&")
sig, err := encoding.SignPKCS1v15([]byte(src), privateKey, hash)
if err != nil {
return "", err
}
s = base64.StdEncoding.EncodeToString(sig)
return s, nil
}
func VerifySign(data url.Values, key []byte) (ok bool, err error) {
return verifySign(data, key)
}
func verifySign(data url.Values, key []byte) (ok bool, err error) {
sign := data.Get("sign")
signType := data.Get("sign_type")
var keys = make([]string, 0, 0)
for key, value := range data {
if key == "sign" || key == "sign_type" {
continue
}
if len(value) > 0 {
keys = append(keys, key)
}
}
sort.Strings(keys)
var pList = make([]string, 0, 0)
for _, key := range keys {
var value = strings.TrimSpace(data.Get(key))
if len(value) > 0 {
pList = append(pList, key+"="+value)
}
}
var s = strings.Join(pList, "&")
return verifyData([]byte(s), signType, sign, key)
}
func verifyData(data []byte, signType, sign string, key []byte) (ok bool, err error) {
signBytes, err := base64.StdEncoding.DecodeString(sign)
if err != nil {
return false, err
}
if signType == K_SIGN_TYPE_RSA {
err = encoding.VerifyPKCS1v15(data, signBytes, key, crypto.SHA1)
} else {
err = encoding.VerifyPKCS1v15(data, signBytes, key, crypto.SHA256)
}
if err != nil {
return false, err
}
return true, nil
}