weixinRegistration.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import { DEFAULT_WEIXIN_ILINK_BASE_URL } from "./weixinProvider.js";
  2. interface WeixinRegistrationBeginResult {
  3. qrCode: string;
  4. qrUrl: string;
  5. interval: number;
  6. expiresAt: number;
  7. }
  8. interface WeixinRegistrationPollParams {
  9. qrCode: string;
  10. }
  11. type WeixinRegistrationPollResult =
  12. | {
  13. status: "pending" | "scanned";
  14. interval: number;
  15. }
  16. | {
  17. status: "success";
  18. botToken: string;
  19. botId?: string;
  20. }
  21. | {
  22. status: "expired" | "error";
  23. message?: string;
  24. };
  25. interface WeixinQrBeginResponse {
  26. ret?: number;
  27. errcode?: number;
  28. errmsg?: string;
  29. data?: unknown;
  30. qrcode?: string;
  31. qr_code?: string;
  32. qrcode_url?: string;
  33. qrcode_img_content?: string;
  34. expire_time?: number;
  35. expires_in?: number;
  36. }
  37. interface WeixinQrPollResponse {
  38. ret?: number;
  39. errcode?: number;
  40. errmsg?: string;
  41. data?: unknown;
  42. status?: string | number;
  43. bot_token?: string;
  44. token?: string;
  45. ilink_bot_id?: string;
  46. bot_id?: string;
  47. baseurl?: string;
  48. base_url?: string;
  49. }
  50. const WEIXIN_BOT_API_PREFIX = "/ilink/bot";
  51. const WEIXIN_LOGIN_INTERVAL_SECONDS = 3;
  52. const WEIXIN_LOGIN_EXPIRE_SECONDS = 120;
  53. const WEIXIN_LOGIN_REQUEST_TIMEOUT_MS = 30_000;
  54. function isRecord(value: unknown): value is Record<string, unknown> {
  55. return typeof value === "object" && value !== null;
  56. }
  57. function readString(record: Record<string, unknown> | null | undefined, key: string): string {
  58. const value = record?.[key];
  59. return typeof value === "string" ? value : "";
  60. }
  61. function readNumber(record: Record<string, unknown> | null | undefined, key: string): number | null {
  62. const value = record?.[key];
  63. return typeof value === "number" && Number.isFinite(value) ? value : null;
  64. }
  65. function getWeixinRegistrationBaseUrl(): string {
  66. return DEFAULT_WEIXIN_ILINK_BASE_URL.replace(/\/+$/u, "");
  67. }
  68. function unwrapData(payload: unknown): Record<string, unknown> {
  69. if (!isRecord(payload)) {
  70. return {};
  71. }
  72. return isRecord(payload.data) ? { ...payload, ...payload.data } : payload;
  73. }
  74. async function getWeixinRegistrationJson<T>(baseUrl: string, path: string): Promise<T & Record<string, unknown>> {
  75. const response = await fetch(`${baseUrl}${WEIXIN_BOT_API_PREFIX}${path}`, {
  76. method: "GET",
  77. headers: { "iLink-App-ClientVersion": "1" },
  78. signal: AbortSignal.timeout(WEIXIN_LOGIN_REQUEST_TIMEOUT_MS),
  79. });
  80. if (!response.ok) {
  81. throw new Error(`Weixin login ${path} failed: HTTP ${response.status}`);
  82. }
  83. const payload = unwrapData(await response.json()) as T & Record<string, unknown>;
  84. const ret = readNumber(payload, "ret");
  85. const errcode = readNumber(payload, "errcode");
  86. if ((ret !== null && ret !== 0) || (errcode !== null && errcode !== 0)) {
  87. throw new Error(readString(payload, "errmsg") || `ret=${ret ?? ""} errcode=${errcode ?? ""}`.trim());
  88. }
  89. return payload;
  90. }
  91. function normalizeQrStatus(status: unknown): "pending" | "scanned" | "success" | "expired" | "error" {
  92. if (typeof status === "number") {
  93. if (status === 0) return "pending";
  94. if (status === 1) return "scanned";
  95. if (status === 2) return "success";
  96. if (status === 3 || status === 4) return "expired";
  97. }
  98. if (typeof status !== "string") {
  99. return "pending";
  100. }
  101. const normalized = status.toLowerCase();
  102. if (["confirmed", "confirm", "authorized", "success", "ok"].includes(normalized)) {
  103. return "success";
  104. }
  105. if (["scaned", "scanned", "scan", "confirmed_wait"].includes(normalized)) {
  106. return "scanned";
  107. }
  108. if (["expired", "timeout", "cancel", "cancelled", "canceled"].includes(normalized)) {
  109. return "expired";
  110. }
  111. if (["error", "failed", "fail"].includes(normalized)) {
  112. return "error";
  113. }
  114. return "pending";
  115. }
  116. export async function beginWeixinRegistration(): Promise<WeixinRegistrationBeginResult> {
  117. const baseUrl = getWeixinRegistrationBaseUrl();
  118. const payload = await getWeixinRegistrationJson<WeixinQrBeginResponse>(baseUrl, "/get_bot_qrcode?bot_type=3");
  119. const qrCode = readString(payload, "qrcode") || readString(payload, "qr_code");
  120. const qrUrl = readString(payload, "qrcode_img_content") || readString(payload, "qrcode_url") || qrCode;
  121. if (!qrCode || !qrUrl) {
  122. throw new Error("Weixin login did not return a QR code.");
  123. }
  124. const expireSeconds = readNumber(payload, "expires_in") ?? WEIXIN_LOGIN_EXPIRE_SECONDS;
  125. return {
  126. qrCode,
  127. qrUrl,
  128. interval: WEIXIN_LOGIN_INTERVAL_SECONDS,
  129. expiresAt: Date.now() + expireSeconds * 1000,
  130. };
  131. }
  132. export async function pollWeixinRegistration(
  133. params: WeixinRegistrationPollParams,
  134. ): Promise<WeixinRegistrationPollResult> {
  135. const baseUrl = getWeixinRegistrationBaseUrl();
  136. let payload: WeixinQrPollResponse & Record<string, unknown>;
  137. try {
  138. payload = await getWeixinRegistrationJson<WeixinQrPollResponse>(
  139. baseUrl,
  140. `/get_qrcode_status?qrcode=${encodeURIComponent(params.qrCode)}`,
  141. );
  142. } catch (error) {
  143. if (error instanceof DOMException && error.name === "TimeoutError") {
  144. // Bugfix: 微信扫码状态接口可能长时间挂起等待手机端确认,超时不代表登录失败。
  145. // 返回 pending 让 UI 串行继续轮询,避免把正常等待误报成错误。
  146. return { status: "pending", interval: WEIXIN_LOGIN_INTERVAL_SECONDS };
  147. }
  148. throw error;
  149. }
  150. const status = normalizeQrStatus(payload.status ?? payload["qrcode_status"] ?? payload["qr_status"]);
  151. if (status === "success") {
  152. const botToken = readString(payload, "bot_token") || readString(payload, "token");
  153. if (!botToken) {
  154. return { status: "error", message: "Weixin login succeeded but did not return bot_token." };
  155. }
  156. return {
  157. status: "success",
  158. botToken,
  159. botId: readString(payload, "ilink_bot_id") || readString(payload, "bot_id") || undefined,
  160. };
  161. }
  162. if (status === "expired") {
  163. return { status: "expired" };
  164. }
  165. if (status === "error") {
  166. return { status: "error", message: readString(payload, "errmsg") || "Weixin login failed." };
  167. }
  168. return { status, interval: WEIXIN_LOGIN_INTERVAL_SECONDS };
  169. }