fix(semi-auto): 扫码后主动提交换绑并透出虎牙失败原因

This commit is contained in:
2026-11-16 14:00:17 +08:00
parent 5aa627a0ca
commit ad59c87e13
9 changed files with 475 additions and 63 deletions
@@ -16,6 +16,7 @@ import {
startPublicBinding, startPublicBinding,
startPublicLogin, startPublicLogin,
startPublicWeiboQrLogin, startPublicWeiboQrLogin,
submitPublicRebind,
verifyPublicHuyaSmsChallenge, verifyPublicHuyaSmsChallenge,
} from '../services/semi-auto/semi-auto-task-service.js' } from '../services/semi-auto/semi-auto-task-service.js'
import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js' import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js'
@@ -106,6 +107,16 @@ router.get(
}), }),
) )
router.post(
'/:orderNo/tasks/:taskId/binding/rebind',
writeLimit,
createRouteHandler((req) => submitPublicRebind(req.params.orderNo, req.params.taskId), {
successMessage: '换绑请求已提交',
errorMessage: '提交换绑失败',
scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/rebind]',
}),
)
router.post( router.post(
'/:orderNo/tasks/:taskId/binding/confirm', '/:orderNo/tasks/:taskId/binding/confirm',
writeLimit, writeLimit,
@@ -202,3 +202,44 @@ test('重新扫码换绑会向 Connector 传递 force_rebind', async () => {
globalThis.fetch = originalFetch globalThis.fetch = originalFetch
} }
}) })
test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async () => {
const originalFetch = globalThis.fetch
let requestUrl = ''
let requestBody: Record<string, unknown> = {}
globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
requestUrl = String(url)
requestBody = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
return new Response(
JSON.stringify({
sessionId: 'session-1',
status: 'scanned',
qrImage: '',
qrExpiresAt: '',
qrUrl: '',
bindGameAccount: '微信用户',
bindGameRole: '大鲨鱼伊塞53',
bindGameRoleId: '1199608910400',
bindGameChannel: '安卓(android) · 微信',
rebindRequested: true,
rebindUnchanged: false,
rebindConfirmState: 'accepted',
rebindConfirmMessage: '',
message: '虎牙已受理换绑,正在等待角色生效',
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}) as typeof fetch
try {
const session = await connector.submitHuyaRebind('session-1', 'external')
assert.equal(
requestUrl,
'http://connector.test/api/internal/huya-semi-auto/sessions/session-1/binding/confirm',
)
assert.deepEqual(requestBody, { rebind: true })
assert.equal(session.rebindConfirmState, 'accepted')
assert.equal(session.rebindRequested, true)
} finally {
globalThis.fetch = originalFetch
}
})
@@ -103,6 +103,8 @@ export type ConnectorBindingSession = {
hasExistingBinding?: boolean hasExistingBinding?: boolean
rebindRequested?: boolean rebindRequested?: boolean
rebindUnchanged?: boolean rebindUnchanged?: boolean
rebindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
rebindConfirmMessage?: string
rebindCooldownDays?: number rebindCooldownDays?: number
nextRebindAt?: string nextRebindAt?: string
platformChangeBindDay?: number platformChangeBindDay?: number
@@ -429,6 +431,22 @@ export async function confirmHuyaBinding(
) )
} }
/**
* 扫码后由项目侧主动向虎牙提交换绑确认。
* 外部 Connector 暂未提供独立端点时复用 confirm 端点(语义一致,幂等)。
*/
export async function submitHuyaRebind(
sessionId: string,
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
): Promise<ConnectorBindingSession> {
if (mode === 'embedded') return huyaNativeConnector.submitRebind(sessionId)
return callConnector<ConnectorBindingSession>(
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
{ method: 'POST', body: { rebind: true } },
mode,
)
}
export async function createHuyaBrowserTicket( export async function createHuyaBrowserTicket(
input: { input: {
sessionId: string sessionId: string
@@ -54,6 +54,8 @@ const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
const BINDING_QR_TTL_MS = 5 * 60 * 1000 const BINDING_QR_TTL_MS = 5 * 60 * 1000
const REBIND_WINDOW_DAYS = 7 const REBIND_WINDOW_DAYS = 7
const DAY_MS = 24 * 60 * 60 * 1000 const DAY_MS = 24 * 60 * 60 * 1000
// 提交换绑后给虎牙留的生效时间;期间前端继续轮询,不提前判失败。
const REBIND_EFFECT_WINDOW_MS = 60 * 1000
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000 const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
const MAX_SESSIONS = 500 const MAX_SESSIONS = 500
const NATIVE_TICKET_PREFIX = 'native-ticket-' const NATIVE_TICKET_PREFIX = 'native-ticket-'
@@ -76,6 +78,10 @@ type NativeBindState = {
rebindRequested: boolean rebindRequested: boolean
rebindScanned: boolean rebindScanned: boolean
rebindUnchanged: boolean rebindUnchanged: boolean
rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected'
rebindConfirmMessage: string
rebindConfirmAt: number
rebindEffectDeadlineMs: number
rebindCooldownDays: number rebindCooldownDays: number
nextRebindAt: string nextRebindAt: string
changeBindTime: number changeBindTime: number
@@ -156,6 +162,10 @@ function defaultBindingState(): NativeBindState {
rebindRequested: false, rebindRequested: false,
rebindScanned: false, rebindScanned: false,
rebindUnchanged: false, rebindUnchanged: false,
rebindConfirmState: 'idle',
rebindConfirmMessage: '',
rebindConfirmAt: 0,
rebindEffectDeadlineMs: 0,
rebindCooldownDays: 0, rebindCooldownDays: 0,
nextRebindAt: '', nextRebindAt: '',
changeBindTime: 0, changeBindTime: 0,
@@ -188,8 +198,9 @@ export type RebindCooldownInput = {
} }
/** /**
* 虎牙活动限制:每 7 个自然日允许换绑 1 次。 * 虎牙活动提示:每 7 个自然日允许换绑 1 次。
* changeBindTime 为上次绑定/换绑时间(秒级 Unix 时间戳),changeBindDay 作为兜底剩余天数。 * 这里计算的是「本次绑定后预计下次可换绑时间」,只用于文案展示,
* 不能作为本次提交换绑的前置拦截;是否允许以 confirmBindActAccount 的返回为准。
*/ */
export function resolveRebindCooldown( export function resolveRebindCooldown(
response: RebindCooldownInput | null | undefined, response: RebindCooldownInput | null | undefined,
@@ -229,16 +240,16 @@ function applyRebindMeta(
session.binding.changeBindDay = Number(response?.changeBindDay || 0) session.binding.changeBindDay = Number(response?.changeBindDay || 0)
} }
function rebindUnchangedMessage( function rebindFailureMessage(
roleName: string, roleName: string,
cooldownDays: number, platformMessage: string,
nextRebindAt: string, nextRebindAt: string,
): string { ): string {
// 优先展示虎牙原始原因(例如「7 天内只能换绑 1 次」),不要本地编造失败原因。
const raw = readString(platformMessage)
if (raw) return `换绑未成功:${raw}`
const next = rebindDateLabel(nextRebindAt) const next = rebindDateLabel(nextRebindAt)
if (cooldownDays > 0) { return `换绑已提交,但平台仍返回原绑定角色「${roleName}」${next ? `,预计下次换绑:${next}` : ''};请稍后刷新或重新提交换绑`
return `扫码后仍识别到原绑定角色「${roleName}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}`
}
return `扫码后仍识别到原绑定角色「${roleName}」,请确认微信中选择的角色或重新换绑`
} }
function extractInt(value: unknown): number { function extractInt(value: unknown): number {
@@ -763,9 +774,9 @@ export class HuyaNativeConnector {
this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested) this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested)
if (session.binding.rebindRequested) { if (session.binding.rebindRequested) {
session.binding.message = session.binding.rebindUnchanged session.binding.message = session.binding.rebindUnchanged
? rebindUnchangedMessage( ? rebindFailureMessage(
role.role, role.role,
session.binding.rebindCooldownDays, session.binding.rebindConfirmMessage,
session.binding.nextRebindAt, session.binding.nextRebindAt,
) )
: '已识别待换绑角色,请确认换绑' : '已识别待换绑角色,请确认换绑'
@@ -833,6 +844,10 @@ export class HuyaNativeConnector {
session.binding.rebindRequested = true session.binding.rebindRequested = true
session.binding.rebindScanned = false session.binding.rebindScanned = false
session.binding.rebindUnchanged = false session.binding.rebindUnchanged = false
session.binding.rebindConfirmState = 'idle'
session.binding.rebindConfirmMessage = ''
session.binding.rebindConfirmAt = 0
session.binding.rebindEffectDeadlineMs = 0
session.binding.baselineRoleKey = bindingRoleKey(role) session.binding.baselineRoleKey = bindingRoleKey(role)
} }
session.binding.status = 'qr_pending' session.binding.status = 'qr_pending'
@@ -847,6 +862,40 @@ export class HuyaNativeConnector {
}) })
} }
/**
* 扫码完成后由项目侧替客户点「确认绑定」。
* confirmBindActAccount 确认的是虎牙侧已选中的角色,必须在读取新角色之前调用;
* 若客户已在虎牙弹窗里点过确认,重复调用是幂等的。
*/
private async submitRebindLocked(session: NativeSession, rpc: HuyaRpcClient): Promise<void> {
const { bindActId, outerActId } = configValues()
const now = this.now()
session.binding.rebindConfirmState = 'submitting'
session.binding.rebindConfirmMessage = ''
session.binding.rebindConfirmAt = now
try {
const confirmed = await rpc.confirmBindActAccount({
uid: session.uid,
cookie: session.cookie,
bindActId,
outerActId,
})
if (confirmed && confirmed.status === 200) {
session.binding.rebindConfirmState = 'accepted'
session.binding.rebindEffectDeadlineMs = now + REBIND_EFFECT_WINDOW_MS
session.binding.message = '虎牙已受理换绑,正在等待角色生效'
return
}
session.binding.rebindConfirmState = 'rejected'
session.binding.rebindConfirmMessage = confirmed?.msg || '虎牙未接受本次换绑'
session.binding.message = `虎牙未接受本次换绑:${session.binding.rebindConfirmMessage}`
} catch (error) {
session.binding.rebindConfirmState = 'rejected'
session.binding.rebindConfirmMessage = errorMessage(error)
session.binding.message = `提交换绑失败:${session.binding.rebindConfirmMessage}`
}
}
async pollBinding(sessionId: string): Promise<ConnectorBindingSession> { async pollBinding(sessionId: string): Promise<ConnectorBindingSession> {
return this.withLock(sessionId, async () => { return this.withLock(sessionId, async () => {
const session = this.requireAuthenticatedSession(sessionId) const session = this.requireAuthenticatedSession(sessionId)
@@ -865,7 +914,9 @@ export class HuyaNativeConnector {
} }
if (qrStatus.isScan) { if (qrStatus.isScan) {
session.binding.status = 'scanned' session.binding.status = 'scanned'
session.binding.message = '已扫码,等待绑定完成' session.binding.message = session.binding.rebindRequested
? '已扫码,请在虎牙确认框中选中目标角色'
: '已扫码,等待绑定完成'
} }
if (qrStatus.isScan || qrStatus.isCompleted) { if (qrStatus.isScan || qrStatus.isCompleted) {
session.binding.rebindScanned = true session.binding.rebindScanned = true
@@ -877,6 +928,15 @@ export class HuyaNativeConnector {
return this.bindingView(session) return this.bindingView(session)
} }
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs })
// 小程序流程结束后立即由项目侧提交换绑,不再等角色自己变化。
if (
session.binding.rebindRequested &&
session.binding.rebindScanned &&
qrCompleted &&
session.binding.rebindConfirmState === 'idle'
) {
await this.submitRebindLocked(session, rpc)
}
const response = await rpc.checkUserBindGameAccount({ const response = await rpc.checkUserBindGameAccount({
uid: session.uid, uid: session.uid,
cookie: session.cookie, cookie: session.cookie,
@@ -898,20 +958,36 @@ export class HuyaNativeConnector {
const changedRole = const changedRole =
!session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey !session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey
if (rebindRequested && !changedRole) { if (rebindRequested && !changedRole) {
if (qrCompleted || session.binding.rebindUnchanged) { if (session.binding.rebindConfirmState === 'rejected') {
// 扫码完成但虎牙仍返回原角色:保留 rebind 状态,明确告知未换绑及冷却原因, // 虎牙明确拒绝:保留 rebind 状态并展示虎牙原文,不能清空 rebindRequested。
// 不能清空 rebindRequested,否则 confirmBinding 会误判为“使用已有绑定”。
session.binding.rebindUnchanged = true session.binding.rebindUnchanged = true
this.markRoleReady(session, role, hasExistingBinding) this.markRoleReady(session, role, hasExistingBinding)
session.binding.message = rebindUnchangedMessage( session.binding.message = rebindFailureMessage(
role.role, role.role,
session.binding.rebindCooldownDays, session.binding.rebindConfirmMessage,
session.binding.nextRebindAt, session.binding.nextRebindAt,
) )
} else { return this.bindingView(session)
session.binding.status = 'scanned'
session.binding.message = '已扫码,正在等待换绑角色生效'
} }
if (session.binding.rebindConfirmState === 'accepted') {
if (this.now() < session.binding.rebindEffectDeadlineMs) {
session.binding.status = 'scanned'
session.binding.message = '虎牙已受理换绑,正在等待角色生效'
} else {
session.binding.rebindUnchanged = true
this.markRoleReady(session, role, hasExistingBinding)
session.binding.message = rebindFailureMessage(
role.role,
session.binding.rebindConfirmMessage,
session.binding.nextRebindAt,
)
}
return this.bindingView(session)
}
session.binding.status = 'scanned'
session.binding.message = qrCompleted
? '扫码已完成,请点击「已选好角色,提交换绑」'
: '已扫码,请在虎牙确认框中选中目标角色'
return this.bindingView(session) return this.bindingView(session)
} }
if (rebindRequested) session.binding.rebindUnchanged = false if (rebindRequested) session.binding.rebindUnchanged = false
@@ -932,6 +1008,11 @@ export class HuyaNativeConnector {
const session = this.requireAuthenticatedSession(sessionId) const session = this.requireAuthenticatedSession(sessionId)
const { bindActId, outerActId } = configValues() const { bindActId, outerActId } = configValues()
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs })
const rebindRequested = session.binding.rebindRequested
if (rebindRequested && session.binding.rebindConfirmState !== 'accepted') {
// 客户点确认前再兜底提交一次,避免小程序扫码后项目没来得及自动提交。
await this.submitRebindLocked(session, rpc)
}
const response = await rpc.checkUserBindGameAccount({ const response = await rpc.checkUserBindGameAccount({
uid: session.uid, uid: session.uid,
cookie: session.cookie, cookie: session.cookie,
@@ -945,28 +1026,30 @@ export class HuyaNativeConnector {
errorCode: 'huya_bind_role_not_ready', errorCode: 'huya_bind_role_not_ready',
}) })
} }
const rebindRequested = session.binding.rebindRequested
applyRebindMeta(session, response, this.now()) applyRebindMeta(session, response, this.now())
if ( if (
rebindRequested && rebindRequested &&
session.binding.baselineRoleKey && session.binding.baselineRoleKey &&
bindingRoleKey(role) === session.binding.baselineRoleKey bindingRoleKey(role) === session.binding.baselineRoleKey
) { ) {
const cooldownDays = session.binding.rebindCooldownDays // 只有虎牙实际未生效时才拦截;冷却原因以虎牙返回的原文为准。
const next = rebindDateLabel(session.binding.nextRebindAt)
throw createHttpError( throw createHttpError(
cooldownDays > 0 rebindFailureMessage(
? `换绑未生效:平台仍返回原绑定角色「${role.role}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}` role.role,
: `换绑未生效:平台仍返回原绑定角色「${role.role}」,请重新扫码选择正确角色`, session.binding.rebindConfirmMessage,
session.binding.nextRebindAt,
),
{ {
statusCode: 409, statusCode: 409,
errorCode: errorCode:
cooldownDays > 0 ? 'huya_bind_rebind_cooldown' : 'huya_bind_rebind_not_ready', session.binding.rebindConfirmState === 'rejected'
? 'huya_bind_rebind_rejected'
: 'huya_bind_rebind_not_effective',
}, },
) )
} }
const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested
if (!useExistingBinding) { if (!useExistingBinding && session.binding.rebindConfirmState !== 'accepted') {
const confirmed = await rpc.confirmBindActAccount({ const confirmed = await rpc.confirmBindActAccount({
uid: session.uid, uid: session.uid,
cookie: session.cookie, cookie: session.cookie,
@@ -986,6 +1069,10 @@ export class HuyaNativeConnector {
session.binding.rebindRequested = false session.binding.rebindRequested = false
session.binding.rebindScanned = false session.binding.rebindScanned = false
session.binding.rebindUnchanged = false session.binding.rebindUnchanged = false
session.binding.rebindConfirmState = 'idle'
session.binding.rebindConfirmMessage = ''
session.binding.rebindConfirmAt = 0
session.binding.rebindEffectDeadlineMs = 0
session.binding.rebindCooldownDays = 0 session.binding.rebindCooldownDays = 0
session.binding.nextRebindAt = '' session.binding.nextRebindAt = ''
session.binding.baselineRoleKey = '' session.binding.baselineRoleKey = ''
@@ -998,6 +1085,54 @@ export class HuyaNativeConnector {
}) })
} }
/** 客户手动点击「已选好角色,提交换绑」时调用。 */
async submitRebind(sessionId: string): Promise<ConnectorBindingSession> {
return this.withLock(sessionId, async () => {
const session = this.requireAuthenticatedSession(sessionId)
if (!session.binding.rebindRequested) {
throw createHttpError('当前没有待换绑的角色,请重新扫码换绑', {
statusCode: 409,
errorCode: 'huya_bind_rebind_not_requested',
})
}
const { bindActId, outerActId } = configValues()
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs })
await this.submitRebindLocked(session, rpc)
const response = await rpc.checkUserBindGameAccount({
uid: session.uid,
cookie: session.cookie,
bindActId,
outerActId,
})
if (response && response.status === 200) {
const role = parseRole(response)
applyRebindMeta(session, response, this.now())
if (role.role) {
const changedRole =
!session.binding.baselineRoleKey ||
bindingRoleKey(role) !== session.binding.baselineRoleKey
if (changedRole) {
session.binding.rebindUnchanged = false
this.markRoleReady(session, role, false)
session.binding.message = '已识别换绑角色,请确认换绑'
} else if (session.binding.rebindConfirmState === 'rejected') {
session.binding.rebindUnchanged = true
this.markRoleReady(session, role, hasExistingHuyaBinding(response))
session.binding.message = rebindFailureMessage(
role.role,
session.binding.rebindConfirmMessage,
session.binding.nextRebindAt,
)
} else {
session.binding.status = 'scanned'
session.binding.message = '虎牙已受理换绑,正在等待角色生效'
}
}
}
return this.bindingView(session)
})
}
async createBrowserTicket(input: { async createBrowserTicket(input: {
sessionId: string sessionId: string
targetUrl?: string targetUrl?: string
@@ -1276,6 +1411,8 @@ export class HuyaNativeConnector {
hasExistingBinding: binding.hasExistingBinding, hasExistingBinding: binding.hasExistingBinding,
rebindRequested: binding.rebindRequested, rebindRequested: binding.rebindRequested,
rebindUnchanged: binding.rebindUnchanged, rebindUnchanged: binding.rebindUnchanged,
rebindConfirmState: binding.rebindConfirmState,
rebindConfirmMessage: binding.rebindConfirmMessage,
rebindCooldownDays: binding.rebindCooldownDays, rebindCooldownDays: binding.rebindCooldownDays,
nextRebindAt: binding.nextRebindAt, nextRebindAt: binding.nextRebindAt,
platformChangeBindDay: binding.changeBindDay, platformChangeBindDay: binding.changeBindDay,
@@ -27,6 +27,7 @@ import {
revokeHuyaSession, revokeHuyaSession,
sendHuyaSmsCode, sendHuyaSmsCode,
startHuyaBinding, startHuyaBinding,
submitHuyaRebind,
consumeHuyaBrowserTicket, consumeHuyaBrowserTicket,
verifyHuyaSmsChallenge, verifyHuyaSmsChallenge,
type ConnectorBindingSession, type ConnectorBindingSession,
@@ -956,6 +957,8 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
hasExistingBinding: session.hasExistingBinding === true, hasExistingBinding: session.hasExistingBinding === true,
rebindRequested: session.rebindRequested === true, rebindRequested: session.rebindRequested === true,
rebindUnchanged: session.rebindUnchanged === true, rebindUnchanged: session.rebindUnchanged === true,
rebindConfirmState: session.rebindConfirmState || 'idle',
rebindConfirmMessage: String(session.rebindConfirmMessage || ''),
rebindCooldownDays: Number(session.rebindCooldownDays || 0), rebindCooldownDays: Number(session.rebindCooldownDays || 0),
nextRebindAt: String(session.nextRebindAt || ''), nextRebindAt: String(session.nextRebindAt || ''),
platformChangeBindDay: Number(session.platformChangeBindDay || 0), platformChangeBindDay: Number(session.platformChangeBindDay || 0),
@@ -1139,6 +1142,8 @@ async function updateBindingTask(
verdict: comparison.verdict, verdict: comparison.verdict,
rebindRequested: mapped.rebindRequested, rebindRequested: mapped.rebindRequested,
rebindUnchanged: mapped.rebindUnchanged, rebindUnchanged: mapped.rebindUnchanged,
rebindConfirmState: mapped.rebindConfirmState,
rebindConfirmMessage: mapped.rebindConfirmMessage,
rebindCooldownDays: mapped.rebindCooldownDays, rebindCooldownDays: mapped.rebindCooldownDays,
nextRebindAt: mapped.nextRebindAt, nextRebindAt: mapped.nextRebindAt,
changeBindDay: mapped.platformChangeBindDay, changeBindDay: mapped.platformChangeBindDay,
@@ -1159,6 +1164,8 @@ async function updateBindingTask(
hasExistingBinding: mapped.hasExistingBinding, hasExistingBinding: mapped.hasExistingBinding,
rebindRequested: mapped.rebindRequested, rebindRequested: mapped.rebindRequested,
rebindUnchanged: mapped.rebindUnchanged, rebindUnchanged: mapped.rebindUnchanged,
rebindConfirmState: mapped.rebindConfirmState,
rebindConfirmMessage: mapped.rebindConfirmMessage,
rebindCooldownDays: mapped.rebindCooldownDays, rebindCooldownDays: mapped.rebindCooldownDays,
nextRebindAt: mapped.nextRebindAt, nextRebindAt: mapped.nextRebindAt,
platformChangeBindDay: mapped.platformChangeBindDay, platformChangeBindDay: mapped.platformChangeBindDay,
@@ -1358,8 +1365,8 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u
throw createHttpError(session.message || '换绑未生效:平台仍返回原绑定角色,请重新扫码', { throw createHttpError(session.message || '换绑未生效:平台仍返回原绑定角色,请重新扫码', {
statusCode: 409, statusCode: 409,
errorCode: errorCode:
Number(session.rebindCooldownDays || 0) > 0 session.rebindConfirmState === 'rejected'
? 'semi_auto_binding_rebind_cooldown' ? 'semi_auto_binding_rebind_rejected'
: 'semi_auto_binding_rebind_unchanged', : 'semi_auto_binding_rebind_unchanged',
}) })
} }
@@ -1380,6 +1387,38 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u
return { task: mapTask(updated), binding } return { task: mapTask(updated), binding }
} }
/**
* 客户在微信里选好目标角色后,由项目侧主动向虎牙提交换绑确认。
* 与「确认绑定」不同,这一步只提交换绑,不把任务标记为已确认。
*/
export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unknown) {
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能提交换绑', {
statusCode: 409,
errorCode: 'semi_auto_task_closed',
})
}
if (task.platform !== 'huya') {
throw createHttpError('当前平台不需要换绑游戏角色', {
statusCode: 409,
errorCode: 'semi_auto_rebind_not_supported',
})
}
if (!task.connector_session_id || task.login_status !== 'authenticated') {
throw createHttpError('请先完成平台登录', {
statusCode: 409,
errorCode: 'semi_auto_login_required',
})
}
const session = await submitHuyaRebind(task.connector_session_id, task.connector_mode)
const binding = await updateBindingTask(task, session, 'customer')
const updated = await loadTask(task.id)
return { task: mapTask(updated), binding }
}
export async function sendPublicHuyaSmsCode( export async function sendPublicHuyaSmsCode(
orderNoInput: unknown, orderNoInput: unknown,
taskIdInput: unknown, taskIdInput: unknown,
@@ -731,7 +731,7 @@ export default function AdminSemiAutoTasksPage() {
<Text <Text
type={ type={
event.detail.rebindUnchanged === true || event.detail.rebindUnchanged === true ||
Number(event.detail.rebindCooldownDays || 0) > 0 event.detail.rebindConfirmState === 'rejected'
? 'warning' ? 'warning'
: 'secondary' : 'secondary'
} }
@@ -745,6 +745,12 @@ export default function AdminSemiAutoTasksPage() {
: ''} : ''}
</Text> </Text>
) : null} ) : null}
{event.eventType === 'binding_status_changed' &&
event.detail?.rebindConfirmMessage ? (
<Text type="secondary">
虎牙返回:{String(event.detail.rebindConfirmMessage)}
</Text>
) : null}
</Space> </Space>
), ),
}))} }))}
@@ -26,6 +26,7 @@ import {
startCustomerBinding, startCustomerBinding,
startCustomerLogin, startCustomerLogin,
startCustomerWeiboQrLogin, startCustomerWeiboQrLogin,
submitCustomerRebind,
verifyCustomerHuyaSmsChallenge, verifyCustomerHuyaSmsChallenge,
type CustomerHuyaChallengeSolution, type CustomerHuyaChallengeSolution,
type CustomerHuyaSmsChallenge, type CustomerHuyaSmsChallenge,
@@ -306,6 +307,8 @@ export default function CustomerFulfillmentPage() {
if (!bindingInfo?.comparison) return if (!bindingInfo?.comparison) return
// 换绑后仍是原角色时只展示失败原因,不能自动弹出确认框。 // 换绑后仍是原角色时只展示失败原因,不能自动弹出确认框。
if (bindingInfo.rebindUnchanged) return if (bindingInfo.rebindUnchanged) return
// 平台角色与已填资料不一致时先引导同步资料,不能直接弹确认框。
if (bindingInfo.comparison.verdict === 'mismatch') return
const key = `${selectedTask.id}:${bindingInfo.bindGameRoleId || ''}` const key = `${selectedTask.id}:${bindingInfo.bindGameRoleId || ''}`
if (autoOpenedRoleRef.current === key) return if (autoOpenedRoleRef.current === key) return
autoOpenedRoleRef.current = key autoOpenedRoleRef.current = key
@@ -504,7 +507,18 @@ export default function CustomerFulfillmentPage() {
if (nextTask.bindingStatus === 'role_ready') { if (nextTask.bindingStatus === 'role_ready') {
if (nextBinding?.rebindUnchanged) { if (nextBinding?.rebindUnchanged) {
setBindingConfirmOpen(false) setBindingConfirmOpen(false)
message.warning(nextBinding.message || '换绑未生效,请查看下方原因') if (nextBinding.rebindConfirmState === 'rejected') {
message.error(nextBinding.message || '虎牙未接受本次换绑')
} else {
message.warning(nextBinding.message || '换绑未生效,请查看下方原因')
}
return
}
if (nextBinding?.comparison?.verdict === 'mismatch') {
setBindingConfirmOpen(false)
message.warning(
nextBinding.comparison.message || '平台角色与已填资料不一致,请先同步资料',
)
return return
} }
setBindingConfirmOpen(true) setBindingConfirmOpen(true)
@@ -519,7 +533,11 @@ export default function CustomerFulfillmentPage() {
if (openConfirm) setBindingConfirmOpen(false) if (openConfirm) setBindingConfirmOpen(false)
const detail = nextBinding?.message || '' const detail = nextBinding?.message || ''
if (nextTask.bindingStatus === 'scanned') { if (nextTask.bindingStatus === 'scanned') {
message.info(detail || '已扫码,正在等待虎牙平台换绑生效,请稍后再点击刷新') if (nextBinding?.rebindConfirmState === 'accepted') {
message.info('虎牙已受理换绑,正在等待角色生效')
return
}
message.info(detail || '已扫码,请选好角色后点「已选好角色,提交换绑」')
return return
} }
if (nextTask.bindingStatus === 'qr_pending') { if (nextTask.bindingStatus === 'qr_pending') {
@@ -548,6 +566,69 @@ export default function CustomerFulfillmentPage() {
} }
} }
async function handleSubmitRebind() {
if (!selectedTask) return
setBindingLoading(true)
try {
const response = await submitCustomerRebind(orderNo, selectedTask.id)
const nextTask = response.data.task
const nextBinding = response.data.binding
setTasks((current) => current.map((task) => (task.id === nextTask.id ? nextTask : task)))
if (nextBinding) setBindingInfo(nextBinding)
setBindingConfirmOpen(false)
if (nextBinding?.rebindUnchanged || nextBinding?.rebindConfirmState === 'rejected') {
message.error(nextBinding.message || '虎牙未接受本次换绑')
return
}
if (nextTask.bindingStatus === 'role_ready') {
message.success('换绑已生效,请核对角色后确认绑定')
return
}
message.info('已向虎牙提交换绑,正在等待角色生效')
} catch (error) {
if (isHuyaSessionExpired(error)) {
setBindingSessionExpired(true)
setBindingConfirmOpen(false)
message.warning('虎牙登录会话已过期,请重新登录')
return
}
message.error(error instanceof Error ? error.message : '提交换绑失败')
} finally {
setBindingLoading(false)
}
}
async function handleSyncBindingProfile() {
if (!selectedTask) return
const comparison = bindingInfo?.comparison
if (!comparison) return
const roleName = comparison.boundRoleName
const roleId = comparison.boundRoleId
const serverZone = comparison.boundZone
if (!roleName || !roleId || !/^\d+$/.test(roleId) || !serverZone) {
message.warning('平台角色信息不完整,请点「修改资料」手动填写')
return
}
setProfileSaving(true)
try {
const response = await saveCustomerTaskProfile(orderNo, selectedTask.id, {
roleName,
roleId,
serverZone,
})
setTasks((current) =>
current.map((task) => (task.id === response.data.task.id ? response.data.task : task)),
)
const bindingResponse = await pollCustomerBinding(orderNo, selectedTask.id)
if (bindingResponse.data.binding) setBindingInfo(bindingResponse.data.binding)
message.success('资料已按平台角色同步,请核对后确认绑定')
} catch (error) {
message.error(error instanceof Error ? error.message : '同步角色资料失败')
} finally {
setProfileSaving(false)
}
}
async function handleConfirmBinding() { async function handleConfirmBinding() {
if (!selectedTask) return if (!selectedTask) return
setBindingLoading(true) setBindingLoading(true)
@@ -646,10 +727,16 @@ export default function CustomerFulfillmentPage() {
})() })()
const bindingRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || '' const bindingRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || ''
const rebindUnchanged = bindingInfo?.rebindUnchanged === true const rebindUnchanged = bindingInfo?.rebindUnchanged === true
const rebindCooldownDays = Number(bindingInfo?.rebindCooldownDays || 0) const rebindConfirmState = bindingInfo?.rebindConfirmState || 'idle'
const rebindRejected = rebindConfirmState === 'rejected'
const rebindAccepted = rebindConfirmState === 'accepted'
const nextRebindText = bindingInfo?.nextRebindAt const nextRebindText = bindingInfo?.nextRebindAt
? formatAdminDateTime(bindingInfo.nextRebindAt) ? formatAdminDateTime(bindingInfo.nextRebindAt)
: '' : ''
const comparisonMismatch =
selectedTask?.bindingStatus === 'role_ready' &&
!rebindUnchanged &&
bindingComparison?.verdict === 'mismatch'
const showProfileForm = showBindingStage && profileEditing const showProfileForm = showBindingStage && profileEditing
const bindingCustomerReady = Boolean( const bindingCustomerReady = Boolean(
bindingComparison?.customerRoleId || bindingComparison?.customerRoleName, bindingComparison?.customerRoleId || bindingComparison?.customerRoleName,
@@ -990,7 +1077,11 @@ export default function CustomerFulfillmentPage() {
{!bindingSessionExpired ? ( {!bindingSessionExpired ? (
rebindUnchanged ? ( rebindUnchanged ? (
<div className="customer-binding-alert is-warning">换绑未生效,请查看下方原因</div> <div className="customer-binding-alert is-warning">
{rebindRejected
? '虎牙未接受本次换绑,请查看下方原因'
: '换绑未生效,请查看下方原因'}
</div>
) : selectedTask?.bindingStatus === 'role_ready' ? ( ) : selectedTask?.bindingStatus === 'role_ready' ? (
<div className="customer-binding-alert is-info">已识别绑定角色,请核对后确认</div> <div className="customer-binding-alert is-info">已识别绑定角色,请核对后确认</div>
) : selectedTask?.bindingStatus === 'confirmed' || bindingRoleId ? ( ) : selectedTask?.bindingStatus === 'confirmed' || bindingRoleId ? (
@@ -1072,13 +1163,16 @@ export default function CustomerFulfillmentPage() {
<p className="customer-binding-qr-hint">请使用微信APP扫码进行游戏角色绑定</p> <p className="customer-binding-qr-hint">请使用微信APP扫码进行游戏角色绑定</p>
<p className="customer-binding-qr-tip"> <p className="customer-binding-qr-tip">
{selectedTask?.bindingStatus === 'scanned' {selectedTask?.bindingStatus === 'scanned'
? '请在微信中完成角色绑定确认,再点击下方按钮进入下一步' ? rebindAccepted
: '扫码后请在微信确认框中核对目标角色;本活动 7 天内只能换绑 1 次'} ? '已向虎牙提交换绑,正在等待角色生效,请稍候刷新。'
: bindingInfo?.rebindRequested
? '扫码后请在虎牙弹窗中选中目标角色;选好后点下方「已选好角色,提交换绑」。'
: '请在微信中完成角色绑定确认,再点击下方按钮进入下一步。'
: '扫码后请在微信确认框中核对目标角色。'}
</p> </p>
{rebindCooldownDays > 0 ? ( {nextRebindText ? (
<p className="customer-binding-qr-tip"> <p className="customer-binding-qr-tip">
平台提示:预计下次可换绑 本次换绑成功后,下次可换绑:{nextRebindText}。
{nextRebindText ? ` ${nextRebindText}` : '需等待 7 天'};本次扫码可能不会生效。
</p> </p>
) : null} ) : null}
<p className="customer-binding-qr-countdown"> <p className="customer-binding-qr-countdown">
@@ -1094,15 +1188,29 @@ export default function CustomerFulfillmentPage() {
刷新二维码 刷新二维码
</Button> </Button>
</div> </div>
<Button {selectedTask?.bindingStatus === 'scanned' &&
block bindingInfo?.rebindRequested &&
size="large" !rebindAccepted ? (
className="customer-binding-next" <Button
loading={bindingLoading} block
onClick={() => void handlePollBindingNow()} size="large"
> className="customer-binding-next"
已扫码绑定,点击进入下一步 loading={bindingLoading}
</Button> onClick={() => void handleSubmitRebind()}
>
已选好角色,提交换绑
</Button>
) : (
<Button
block
size="large"
className="customer-binding-next"
loading={bindingLoading}
onClick={() => void handlePollBindingNow()}
>
{rebindAccepted ? '刷新绑定状态' : '已扫码绑定,点击进入下一步'}
</Button>
)}
</div> </div>
) : null} ) : null}
@@ -1140,24 +1248,21 @@ export default function CustomerFulfillmentPage() {
<Space direction="vertical" size={12} style={{ width: '100%' }}> <Space direction="vertical" size={12} style={{ width: '100%' }}>
{rebindUnchanged ? ( {rebindUnchanged ? (
<Alert <Alert
type="warning" type={rebindRejected ? 'error' : 'warning'}
showIcon showIcon
message="换绑未生效" message={rebindRejected ? '虎牙未接受本次换绑' : '换绑未生效'}
description={ description={
<Space direction="vertical" size={2}> <Space direction="vertical" size={2}>
<span> <span>
扫码已完成,但平台仍返回原绑定角色: 平台仍返回原绑定角色:
{bindingRoleName || '未识别到角色'} {bindingRoleName || '未识别到角色'}
</span> </span>
{rebindCooldownDays > 0 ? ( {bindingInfo?.rebindConfirmMessage ? (
<span> <span>虎牙原因:{bindingInfo.rebindConfirmMessage}</span>
原因:本活动 7 天内只能换绑 1 次 ) : nextRebindText ? (
{nextRebindText ? `,预计下次可换绑:${nextRebindText}` : ''}。 <span>预计下次可换绑:{nextRebindText}。</span>
</span>
) : ( ) : (
<span> <span>请核对虎牙弹窗中选中的目标角色后重新提交。</span>
请在微信确认框中核对目标角色后重新换绑;如持续失败请联系客服。
</span>
)} )}
</Space> </Space>
} }
@@ -1172,6 +1277,28 @@ export default function CustomerFulfillmentPage() {
.join(' · ')} .join(' · ')}
/> />
)} )}
{comparisonMismatch && bindingComparison ? (
<Alert
type="warning"
showIcon
message="平台识别的角色与已填资料不一致"
description={
<Space direction="vertical" size={2}>
<span>
平台角色:{bindingComparison.boundZone || '区服未知'} ·{' '}
{bindingComparison.boundRoleName || '角色未知'}(ID{' '}
{bindingComparison.boundRoleId || '未知'})
</span>
<span>
已填资料:{bindingComparison.customerZone || '区服未填'} ·{' '}
{bindingComparison.customerRoleName || '角色未填'}(ID{' '}
{bindingComparison.customerRoleId || '未填'})
</span>
<span>三项一致后才能提交确认;可一键同步平台角色。</span>
</Space>
}
/>
) : null}
{!bindingPendingUid && !rebindUnchanged ? ( {!bindingPendingUid && !rebindUnchanged ? (
<Alert <Alert
type="warning" type="warning"
@@ -1187,9 +1314,9 @@ export default function CustomerFulfillmentPage() {
size="large" size="large"
className="customer-binding-confirm" className="customer-binding-confirm"
loading={bindingLoading} loading={bindingLoading}
onClick={() => void handleRefreshBinding(true)} onClick={() => void handleSubmitRebind()}
> >
重新扫码换绑 重新提交换绑
</Button> </Button>
<Button <Button
block block
@@ -1197,9 +1324,31 @@ export default function CustomerFulfillmentPage() {
className="customer-binding-rebind" className="customer-binding-rebind"
icon={<ReloadOutlined />} icon={<ReloadOutlined />}
loading={bindingLoading} loading={bindingLoading}
onClick={() => void handlePollBindingNow()} onClick={() => void handleRefreshBinding(true)}
> >
刷新绑定状态 重新扫码换绑
</Button>
</div>
) : comparisonMismatch ? (
<div className="customer-binding-role-actions">
<Button
block
size="large"
className="customer-binding-confirm"
loading={profileSaving}
onClick={() => void handleSyncBindingProfile()}
>
同步平台角色并继续
</Button>
<Button
block
size="large"
className="customer-binding-rebind"
icon={<ExclamationCircleOutlined />}
loading={bindingLoading}
onClick={() => void handleRefreshBinding(true)}
>
角色不对,重新扫码换绑
</Button> </Button>
</div> </div>
) : ( ) : (
@@ -66,6 +66,13 @@ export function confirmCustomerBinding(orderNo: string, taskId: number) {
) )
} }
export function submitCustomerRebind(orderNo: string, taskId: number) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/rebind`,
{},
)
}
type CustomerHuyaChallengeBase = { type CustomerHuyaChallengeBase = {
image: string image: string
width: number width: number
@@ -2,8 +2,10 @@ export type CustomerBindingComparison = {
verdict: 'match' | 'mismatch' | 'unknown' verdict: 'match' | 'mismatch' | 'unknown'
customerRoleName: string customerRoleName: string
customerRoleId: string customerRoleId: string
customerZone: string
boundRoleName: string boundRoleName: string
boundRoleId: string boundRoleId: string
boundZone: string
message: string message: string
} }
@@ -58,6 +60,8 @@ export type CustomerBindingInfo = {
hasExistingBinding: boolean hasExistingBinding: boolean
rebindRequested: boolean rebindRequested: boolean
rebindUnchanged: boolean rebindUnchanged: boolean
rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected'
rebindConfirmMessage: string
rebindCooldownDays: number rebindCooldownDays: number
nextRebindAt: string nextRebindAt: string
platformChangeBindDay?: number platformChangeBindDay?: number