feat: improve xiaodian seckill flow

This commit is contained in:
yml2213
2026-08-08 23:04:40 +08:00
parent 16972b41cd
commit dde2b43d82
19 changed files with 871 additions and 64 deletions
+194 -5
View File
@@ -12,6 +12,7 @@ import (
"sort"
"strconv"
"strings"
"sync"
"time"
"douyu_go/internal/activity"
@@ -28,6 +29,14 @@ type DouyuClient struct {
Activity *activity.Activity
TimeAPIURL string
Trace *trace.Recorder
xiaodianEmbedMu sync.Mutex
xiaodianEmbedCache map[string]xiaodianEmbedCacheItem
}
type xiaodianEmbedCacheItem struct {
query url.Values
expiresAt time.Time
}
// New 创建斗鱼客户端。act 决定使用哪个活动的接口参数;
@@ -43,9 +52,10 @@ func New(act *activity.Activity, timeAPIURL string, tr *trace.Recorder) *DouyuCl
tr = &trace.Recorder{}
}
return &DouyuClient{
Activity: act,
TimeAPIURL: timeAPIURL,
Trace: tr,
Activity: act,
TimeAPIURL: timeAPIURL,
Trace: tr,
xiaodianEmbedCache: make(map[string]xiaodianEmbedCacheItem),
HTTPClient: &http.Client{
Timeout: 8 * time.Second,
Transport: &http.Transport{
@@ -248,6 +258,8 @@ type xiaodianItem struct {
GoodsName string `json:"sGoodsName"`
Category xiaodianFlexibleString `json:"iCategoryId"`
Price string `json:"iPrice"`
JB2Price string `json:"iJb2Price"`
PayType string `json:"sPayType"`
GoodsLeft string `json:"iGoodsLeft"`
GoodsPic string `json:"sGoodsPic"`
ShowBegin string `json:"dtShowBeginTime"`
@@ -304,6 +316,13 @@ type xiaodianOrderGoods struct {
Quantity xiaodianFlexibleString `json:"iQuantity"`
}
type xiaodianBuyInfo struct {
Ret xiaodianFlexibleString `json:"ret"`
Msg string `json:"msg"`
Serial string `json:"serial"`
SerialNum string `json:"sSerialNum"`
}
// xiaodianEmbedQuery 获取斗鱼为当前账号签发的短时道具城参数。
func (c *DouyuClient) xiaodianEmbedQuery(cookie string) (url.Values, error) {
uid := cookieValue(cookie, "acf_uid")
@@ -312,6 +331,10 @@ func (c *DouyuClient) xiaodianEmbedQuery(cookie string) (url.Values, error) {
if uid == "" || stk == "" || ltkid == "" {
return nil, errors.New("斗鱼 Cookie 缺少 acf_uid、acf_stk 或 acf_ltkid,无法获取和平小店授权")
}
cacheKey := uid + ":" + c.Activity.ActAlias + ":" + c.Activity.RoomID
if cached, ok := c.getXiaodianEmbedCache(cacheKey); ok {
return cached, nil
}
endpoint, err := url.Parse(c.Activity.RoleParamURL)
if err != nil {
return nil, fmt.Errorf("和平小店授权接口地址无效: %w", err)
@@ -345,7 +368,37 @@ func (c *DouyuClient) xiaodianEmbedQuery(cookie string) (url.Values, error) {
if err != nil || result.Data.TXURLH5 == "" {
return nil, errors.New("和平小店授权响应缺少 txurlH5")
}
return h5.Query(), nil
queryValues := h5.Query()
c.setXiaodianEmbedCache(cacheKey, queryValues)
return cloneValues(queryValues), nil
}
func (c *DouyuClient) getXiaodianEmbedCache(key string) (url.Values, bool) {
c.xiaodianEmbedMu.Lock()
defer c.xiaodianEmbedMu.Unlock()
item, ok := c.xiaodianEmbedCache[key]
if !ok || time.Now().After(item.expiresAt) {
delete(c.xiaodianEmbedCache, key)
return nil, false
}
return cloneValues(item.query), true
}
func (c *DouyuClient) setXiaodianEmbedCache(key string, values url.Values) {
c.xiaodianEmbedMu.Lock()
defer c.xiaodianEmbedMu.Unlock()
c.xiaodianEmbedCache[key] = xiaodianEmbedCacheItem{
query: cloneValues(values),
expiresAt: time.Now().Add(45 * time.Second),
}
}
func cloneValues(values url.Values) url.Values {
out := make(url.Values, len(values))
for key, items := range values {
out[key] = append([]string(nil), items...)
}
return out
}
// xiaodianRole 使用短时授权参数解析当前斗鱼账号绑定的游戏角色。
@@ -479,11 +532,14 @@ func (c *DouyuClient) xiaodianProducts(cookie string, options types.XiaodianProd
continue
}
seen[item.GoodsID] = struct{}{}
payType, payLabel, price := xiaodianPayment(item)
products = append(products, types.Product{
CommodityID: item.GoodsID,
CommodityName: item.GoodsName,
Category: string(item.Category),
Score: parseXiaodianInt(item.Price),
Score: price,
PayType: payType,
PayLabel: payLabel,
Count: parseXiaodianInt(item.GoodsLeft),
Pic: item.GoodsPic,
})
@@ -491,6 +547,18 @@ func (c *DouyuClient) xiaodianProducts(cookie string, options types.XiaodianProd
return products, nil
}
func xiaodianPayment(item xiaodianItem) (int, string, int) {
payType := 1
label := "点券"
price := parseXiaodianInt(item.Price)
if strings.Contains(strings.ToLower(item.PayType), "jb2") || parseXiaodianInt(item.JB2Price) > 0 {
payType = 5
label = "扭蛋碎片"
price = parseXiaodianInt(item.JB2Price)
}
return payType, label, price
}
// xiaodianProductPages 按分类拉取完整分页;分类为空时查询全部商品。
func (c *DouyuClient) xiaodianProductPages(endpoint *url.URL, query url.Values, pageSize int, category, excludeCategory, label string) ([]xiaodianItem, error) {
itemsAll := make([]xiaodianItem, 0)
@@ -749,6 +817,9 @@ func (c *DouyuClient) Score(cookie string) (int, error) {
// GenerateCSRF 生成当前活动需要的鉴权 token。
func (c *DouyuClient) GenerateCSRF(cookie string) (string, error) {
if c.Activity.IsXiaodian {
return "", nil
}
if c.Activity.UseCTN {
ctn, err := c.FetchCTN(cookie)
if err != nil {
@@ -875,6 +946,9 @@ func csrfFromResponse(resp *http.Response) string {
// BatchExchangeLimit 请求兑换限制接口。电竞手册不需要此步骤,直接跳过返回默认限制。
func (c *DouyuClient) BatchExchangeLimit(cookie, commodityID string, csrf *string) (int, error) {
if c.Activity.IsXiaodian {
return 1, nil
}
if c.Activity.UseCTN {
return 1, nil
}
@@ -908,6 +982,9 @@ func (c *DouyuClient) BatchExchangeLimit(cookie, commodityID string, csrf *strin
// PreExchange 按抓包流程执行预兑换检查。电竞手册不需要此步骤,直接跳过。
func (c *DouyuClient) PreExchange(cookie, commodityID string, csrf *string) error {
if c.Activity.IsXiaodian {
return nil
}
if c.Activity.UseCTN {
return nil
}
@@ -933,6 +1010,9 @@ func (c *DouyuClient) PreExchange(cookie, commodityID string, csrf *string) erro
// Exchange 正式兑换一个商品。
func (c *DouyuClient) Exchange(cookie, commodityID string, csrf *string) (string, error) {
if c.Activity.IsXiaodian {
return c.xiaodianExchange(cookie, types.Product{CommodityID: commodityID})
}
var result struct {
types.APIResponse
Data struct {
@@ -995,6 +1075,115 @@ func (c *DouyuClient) Exchange(cookie, commodityID string, csrf *string) (string
return fmt.Sprintf("exchangeId=%d,num=%s", result.Data.ExchangeID, result.Data.ExchangeNum), nil
}
// ExchangeProduct 正式兑换一个商品。和平小店需要商品支付类型/价格,因此应优先走这个入口。
func (c *DouyuClient) ExchangeProduct(cookie string, product types.Product, csrf *string) (string, error) {
if c.Activity.IsXiaodian {
return c.xiaodianExchange(cookie, product)
}
return c.Exchange(cookie, product.CommodityID, csrf)
}
func (c *DouyuClient) xiaodianExchange(cookie string, product types.Product) (string, error) {
if strings.TrimSpace(cookie) == "" {
return "", errors.New("Cookie 为空")
}
if strings.TrimSpace(product.CommodityID) == "" {
return "", errors.New("商品 ID 为空")
}
embedQuery, err := c.xiaodianEmbedQuery(cookie)
if err != nil {
return "", err
}
payType := product.PayType
if payType <= 0 {
payType = 1
}
payPrice := product.Score
if payPrice < 0 {
payPrice = 0
}
endpoint, err := url.Parse(c.xiaodianLiveBuyURL())
if err != nil {
return "", err
}
query := endpoint.Query()
query.Set("_service", "buy.plug.svr.web")
query.Set("_plug_id", "7200")
query.Set("_jsvar", "buyInfo")
query.Set("acctype", "livelink")
query.Set("_app_id", "2123")
query.Set("iActionId", c.Activity.ActID)
query.Set("propid", product.CommodityID)
query.Set("paytype", strconv.Itoa(payType))
query.Set("source", c.Activity.RoomID)
query.Set("sAnchorId", c.Activity.RoomID)
query.Set("attach", `{"actId":"`+embedQuery.Get("actId")+`"}`)
query.Set("apptype", "3")
query.Set("_biz_code", "cjm")
query.Set("_act_id", c.Activity.ActID)
query.Set("authType", "delegate")
query.Set("sLiveUserInfo", `{"sAnchorId":"`+c.Activity.RoomID+`","sVideoId":0}`)
for _, key := range []string{"actId", "appId", "gameId", "livePlatId", "code", "timestamp", "v", "sig"} {
query.Set(key, embedQuery.Get(key))
}
appext, err := json.Marshal(map[string]any{
"user_price": payPrice,
"sGoodsPic": product.Pic,
"paytype": payType,
})
if err != nil {
return "", err
}
query.Set("appext", string(appext))
query.Set("_sid", "8")
query.Set("set", "8")
endpoint.RawQuery = query.Encode()
req, err := http.NewRequest(http.MethodGet, endpoint.String(), nil)
if err != nil {
return "", err
}
c.setXiaodianHeaders(req)
body, err := c.doText(req, "和平小店正式兑换", true)
if err != nil {
return "", err
}
var result xiaodianBuyInfo
if err := parseXiaodianVariable(body, "buyInfo", &result); err != nil {
return "", fmt.Errorf("和平小店兑换响应解析失败: %w", err)
}
if result.Ret != "0" {
if strings.TrimSpace(result.Msg) == "" {
return "", fmt.Errorf("和平小店兑换失败: ret=%s", result.Ret)
}
return "", fmt.Errorf("和平小店兑换失败: %s", result.Msg)
}
serial := result.Serial
if serial == "" {
serial = result.SerialNum
}
if serial == "" {
return "paytype=" + strconv.Itoa(payType), nil
}
return fmt.Sprintf("serial=%s,paytype=%d", serial, payType), nil
}
func (c *DouyuClient) xiaodianLiveBuyURL() string {
roleURL := strings.TrimSpace(c.Activity.RoleURL)
if roleURL == "" {
return "https://apps.game.qq.com/daoju/igw/livebuy/"
}
endpoint, err := url.Parse(roleURL)
if err != nil || endpoint.Scheme == "" || endpoint.Host == "" {
return "https://apps.game.qq.com/daoju/igw/livebuy/"
}
endpoint.Path = "/daoju/igw/livebuy/"
endpoint.RawQuery = ""
endpoint.Fragment = ""
return endpoint.String()
}
// RoleName 查询绑定角色名。
func (c *DouyuClient) RoleName(cookie string) (string, error) {
var result struct {
+73 -3
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
@@ -171,14 +172,14 @@ func TestProductsAutomaticallyResolvesXiaodianRoleAndPaginates(t *testing.T) {
if category == "76" {
switch offset {
case "0":
items = []map[string]string{{"iGoodsId": "g3", "sGoodsName": "热门商品", "iCategoryId": "76", "iPrice": "30", "iGoodsLeft": "0"}}
items = []map[string]string{{"iGoodsId": "g3", "sGoodsName": "热门商品", "iCategoryId": "76", "iPrice": "30", "sPayType": "qpqb", "iGoodsLeft": "0"}}
}
} else {
switch offset {
case "0":
items = []map[string]string{{"iGoodsId": "g1", "sGoodsName": "商品一", "iCategoryId": "1", "iPrice": "10", "iGoodsLeft": "-1"}, {"iGoodsId": "g2", "sGoodsName": "特惠商品", "iCategoryId": "45", "iPrice": "20", "iGoodsLeft": "3"}}
items = []map[string]string{{"iGoodsId": "g1", "sGoodsName": "商品一", "iCategoryId": "1", "iPrice": "10", "sPayType": "qpqb", "iGoodsLeft": "-1"}, {"iGoodsId": "g2", "sGoodsName": "特惠商品", "iCategoryId": "45", "iPrice": "0", "iJb2Price": "20", "sPayType": "jb2", "iGoodsLeft": "3"}}
case "2":
items = []map[string]string{{"iGoodsId": "g2", "sGoodsName": "重复商品", "iCategoryId": "45", "iPrice": "20", "iGoodsLeft": "3"}, {"iGoodsId": "g4", "sGoodsName": "商品四", "iCategoryId": "1", "iPrice": "40", "iGoodsLeft": "0"}}
items = []map[string]string{{"iGoodsId": "g2", "sGoodsName": "重复商品", "iCategoryId": "45", "iPrice": "0", "iJb2Price": "20", "sPayType": "jb2", "iGoodsLeft": "3"}, {"iGoodsId": "g4", "sGoodsName": "商品四", "iCategoryId": "1", "iPrice": "40", "sPayType": "qpqb", "iGoodsLeft": "0"}}
}
}
body, _ := json.Marshal(map[string]any{"data": map[string]any{"client_data": map[string]any{"itemsdetail": items}}})
@@ -218,6 +219,9 @@ func TestProductsAutomaticallyResolvesXiaodianRoleAndPaginates(t *testing.T) {
if products[1].Category != "45" || products[3].Score != 30 {
t.Fatalf("商品字段 = %#v", products)
}
if products[0].PayType != 1 || products[0].PayLabel != "点券" || products[1].PayType != 5 || products[1].PayLabel != "扭蛋碎片" || products[1].Score != 20 {
t.Fatalf("支付字段 = %#v", products)
}
if got := strings.Join(goodsRequests, ","); got != ":iCategoryId_76:0,:iCategoryId_76:2,:iCategoryId_76:4,76::0" {
t.Fatalf("分类分页请求 = %s", got)
}
@@ -230,6 +234,72 @@ func TestProductsAutomaticallyResolvesXiaodianRoleAndPaginates(t *testing.T) {
}
}
func TestXiaodianExchangeProductUsesLiveBuyPayTypes(t *testing.T) {
var requests []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/embed":
_, _ = w.Write([]byte(`{"error":0,"data":{"txurlH5":"https://app.daoju.qq.com/act/a20260602cjmshop/index.html?gameId=cjm&actId=18882&appId=bp_cf&livePlatId=douyu&code=code&timestamp=1&v=2.0&sig=sig"}}`))
case "/daoju/igw/livebuy/":
requests = append(requests, r.URL.RawQuery)
if got := r.URL.Query().Get("_service"); got != "buy.plug.svr.web" {
t.Errorf("_service = %q", got)
}
if got := r.URL.Query().Get("iActionId"); got != "46195" {
t.Errorf("iActionId = %q", got)
}
_, _ = w.Write([]byte(`var buyInfo={"ret":"0","msg":"ok","serial":"CJM-1","sSerialNum":"CJM-1"};`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
act := &activity.Activity{
ID: "xiaodian", DisplayName: "和平小店", RoomID: "9263298", ActAlias: "20260623KDQFH",
ActID: "46195", RoleParamURL: server.URL + "/embed", RoleURL: server.URL + "/daoju/igw/live", IsXiaodian: true,
}
cli := New(act, "", &trace.Recorder{})
cli.HTTPClient = server.Client()
got, err := cli.ExchangeProduct("acf_uid=uid; acf_stk=stk; acf_ltkid=ltkid", types.Product{
CommodityID: "g-dq", Score: 8800, PayType: 1, Pic: "pic-dq",
}, nil)
if err != nil {
t.Fatalf("点券 ExchangeProduct() error = %v", err)
}
if !strings.Contains(got, "serial=CJM-1") {
t.Fatalf("点券返回 = %q", got)
}
got, err = cli.ExchangeProduct("acf_uid=uid; acf_stk=stk; acf_ltkid=ltkid", types.Product{
CommodityID: "g-jb2", Score: 108, PayType: 5, Pic: "pic-jb2",
}, nil)
if err != nil {
t.Fatalf("碎片 ExchangeProduct() error = %v", err)
}
if !strings.Contains(got, "paytype=5") {
t.Fatalf("碎片返回 = %q", got)
}
if len(requests) != 2 {
t.Fatalf("请求数量 = %d", len(requests))
}
first, _ := url.ParseQuery(requests[0])
second, _ := url.ParseQuery(requests[1])
if first.Get("paytype") != "1" || first.Get("propid") != "g-dq" {
t.Fatalf("点券请求 = %s", requests[0])
}
if second.Get("paytype") != "5" || second.Get("propid") != "g-jb2" {
t.Fatalf("碎片请求 = %s", requests[1])
}
var appext map[string]any
if err := json.Unmarshal([]byte(second.Get("appext")), &appext); err != nil {
t.Fatalf("appext 解析失败: %v", err)
}
if appext["user_price"].(float64) != 108 || appext["paytype"].(float64) != 5 {
t.Fatalf("碎片 appext = %#v", appext)
}
}
func TestXiaodianExchangeListUsesOrderListAndParsesGoods(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {