1
0

biliqrcode.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // ============================================================================
  2. // biliqrcode.go — B站二维码扫码登录
  3. //
  4. // 流程(B站官方二维码登录接口):
  5. // 1. GET /x/passport-login/web/qrcode/generate → 生成二维码(data.url + data.qrcode_key)
  6. // 2. 前端展示二维码,用户用 B站 App 扫码
  7. // 3. 轮询 GET /x/passport-login/web/qrcode/poll → 登录状态
  8. // data.code=0 登录成功(data.url 为 SSO 回调,需 GET 它取 Set-Cookie)
  9. // data.code=86038 二维码已失效
  10. // data.code=86090 未扫码
  11. // data.code=86101 已扫码未确认
  12. // 4. 成功后提取 cookie(SESSDATA 等)+ refresh_token,保存到设置
  13. //
  14. // 说明:二维码接口同样受风控影响,可能返回 code=-352(需验证),此时提示用户。
  15. // ============================================================================
  16. package main
  17. import (
  18. "encoding/base64"
  19. "encoding/json"
  20. "fmt"
  21. "io"
  22. "net/http"
  23. "net/url"
  24. "strings"
  25. "time"
  26. qrcode "github.com/skip2/go-qrcode"
  27. )
  28. const (
  29. biliQRGenerateURL = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"
  30. biliQRPollURL = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll"
  31. biliUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
  32. )
  33. // BiliQRResult 二维码生成结果:qrcodeKey 供轮询,imageDataURI 为二维码 PNG data URI
  34. type BiliQRResult struct {
  35. QrcodeKey string `json:"qrcodeKey"`
  36. ImageDataURI string `json:"imageDataURI"` // data:image/png;base64,...
  37. ExpireAt int64 `json:"expireAt"` // 二维码过期时间戳(毫秒)
  38. }
  39. // BiliQRPollResult 轮询结果
  40. // Status: pending(未扫码) / scanned(已扫码未确认) / success(登录成功) / expired(失效) / error
  41. // Message: 附加说明(如风控提示)
  42. type BiliQRPollResult struct {
  43. Status string `json:"status"`
  44. Message string `json:"message"`
  45. Cookie string `json:"cookie,omitempty"` // 仅 success 时返回新 cookie(供前端回填)
  46. RefreshToken string `json:"refreshToken,omitempty"` // 仅 success 时返回新 refresh_token(供前端回填)
  47. }
  48. // biliQRData 二维码接口 data 字段
  49. type biliQRData struct {
  50. URL string `json:"url"` // generate: 二维码内容;poll success: SSO 回调链接
  51. QrcodeKey string `json:"qrcode_key"` // generate: 轮询 key
  52. RefreshToken string `json:"refresh_token"` // poll success: 新 refresh_token
  53. Code int `json:"code"` // poll: 登录状态码
  54. Message2 string `json:"message"` // poll: 状态说明
  55. }
  56. // biliQRPayload 二维码接口响应结构
  57. type biliQRPayload struct {
  58. Code int `json:"code"`
  59. Message string `json:"message"`
  60. Data biliQRData `json:"data"`
  61. }
  62. // biliQRGenerate 生成 B站登录二维码。返回二维码 key + PNG data URI。
  63. func biliQRGenerate() (*BiliQRResult, error) {
  64. client := &http.Client{Timeout: 12 * time.Second}
  65. // 先访问主页拿 buvid3(generate 接口可能要求),失败不阻断(接口本身可无 buvid)
  66. _, buvids := fetchBuvid3()
  67. req, err := http.NewRequest(http.MethodGet, biliQRGenerateURL, nil)
  68. if err != nil {
  69. return nil, err
  70. }
  71. req.Header.Set("User-Agent", biliUserAgent)
  72. req.Header.Set("Referer", biliHomeURL)
  73. req.Header.Set("Accept", "application/json")
  74. if buvids != "" {
  75. req.Header.Set("Cookie", buvids)
  76. }
  77. resp, err := client.Do(req)
  78. if err != nil {
  79. return nil, err
  80. }
  81. defer resp.Body.Close()
  82. body, _ := io.ReadAll(resp.Body)
  83. var p biliQRPayload
  84. if err := json.Unmarshal(body, &p); err != nil {
  85. return nil, fmt.Errorf("解析二维码生成响应失败: %w", err)
  86. }
  87. if p.Code != 0 {
  88. return nil, fmt.Errorf("二维码生成接口返回 code=%d message=%s", p.Code, p.Message)
  89. }
  90. key := strings.TrimSpace(p.Data.QrcodeKey)
  91. qrURL := strings.TrimSpace(p.Data.URL)
  92. if key == "" || qrURL == "" {
  93. return nil, fmt.Errorf("二维码生成响应缺少 qrcode_key 或 url")
  94. }
  95. // 用 go-qrcode 生成 240x240 PNG 二维码,转 data URI 供前端 <img> 显示
  96. png, err := qrcode.Encode(qrURL, qrcode.Medium, 240)
  97. if err != nil {
  98. return nil, fmt.Errorf("生成二维码图片失败: %w", err)
  99. }
  100. dataURI := "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
  101. return &BiliQRResult{
  102. QrcodeKey: key,
  103. ImageDataURI: dataURI,
  104. ExpireAt: time.Now().Add(3 * time.Minute).UnixMilli(), // 二维码通常 3 分钟有效
  105. }, nil
  106. }
  107. // biliQRPoll 轮询二维码登录状态。登录成功时提取 cookie 并保存到设置。
  108. func biliQRPoll(qrcodeKey string) (*BiliQRPollResult, error) {
  109. qrcodeKey = strings.TrimSpace(qrcodeKey)
  110. if qrcodeKey == "" {
  111. return nil, fmt.Errorf("缺少 qrcode_key")
  112. }
  113. client := &http.Client{Timeout: 12 * time.Second}
  114. pollURL := biliQRPollURL + "?qrcode_key=" + url.QueryEscape(qrcodeKey)
  115. req, err := http.NewRequest(http.MethodGet, pollURL, nil)
  116. if err != nil {
  117. return nil, err
  118. }
  119. req.Header.Set("User-Agent", biliUserAgent)
  120. req.Header.Set("Referer", biliHomeURL)
  121. req.Header.Set("Accept", "application/json")
  122. resp, err := client.Do(req)
  123. if err != nil {
  124. return nil, err
  125. }
  126. defer resp.Body.Close()
  127. body, _ := io.ReadAll(resp.Body)
  128. var p biliQRPayload
  129. if err := json.Unmarshal(body, &p); err != nil {
  130. return nil, fmt.Errorf("解析轮询响应失败: %w", err)
  131. }
  132. if p.Code != 0 {
  133. // -352 为风控(需人机验证)
  134. return &BiliQRPollResult{Status: "error", Message: fmt.Sprintf("轮询接口返回 code=%d(%s)", p.Code, p.Message)}, nil
  135. }
  136. switch p.Data.Code {
  137. case 0:
  138. // 登录成功:轮询响应的 Set-Cookie + 回调(URL 参数 / Set-Cookie)提取登录凭据
  139. return biliQRLoginSuccess(client, resp.Cookies(), p.Data)
  140. case 86038:
  141. return &BiliQRPollResult{Status: "expired", Message: "二维码已失效,请刷新重新扫码"}, nil
  142. case 86090:
  143. return &BiliQRPollResult{Status: "pending", Message: "请用 B站 App 扫码登录"}, nil
  144. case 86101:
  145. return &BiliQRPollResult{Status: "scanned", Message: "已扫码,请在手机上确认登录"}, nil
  146. default:
  147. return &BiliQRPollResult{Status: "pending", Message: fmt.Sprintf("等待扫码(状态 %d)", p.Data.Code)}, nil
  148. }
  149. }
  150. // biliQRLoginSuccess 登录成功处理:提取 cookie + refresh_token 保存。
  151. // SESSDATA/bili_jct 等登录凭据有三个来源(按优先级从低到高合并):
  152. // 1. 轮询响应的 Set-Cookie(pollCookies)
  153. // 2. 回调 URL(crossDomain 链接)的查询参数里直接带有 SESSDATA/bili_jct/DedeUserID
  154. // 3. GET 回调地址时 Set-Cookie 返回(可能在重定向链的中间跳,需 CheckRedirect 逐跳捕获)
  155. func biliQRLoginSuccess(client *http.Client, pollCookies []*http.Cookie, data biliQRData) (*BiliQRPollResult, error) {
  156. if data.URL == "" {
  157. return &BiliQRPollResult{Status: "error", Message: "登录成功但未返回回调地址"}, nil
  158. }
  159. var parts []string
  160. seen := map[string]bool{}
  161. addKV := func(k, v string) {
  162. k, v = strings.TrimSpace(k), strings.TrimSpace(v)
  163. if k == "" || v == "" || seen[k] {
  164. return
  165. }
  166. seen[k] = true
  167. parts = append(parts, k+"="+v)
  168. }
  169. // 来源 1:轮询响应的 Set-Cookie(优先级最低,先加)
  170. for _, c := range pollCookies {
  171. addKV(c.Name, c.Value)
  172. }
  173. // 来源 1:回调 URL 查询参数(crossDomain 链接直接携带登录凭据)
  174. if u, perr := url.Parse(data.URL); perr == nil {
  175. q := u.Query()
  176. for _, k := range []string{"SESSDATA", "bili_jct", "DedeUserID", "DedeUserID__ckMd5", "buvid3", "sid"} {
  177. addKV(k, q.Get(k))
  178. }
  179. }
  180. // 来源 2:GET 回调地址,捕获重定向链上每一跳响应的 Set-Cookie
  181. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  182. if req.Response != nil {
  183. for _, c := range req.Response.Cookies() {
  184. addKV(c.Name, c.Value)
  185. }
  186. }
  187. if len(via) >= 10 {
  188. return fmt.Errorf("重定向次数过多")
  189. }
  190. return nil
  191. }
  192. req, err := http.NewRequest(http.MethodGet, data.URL, nil)
  193. if err != nil {
  194. return nil, err
  195. }
  196. req.Header.Set("User-Agent", biliUserAgent)
  197. req.Header.Set("Referer", biliHomeURL)
  198. req.Header.Set("Accept", "application/json")
  199. resp, err := client.Do(req)
  200. if err == nil {
  201. defer resp.Body.Close()
  202. io.Copy(io.Discard, resp.Body)
  203. for _, c := range resp.Cookies() { // 最终响应的 Set-Cookie
  204. addKV(c.Name, c.Value)
  205. }
  206. }
  207. // 与已有 cookie 合并(保留 buvid3 等未覆盖项),再校验 SESSDATA
  208. settings := loadSettings()
  209. var cks []*http.Cookie
  210. for _, p := range parts {
  211. if k, v, ok := strings.Cut(p, "="); ok {
  212. cks = append(cks, &http.Cookie{Name: k, Value: v})
  213. }
  214. }
  215. cookie := mergeCookie(settings.BiliCookie, cks)
  216. if biliCookieValue(cookie, "SESSDATA") == "" {
  217. return &BiliQRPollResult{Status: "error", Message: "登录成功但未获取到 SESSDATA(回调未携带登录凭据,请重试扫码)"}, nil
  218. }
  219. // 保存到设置:cookie + refresh_token(复用 refreshBiliCookie 的续期链路)
  220. settings.BiliCookie = cookie
  221. rt := strings.TrimSpace(data.RefreshToken)
  222. if rt != "" {
  223. settings.BiliRefreshToken = rt
  224. }
  225. if err := saveSettings(settings); err != nil {
  226. return nil, fmt.Errorf("保存登录 cookie 失败: %w", err)
  227. }
  228. return &BiliQRPollResult{Status: "success", Message: "登录成功", Cookie: cookie, RefreshToken: rt}, nil
  229. }