This repository has been archived by the owner on Feb 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
auto_order_jd.go
518 lines (497 loc) · 14.7 KB
/
auto_order_jd.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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/tidwall/gjson"
"golang.org/x/text/encoding/simplifiedchinese"
)
// JDOrderDetail - JD Order Detail
type JDOrderDetail struct {
Address string `form:"address"`
Receiver string `form:"receiver"`
TotalPrice string `form:"total_price"`
Items []string `form:"items"`
}
// JDCartItem - JD Cart Item Detail
type JDCartItem struct {
SkuID string `form:"skuid"`
Name string `form:"name"`
VenderID string `form:"verder_id"`
Count string `form:"count"`
UnitPrice string `form:"unit_price"`
TotalPrice string `form:"total_price"`
IsSelected bool `form:"is_selected"`
PType string `form:"p_type"`
TargetID string `form:"target_id"`
PromoID string `form:"promo_id"`
}
// OrderJD - Order JD
type OrderJD struct {
orderClient *http.Client
skuChan chan string
skuState map[string]bool
riskControl string
expired bool
}
func (o *OrderJD) initHTTPClient() {
logger.Infoln("[+] [JD] Init Http Client and Cookies")
cookies := []*http.Cookie{}
for _, c := range strings.Split(config["cookies"], ";") {
kv := strings.Split(strings.Trim(c, " "), "=")
cookie := &http.Cookie{Name: kv[0], Value: kv[1], Path: "/", MaxAge: 86400}
cookies = append(cookies, cookie)
}
jar, _ := cookiejar.New(nil)
// passport
u, _ := url.Parse("https://passport.jd.com")
jar.SetCookies(u, cookies)
// order
// u, _ := url.Parse("https://jd.com")
// jar.SetCookies(u, cookies)
o.orderClient = &http.Client{
Jar: jar,
Transport: tr,
}
}
func (o *OrderJD) heartbeat() {
heartbeatURL := fmt.Sprintf("https://passport.jd.com/new/helloService.ashx?callback=%s&_=%s", getCallback(), getRandomTs())
req, err := http.NewRequest("GET", heartbeatURL, nil)
if err != nil {
logger.Errorln("[-] HB::NewRequest:", err.Error())
return
}
setReqHeader(req)
req.Header.Set("Referer", "https://order.jd.com/center/list.action")
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] HB::DoRequest", err.Error())
return
}
defer resp.Body.Close()
reader := simplifiedchinese.GB18030.NewDecoder().Reader(resp.Body)
body, err := ioutil.ReadAll(reader)
if err != nil {
logger.Errorln("[-] HB::ReadBody", err.Error())
return
}
jsonObj := make(map[string]interface{})
err = json.Unmarshal(getCallbackBody(body, "HB"), &jsonObj)
if err != nil {
logger.Errorln("[-] HB::UnmarshalBody", err.Error())
logger.Errorln("[-] HeartbeatURL", heartbeatURL)
logger.Debug(string(body))
return
}
if jsonObj["nick"] == "" {
logger.Errorln("[!!!] HB::Heartbeat:: Session is Expired!!!")
logger.Errorln("[!!!] HB::Heartbeat:: Session is Expired!!!")
logger.Errorln("[!!!] HB::Heartbeat:: Session is Expired!!!")
o.expired = true
return
}
logger.Infof("[+] User [ %s ] is alive!\n", jsonObj["nick"])
}
func (o *OrderJD) cancelAllItem() bool {
cancleURL := "https://cart.jd.com/cancelAllItem.action"
data := url.Values{}
data.Set("t", "0")
data.Set("outSkus", "")
data.Set("random", getRandomTs())
req, err := http.NewRequest("POST", cancleURL, strings.NewReader(data.Encode()))
if err != nil {
logger.Errorln("[-] CAI::NewRequest:", err)
return false
}
setReqHeader(req)
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] CAI::DoRequest", err)
return false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false
}
logger.Debug("[D] CancelAllItem success")
return true
}
func getTagValue(v string) string {
return strings.Trim(v, " \t\r\n")
}
func (o *OrderJD) getCartDetail() (map[string]*JDCartItem, error) {
cartItems := make(map[string]*JDCartItem)
cartURL := "https://cart.jd.com/cart.action"
req, err := http.NewRequest("GET", cartURL, nil)
if err != nil {
logger.Errorln("[-] GCD::NewRequest:", err)
return cartItems, err
}
setReqHeader(req)
req.Header.Set("Referer", "https://order.jd.com/center/list.action")
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] GCD::DoRequest", err)
return cartItems, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
logger.Errorln("[-] GCD::Respon ", resp.StatusCode, resp.Status)
return cartItems, err
}
reader := simplifiedchinese.GB18030.NewDecoder().Reader(resp.Body)
doc, err := goquery.NewDocumentFromReader(reader)
if err != nil {
logger.Errorln("[-] GCD::NewDocument ", err.Error())
return cartItems, err
}
doc.Find(".item-item.item-single").Each(func(i int, item *goquery.Selection) {
skuid, exists := item.Attr("skuid")
if !exists {
logger.Errorln("[!] Not Found skuid on item")
return
}
incrementItemID, exists := item.Find(".increment").Attr("id")
if !exists {
logger.Errorln("[!] Not Found increment in item")
return
}
itemAttrList := strings.Split(incrementItemID, "_")
// ["increment","8888","7498167","1","1","0"]
// ["increment","8888","59959871348","1","11","0","33739343507"]
var promoID = "0"
if len(itemAttrList) == 7 {
promoID = itemAttrList[6]
}
jdci := &JDCartItem{
SkuID: skuid,
Name: getTagValue(item.Find("div.p-name a").Text()),
VenderID: item.AttrOr("venderid", "9999"),
Count: item.AttrOr("num", "99999"),
UnitPrice: getTagValue(item.Find("div.p-price strong").Text())[1:],
TotalPrice: getTagValue(item.Find("div.p-sum strong").Text())[1:],
PType: itemAttrList[4],
PromoID: promoID,
TargetID: promoID,
IsSelected: false,
}
cartItems[skuid] = jdci
})
if len(cartItems) == 0 {
logger.Debug("[D] CetCartDetail::Doc", doc)
return cartItems, errors.New("Cart Is Empty")
}
logger.Debug("[D] CetCartDetail success")
return cartItems, nil
}
func (o *OrderJD) changeItemNumInCart(num int, item *JDCartItem) bool {
changeURL := "https://cart.jd.com/changeNum.action"
var r http.Request
err := r.ParseForm()
if err != nil {
logger.Errorln("[-] CINIC::ParseForm:", err.Error())
return false
}
r.Form.Add("t", "0")
r.Form.Add("outSkus", "")
r.Form.Add("random", getRandomTs())
r.Form.Add("venderId", item.VenderID)
r.Form.Add("pid", item.SkuID)
r.Form.Add("pcount", item.Count)
r.Form.Add("ptype", item.PType)
r.Form.Add("targetId", item.TargetID)
r.Form.Add("promoID", item.PromoID)
bodystr := strings.TrimSpace(r.Form.Encode())
req, err := http.NewRequest("POST", changeURL, strings.NewReader(bodystr))
if err != nil {
logger.Errorln("[-] CINIC::NewRequest:", err.Error())
return false
}
setReqHeader(req)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", "https://cart.jd.com/cart")
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] CINIC::DoRequest", err)
return false
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Errorln("[-] CINIC::ReadBody", err.Error())
return false
}
// sortedWebCartResult.ids 选择状态的 SKUID 列表
if gjson.GetBytes(body, "sortedWebCartResult.ids").String() == item.SkuID {
logger.Debug("[D] changeItemNumInCart success")
return true
}
logger.Debug("[D] CINIC::Body", string(body))
return false
}
func (o *OrderJD) addItemToCart(skuID string, num int) bool {
_gateURL := "https://cart.jd.com/gate.action"
gateURL := fmt.Sprintf("%s?pid=%s&pcount=%d&ptype=1", _gateURL, skuID, num)
req, err := http.NewRequest("GET", gateURL, nil)
if err != nil {
logger.Errorln("[-] AITC::NewRequest:", err.Error())
return false
}
setReqHeader(req)
req.Header.Set("Referer", "https://cart.jd.com/cart.action")
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] AITC::DoRequest", err.Error())
return false
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Errorln("[-] GCPD::ReadBody", err.Error())
return false
}
if strings.Contains(string(body), "商品已成功加入购物车") {
logger.Debug("[D] AddItemToCart success")
return true
}
l, err := resp.Location()
if err != nil {
logger.Errorln("[-] AITC::Location", err.Error())
return false
}
if strings.Contains(l.String(), "https://cart.jd.com/addToCart.html") ||
strings.Contains(l.String(), "https://cart.jd.com/cart.action") {
logger.Infof("[+] [%s] add to cart success!", skuID)
logger.Debug("[D] AddItemToCart success")
return true
}
logger.Errorln("[-] AITC::Location=", l.String())
return false
}
// 获取订单结算页面信息
// 该方法会返回订单结算页面的详细信息:商品名称、价格、数量、库存状态等。
func (o *OrderJD) getCheckoutPageDetail() error {
tradeURL := fmt.Sprintf("http://trade.jd.com/shopping/order/getOrderInfo.action?rid=%s", getRandomTs())
req, err := http.NewRequest("GET", tradeURL, nil)
if err != nil {
logger.Errorln("[-] GCPD::NewRequest:", err.Error())
return err
}
setReqHeader(req)
req.Header.Set("Referer", "https://cart.jd.com/cart.action")
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] GCPD::DoRequest", err.Error())
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = errors.New("Get Order Info Error")
logger.Errorln("[-] GCPD::DoRequest", err.Error())
return err
}
// reader := simplifiedchinese.GB18030.NewDecoder().Reader(resp.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Errorln("[-] GCPD::ReadBody", err.Error())
return err
}
bodyStr := string(body)
if strings.Contains(bodyStr, "刷新太频繁了") {
err = errors.New("刷新太频繁了")
return err
}
doc, err := goquery.NewDocumentFromReader(strings.NewReader(bodyStr))
if err != nil {
logger.Errorln("[-] GCPD::NewDocument ", err.Error())
return err
}
if strings.Contains(doc.Find("span#p-state").Text(), "无货") {
err = errors.New("Sku is gone")
return err
}
o.riskControl = doc.Find("#riskControl").AttrOr("value", "")
if verbose || debug {
orderDetail := &JDOrderDetail{
Address: doc.Find("span#sendAddr").Text(), // remove '寄送至: ' from the begin
Receiver: doc.Find("span#sendMobile").Text(), // remove '收件人:' from the begin
TotalPrice: doc.Find("span#sumPayPriceId").Text(), // remove '¥' from the begin
Items: []string{},
}
logger.Infoln("[+] Order Detail:", orderDetail)
}
if o.riskControl == "" {
return errors.New("RiskControl has not got")
}
logger.Debug("[D] GetCheckoutPageDetail success")
return nil
}
func encryptPaymentPwd(pwd string) string {
res := ""
n := len(pwd)
for i := 0; i < n; i++ {
res += fmt.Sprintf("u3%c", pwd[i])
}
return res
}
// 提交订单
// 1.该方法只适用于普通商品的提交订单
// 2.提交订单时,会对购物车中勾选✓的商品进行结算
func (o *OrderJD) submitOrder() bool {
submitURL := "https://trade.jd.com/shopping/order/submitOrder.action"
data := url.Values{}
// 预售商品订单
// ....
// submitOrderParam.eid: GX6IM4NTJ6FH5PSTNW6A3DSYGTXQSGTX6T4GMSSFUERD7Y4PR2KXHIRDSZACKONK22D3LLNJBHNZ4JEIFYYT5Q3X6Q
// submitOrderParam.fp: 19e893513f69af8bfceaa200d0ea2f74
// 普通商品订单
data.Set("overseaPurchaseCookies", "")
data.Set("vendorRemarks", "[]")
data.Set("submitOrderParam.sopNotPutInvoice", "false")
data.Set("submitOrderParam.trackID", "TestTrackId")
data.Set("submitOrderParam.ignorePriceChange", "0")
// 支付密码
if len(config["paymentpwd"]) > 0 {
data.Set("submitOrderParam.payPassword", encryptPaymentPwd(config["paymentpwd"]))
}
// jxj trackId 风控相关 order.js
data.Set("submitOrderParam.jxj", "1")
data.Set("submitOrderParam.trackId", "2f69d65eadf9e6b15701eb5875f4b8e9")
data.Set("riskControl", o.riskControl) // 就是是 csrf 的东西
req, err := http.NewRequest("POST", submitURL, strings.NewReader(data.Encode()))
if err != nil {
logger.Errorln("[-] SO::NewRequest:", err)
return false
}
setReqHeader(req)
req.Header.Set("Referer", "http://trade.jd.com/shopping/order/getOrderInfo.action")
resp, err := o.orderClient.Do(req)
if err != nil {
logger.Errorln("[-] SO::DoRequest", err)
return false
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Errorln("[-] SO::ReadBody", err.Error())
return false
}
obj := gjson.GetManyBytes(body, "success", "orderId", "message", "resultCode")
if obj[0].Bool() {
logger.Infoln("[+] Order Success! OrderNo:", obj[1])
return true
}
code := obj[3].Int()
errMsg := obj[2].String()
if code == 0 {
errMsg += "(下单商品可能为第三方商品,将切换为普通发票进行尝试)"
} else if code == 60077 {
errMsg += "(可能是购物车为空 或 未勾选购物车中商品)"
} else if code == 60123 {
errMsg += "(需要在 config.conf 文件中配置支付密码)"
}
logger.Errorln("[-] Order fail", errMsg)
logger.Debug("[D] SubmitOrder", string(body))
return false
}
func (o *OrderJD) doOrder(skuID string) {
logger.Infoln("[+] Do Order [", skuID, "]")
i := 1
for {
if i > 3 {
break
}
logger.Infof("[+] ===== 第 [ %d / %d ] 次尝试提交订单 =====\n", i, 3)
msg := fmt.Sprintf("[!!!] [%d/3 submit] [%s] Order ", i, skuID)
i++
if !o.cancelAllItem() {
logger.Errorln("[-] DoOrder : Cannot cancel all item")
continue
}
cartItems, err := o.getCartDetail()
if err != nil {
logger.Errorln("[-] DoOrder : ", err.Error())
continue
}
ret := false
if item, ok := cartItems[skuID]; ok {
logger.Debug("changeItemNumInCart")
ret = o.changeItemNumInCart(1, item)
} else {
logger.Debug("addItemToCart")
ret = o.addItemToCart(skuID, 1)
}
if ret {
err := o.getCheckoutPageDetail()
if err == nil {
if o.submitOrder() {
msg += "Success!"
go sendBotMsg(msg)
break
} else {
msg += "Fail!"
}
} else {
msg += "Fail!"
logger.Errorln("[-] DoOrder :", err.Error())
}
} else {
msg += "Fail!"
}
logger.Infoln(msg)
time.Sleep(5 * time.Second)
}
}
func (o *OrderJD) orderSku() {
w := &sync.WaitGroup{}
for {
logger.Infoln("[+] [JD] Waiting OrderSku chan...")
skuID := <-o.skuChan
logger.Infoln("[+] skuID := <-o.skuChan:", skuID)
if skuID == "0" || o.expired {
break
}
if o.skuState[skuID] {
continue
}
logger.Infoln("[+] Order [", skuID, "]")
o.skuState[skuID] = true
w.Add(1)
go func() {
defer w.Done()
o.doOrder(skuID)
}()
// Reset
w.Add(1)
go func() {
defer w.Done()
time.Sleep(time.Duration(orderdelay) * time.Second)
o.skuState[skuID] = false
}()
w.Wait()
}
}
func (o *OrderJD) addSkuID(skuID string) {
logger.Infoln("[+] [JD] Add Order ", skuID)
o.skuChan <- skuID
}
// RunOrderJD - Run Order Sku
func RunOrderJD() *OrderJD {
o := &OrderJD{}
o.initHTTPClient()
o.skuChan = make(chan string, 1)
o.skuState = make(map[string]bool, len(skuMetas))
o.expired = false
for skuid := range skuMetas {
o.skuState[skuid] = false
}
return o
}