feat(半自动履约): 补齐微博游戏角色绑定流程
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { buildServerZone, compareBindingIdentity, resolveServerZone } from './binding-identity.js'
|
||||
import { getAccountBindingPolicy } from './platform-policy.js'
|
||||
|
||||
test('平台能力声明统一描述角色查询、确认与换绑方式', () => {
|
||||
const huya = getAccountBindingPolicy('huya')
|
||||
assert.equal(huya.bindingKind, 'game_role')
|
||||
assert.equal(huya.queryOwner, 'order_site')
|
||||
assert.equal(huya.confirmationMode, 'customer_match')
|
||||
assert.equal(huya.rebindMode, 'platform_confirm')
|
||||
|
||||
const douyu = getAccountBindingPolicy('douyu')
|
||||
assert.equal(douyu.bindingKind, 'game_role')
|
||||
assert.equal(douyu.queryOwner, 'live_hub')
|
||||
assert.deepEqual(douyu.requiredFields, ['roleName', 'serverZone'])
|
||||
|
||||
const weibo = getAccountBindingPolicy('weibo')
|
||||
assert.equal(weibo.bindingKind, 'game_role')
|
||||
assert.equal(weibo.bindingRequired, true)
|
||||
assert.equal(weibo.requiresCustomerProfile, false)
|
||||
assert.equal(weibo.confirmationMode, 'platform_verified')
|
||||
assert.equal(weibo.rebindMode, 'rescan_qr')
|
||||
assert.deepEqual(weibo.requiredFields, ['roleName'])
|
||||
})
|
||||
|
||||
test('区服规范化为同一口径', () => {
|
||||
assert.equal(resolveServerZone('苹果(iOS) · QQ'), '苹果Q区')
|
||||
assert.equal(resolveServerZone('微信 安卓(android)'), '安卓V区')
|
||||
assert.equal(buildServerZone('ios', 'wechat'), '苹果V区')
|
||||
assert.equal(buildServerZone('android', 'qq'), '安卓Q区')
|
||||
})
|
||||
|
||||
test('公共身份比对明确区分 match、mismatch 与 unknown', () => {
|
||||
const fields = ['roleName', 'roleId', 'serverZone'] as const
|
||||
assert.equal(
|
||||
compareBindingIdentity({
|
||||
requiredFields: fields,
|
||||
customer: { roleName: '角色 A', roleId: '1001', serverZone: '安卓Q区' },
|
||||
platform: { roleName: '角色A', roleId: '1001', serverZone: '安卓Q区' },
|
||||
}).verdict,
|
||||
'match',
|
||||
)
|
||||
assert.equal(
|
||||
compareBindingIdentity({
|
||||
requiredFields: fields,
|
||||
customer: { roleName: '角色A', roleId: '1001', serverZone: '安卓Q区' },
|
||||
platform: { roleName: '角色B', roleId: '1001', serverZone: '安卓Q区' },
|
||||
}).verdict,
|
||||
'mismatch',
|
||||
)
|
||||
assert.equal(
|
||||
compareBindingIdentity({
|
||||
requiredFields: fields,
|
||||
customer: { roleName: '角色A', roleId: '', serverZone: '安卓Q区' },
|
||||
platform: { roleName: '角色A', roleId: '1001', serverZone: '安卓Q区' },
|
||||
}).verdict,
|
||||
'unknown',
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { AccountBindingField } from './platform-policy.js'
|
||||
|
||||
export type BindingFieldValues = Partial<Record<AccountBindingField, string>>
|
||||
|
||||
export type BindingIdentityComparison = {
|
||||
verdict: 'match' | 'mismatch' | 'unknown'
|
||||
missing: AccountBindingField[]
|
||||
mismatched: AccountBindingField[]
|
||||
customer: BindingFieldValues
|
||||
platform: BindingFieldValues
|
||||
}
|
||||
|
||||
export function normalizeBindingRoleName(value: unknown) {
|
||||
return String(value ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
export function normalizeBindingField(field: AccountBindingField, value: unknown): string {
|
||||
const text = String(value ?? '').trim()
|
||||
if (field === 'roleName') return normalizeBindingRoleName(text)
|
||||
return text.toLowerCase()
|
||||
}
|
||||
|
||||
export function resolveServerZone(input: unknown) {
|
||||
const text = String(input ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
if (!text) return ''
|
||||
const system = /苹果|ios/.test(text) ? '苹果' : /安卓|android/.test(text) ? '安卓' : ''
|
||||
const login = /qq|q区|手q/.test(text) ? 'Q' : /微信|wechat|v区/.test(text) ? 'V' : ''
|
||||
return system && login ? `${system}${login}区` : ''
|
||||
}
|
||||
|
||||
export function buildServerZone(system: unknown, loginChannel: unknown) {
|
||||
const systemText = String(system ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
const loginText = String(loginChannel ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
return resolveServerZone(`${systemText} ${loginText}`)
|
||||
}
|
||||
|
||||
export function compareBindingIdentity(input: {
|
||||
requiredFields: readonly AccountBindingField[]
|
||||
customer: BindingFieldValues
|
||||
platform: BindingFieldValues
|
||||
}): BindingIdentityComparison {
|
||||
const missing: AccountBindingField[] = []
|
||||
const mismatched: AccountBindingField[] = []
|
||||
for (const field of input.requiredFields) {
|
||||
const customer = normalizeBindingField(field, input.customer[field])
|
||||
const platform = normalizeBindingField(field, input.platform[field])
|
||||
if (!customer || !platform) {
|
||||
missing.push(field)
|
||||
continue
|
||||
}
|
||||
if (customer !== platform) mismatched.push(field)
|
||||
}
|
||||
return {
|
||||
verdict: missing.length > 0 ? 'unknown' : mismatched.length > 0 ? 'mismatch' : 'match',
|
||||
missing,
|
||||
mismatched,
|
||||
customer: input.customer,
|
||||
platform: input.platform,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
export type AccountBindingPlatform = 'huya' | 'douyu' | 'weibo'
|
||||
export type AccountBindingQueryOwner = 'order_site' | 'live_hub'
|
||||
export type AccountBindingKind = 'game_role' | 'account_authorization'
|
||||
export type AccountBindingField = 'roleName' | 'roleId' | 'serverZone' | 'loginChannel'
|
||||
export type AccountBindingConfirmationMode = 'customer_match' | 'platform_verified'
|
||||
export type AccountBindingRebindMode = 'platform_confirm' | 'rescan_qr'
|
||||
|
||||
export type AccountBindingPolicy = {
|
||||
platform: AccountBindingPlatform
|
||||
platformLabel: string
|
||||
bindingKind: AccountBindingKind
|
||||
bindingRequired: boolean
|
||||
requiresCustomerProfile: boolean
|
||||
supportsRebind: boolean
|
||||
queryOwner: AccountBindingQueryOwner
|
||||
requiredFields: readonly AccountBindingField[]
|
||||
confirmationMode: AccountBindingConfirmationMode
|
||||
rebindMode: AccountBindingRebindMode
|
||||
defaultTargetUrl: string
|
||||
}
|
||||
|
||||
const POLICIES: Record<AccountBindingPlatform, AccountBindingPolicy> = {
|
||||
huya: {
|
||||
platform: 'huya',
|
||||
platformLabel: '虎牙',
|
||||
bindingKind: 'game_role',
|
||||
bindingRequired: true,
|
||||
requiresCustomerProfile: true,
|
||||
supportsRebind: true,
|
||||
queryOwner: 'order_site',
|
||||
requiredFields: ['roleName', 'roleId', 'serverZone'],
|
||||
confirmationMode: 'customer_match',
|
||||
rebindMode: 'platform_confirm',
|
||||
defaultTargetUrl: 'https://www.huya.com/',
|
||||
},
|
||||
douyu: {
|
||||
platform: 'douyu',
|
||||
platformLabel: '斗鱼',
|
||||
bindingKind: 'game_role',
|
||||
bindingRequired: true,
|
||||
requiresCustomerProfile: true,
|
||||
supportsRebind: true,
|
||||
queryOwner: 'live_hub',
|
||||
requiredFields: ['roleName', 'serverZone'],
|
||||
confirmationMode: 'customer_match',
|
||||
rebindMode: 'platform_confirm',
|
||||
defaultTargetUrl: 'https://www.douyu.com/',
|
||||
},
|
||||
weibo: {
|
||||
platform: 'weibo',
|
||||
platformLabel: '微博',
|
||||
bindingKind: 'game_role',
|
||||
bindingRequired: true,
|
||||
requiresCustomerProfile: false,
|
||||
supportsRebind: true,
|
||||
queryOwner: 'order_site',
|
||||
requiredFields: ['roleName'],
|
||||
confirmationMode: 'platform_verified',
|
||||
rebindMode: 'rescan_qr',
|
||||
defaultTargetUrl: 'https://weibo.com/',
|
||||
},
|
||||
}
|
||||
|
||||
export function getAccountBindingPolicy(platform: AccountBindingPlatform) {
|
||||
return POLICIES[platform]
|
||||
}
|
||||
@@ -364,14 +364,14 @@ export async function createSemiAutoMock(
|
||||
const connectorMode =
|
||||
platform === 'weibo' ? 'embedded' : normalizeMockSemiAutoConnectorMode(input.connectorMode)
|
||||
const pageTitle = String(
|
||||
input.pageTitle || (platform === 'weibo' ? '微博发帖授权测试' : '虎牙账号授权测试'),
|
||||
input.pageTitle || (platform === 'weibo' ? '微博角色绑定测试' : '虎牙账号授权测试'),
|
||||
)
|
||||
.trim()
|
||||
.slice(0, 60)
|
||||
const pageDescription = String(
|
||||
input.pageDescription ||
|
||||
(platform === 'weibo'
|
||||
? '开发 Mock:完成微博登录即视为授权,客服在后台完成发帖履约。'
|
||||
? '开发 Mock:完成微博登录并绑定游戏角色后,客服在后台完成履约。'
|
||||
: '开发 Mock:完成登录和角色绑定后,客服在后台完成履约。'),
|
||||
)
|
||||
.trim()
|
||||
@@ -532,7 +532,7 @@ export async function createSemiAutoMock(
|
||||
'完成履约仍走真实确认流程,会写入成本快照和财务确认。',
|
||||
'微博使用内置 Connector:短信验证码会真实发送到客户手机号;扫码登录需在微博 App 中确认。',
|
||||
'后台领取任务后生成 weibo-ticket-* 浏览器票据,扩展消费票据后写入微博 Cookie。',
|
||||
'微博登录成功即视为授权完成,任务会直接进入等待客服处理。',
|
||||
'微博登录后读取平台游戏角色;未绑定时需客户微信/QQ 扫码,绑定确认后才进入等待客服处理。',
|
||||
]
|
||||
: [
|
||||
'完成履约仍走真实确认流程,会写入成本快照和财务确认。',
|
||||
@@ -791,7 +791,7 @@ export async function createSemiAutoIntegrationMock(
|
||||
const shopId = 'dev-integration-shop'
|
||||
const externalSkuCode = `INTEGRATION-${suffix}`
|
||||
const pageTitle = String(
|
||||
input.pageTitle || (platform === 'weibo' ? '微博账号登录授权' : '虎牙账号登录授权'),
|
||||
input.pageTitle || (platform === 'weibo' ? '微博账号登录与角色绑定' : '虎牙账号登录授权'),
|
||||
)
|
||||
.trim()
|
||||
.slice(0, 60)
|
||||
|
||||
@@ -5,6 +5,12 @@ import { publishRealtimeEvent } from '../realtime/realtime-event-service.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
import {
|
||||
buildServerZone,
|
||||
compareBindingIdentity,
|
||||
resolveServerZone,
|
||||
} from '../account-binding/binding-identity.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
|
||||
type DouyuTaskRow = {
|
||||
id: number
|
||||
@@ -358,33 +364,32 @@ async function loadTask(taskId: number) {
|
||||
return task
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown) {
|
||||
return String(value || '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
export function compareCustomerRole(task: DouyuTaskRow, live: LiveBindingState) {
|
||||
const comparison = compareBindingIdentity({
|
||||
requiredFields: getAccountBindingPolicy('douyu').requiredFields,
|
||||
customer: {
|
||||
roleName: task.customer_role_name,
|
||||
serverZone: buildServerZone(task.customer_system, task.customer_platform),
|
||||
},
|
||||
platform: {
|
||||
roleName: live.roleName,
|
||||
serverZone: resolveServerZone(`${live.areaName} ${live.platName}`),
|
||||
},
|
||||
})
|
||||
const roleMatched =
|
||||
Boolean(task.customer_role_name && live.roleName) &&
|
||||
normalizeText(task.customer_role_name) === normalizeText(live.roleName)
|
||||
const liveParts = new Set([normalizeText(live.areaName), normalizeText(live.platName)])
|
||||
const expected: string[] = []
|
||||
if (task.customer_platform === 'wechat') expected.push('微信')
|
||||
if (task.customer_platform === 'qq') expected.push('qq', '手q')
|
||||
if (task.customer_system === 'ios') expected.push('苹果', 'ios')
|
||||
if (task.customer_system === 'android') expected.push('安卓', 'android')
|
||||
const channelMatched = expected.every((item) =>
|
||||
[...liveParts].some((part) => part.includes(item) || item.includes(part)),
|
||||
)
|
||||
!comparison.missing.includes('roleName') && !comparison.mismatched.includes('roleName')
|
||||
const channelMatched =
|
||||
!comparison.missing.includes('serverZone') && !comparison.mismatched.includes('serverZone')
|
||||
return {
|
||||
matched: roleMatched && channelMatched,
|
||||
matched: comparison.verdict === 'match',
|
||||
roleMatched,
|
||||
channelMatched,
|
||||
message:
|
||||
roleMatched && channelMatched
|
||||
comparison.verdict === 'match'
|
||||
? '客户资料与平台识别角色一致'
|
||||
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
|
||||
: comparison.verdict === 'unknown'
|
||||
? '客户资料或平台角色信息不完整,请修改资料或联系客服'
|
||||
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from './weibo-connector-client.js'
|
||||
import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
compareBindingRole,
|
||||
@@ -252,9 +253,7 @@ export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
|
||||
).trim()
|
||||
const targetUrl = /^https:\/\//i.test(configuredTarget)
|
||||
? configuredTarget
|
||||
: credential.platform === 'weibo'
|
||||
? 'https://weibo.com/'
|
||||
: 'https://www.huya.com/'
|
||||
: getAccountBindingPolicy(credential.platform).defaultTargetUrl
|
||||
const cookieHeader = targetUrl
|
||||
? buildSemiAutoCredentialCookieHeader(credential.cookies, targetUrl)
|
||||
: ''
|
||||
@@ -357,8 +356,10 @@ export async function reconcileSemiAutoTaskStates(limitInput = 100) {
|
||||
task = await loadTask(task.id)
|
||||
updated += 1
|
||||
}
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
bindingPolicy.bindingRequired &&
|
||||
bindingPolicy.queryOwner === 'order_site' &&
|
||||
task.login_status === 'authenticated' &&
|
||||
['qr_pending', 'scanned', 'role_ready'].includes(task.binding_status)
|
||||
) {
|
||||
|
||||
@@ -21,8 +21,10 @@ import {
|
||||
loginWeiboSms,
|
||||
revokeWeiboSession,
|
||||
sendWeiboSmsCode,
|
||||
startWeiboBinding,
|
||||
} from './weibo-connector-client.js'
|
||||
import { upsertSemiAutoCredentialWithClient } from './semi-auto-credential-service.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
assertCustomerProfileReady,
|
||||
@@ -42,6 +44,7 @@ import {
|
||||
normalizeId,
|
||||
normalizeOrderNo,
|
||||
publishSemiAutoTaskRealtimeChange,
|
||||
resetTaskForInvalidCredential,
|
||||
resetTaskForCustomerLogin,
|
||||
revokeSessionForTask,
|
||||
TASK_SELECT,
|
||||
@@ -137,7 +140,8 @@ export async function savePublicTaskProfile(
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
if (task.platform !== 'huya') {
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
if (!bindingPolicy.requiresCustomerProfile) {
|
||||
throw createHttpError('当前平台不需要填写游戏角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_not_supported',
|
||||
@@ -224,6 +228,24 @@ function mapLoginUpdate(session: ConnectorLoginSession) {
|
||||
}
|
||||
}
|
||||
|
||||
async function syncWeiboBindingSnapshot(
|
||||
task: TaskRow,
|
||||
sessionId: string,
|
||||
actorType: TaskActorType,
|
||||
) {
|
||||
try {
|
||||
const binding = await getWeiboBinding(sessionId, task.connector_mode)
|
||||
await updateBindingTask(task, binding, actorType)
|
||||
return null
|
||||
} catch (error) {
|
||||
const resetTask = await resetTaskForInvalidCredential(task, error)
|
||||
if (resetTask) {
|
||||
return resetTask
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateLoginTask(
|
||||
task: TaskRow,
|
||||
session: ConnectorLoginSession,
|
||||
@@ -248,10 +270,11 @@ export async function updateLoginTask(
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return
|
||||
}
|
||||
// 虎牙登录成功还不算授权完成,必须等客户确认绑定角色;微博登录即授权。
|
||||
// 登录成功只代表拿到账号 CK;必须等平台角色绑定事实确认后才进入客服处理。
|
||||
const nextExecutionStatus: ExecutionStatus =
|
||||
mapped.status === 'authenticated'
|
||||
? current.platform === 'weibo' || current.binding_status === 'confirmed'
|
||||
? !getAccountBindingPolicy(current.platform).bindingRequired ||
|
||||
current.binding_status === 'confirmed'
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
: current.execution_status
|
||||
@@ -305,6 +328,13 @@ export async function updateLoginTask(
|
||||
})
|
||||
}
|
||||
})
|
||||
if (mapped.status === 'authenticated' && task.platform === 'weibo') {
|
||||
const resetTask = await syncWeiboBindingSnapshot(task, session.sessionId, actorType)
|
||||
if (resetTask) {
|
||||
publishSemiAutoTaskRealtimeChange(resetTask.id, resetTask.order_id)
|
||||
return
|
||||
}
|
||||
}
|
||||
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
|
||||
}
|
||||
|
||||
@@ -429,11 +459,11 @@ export async function pollPublicLogin(orderNoInput: unknown, taskIdInput: unknow
|
||||
export async function startPublicBinding(
|
||||
orderNoInput: unknown,
|
||||
taskIdInput: unknown,
|
||||
input: { forceRebind?: unknown } = {},
|
||||
input: { forceRebind?: unknown; channel?: unknown } = {},
|
||||
) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能重新绑定', {
|
||||
statusCode: 409,
|
||||
@@ -447,12 +477,21 @@ export async function startPublicBinding(
|
||||
})
|
||||
}
|
||||
assertCustomerProfileReady(task)
|
||||
const session =
|
||||
task.platform === 'weibo'
|
||||
? await getWeiboBinding(task.connector_session_id, task.connector_mode)
|
||||
: await startHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
forceRebind: input.forceRebind === true,
|
||||
})
|
||||
let session: ConnectorBindingSession
|
||||
try {
|
||||
session =
|
||||
task.platform === 'weibo'
|
||||
? await startWeiboBinding(task.connector_session_id, task.connector_mode, {
|
||||
channel: input.channel === 'qq' ? 'qq' : 'wx',
|
||||
forceRebind: input.forceRebind === true,
|
||||
})
|
||||
: await startHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
forceRebind: input.forceRebind === true,
|
||||
})
|
||||
} catch (error) {
|
||||
await resetTaskForInvalidCredential(task, error)
|
||||
throw error
|
||||
}
|
||||
const binding = await updateBindingTask(task, session, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
@@ -466,7 +505,12 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
if (task.platform !== 'huya') {
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
if (
|
||||
!bindingPolicy.supportsRebind ||
|
||||
bindingPolicy.confirmationMode !== 'customer_match' ||
|
||||
bindingPolicy.rebindMode !== 'platform_confirm'
|
||||
) {
|
||||
throw createHttpError('当前平台不需要重置绑定状态', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_reset_not_supported',
|
||||
@@ -551,14 +595,21 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unknown) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
return { task: mapTask(task), binding: null }
|
||||
}
|
||||
if (!task.connector_session_id || task.login_status !== 'authenticated') {
|
||||
return { task: mapTask(task), binding: null }
|
||||
}
|
||||
const session = await getBindingForTask(task, task.connector_session_id)
|
||||
let session: ConnectorBindingSession
|
||||
try {
|
||||
session = await getBindingForTask(task, task.connector_session_id)
|
||||
} catch (error) {
|
||||
const resetTask = await resetTaskForInvalidCredential(task, error)
|
||||
if (resetTask) return { task: mapTask(resetTask), binding: null }
|
||||
throw error
|
||||
}
|
||||
const binding = await updateBindingTask(task, session, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
@@ -571,7 +622,14 @@ export async function confirmPublicBinding(
|
||||
) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
if (bindingPolicy.confirmationMode !== 'customer_match') {
|
||||
throw createHttpError('当前平台由平台事实直接确认绑定,无需客户提交', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_confirm_not_supported',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能确认绑定', {
|
||||
statusCode: 409,
|
||||
@@ -580,7 +638,7 @@ export async function confirmPublicBinding(
|
||||
}
|
||||
if (
|
||||
!task.connector_session_id ||
|
||||
(task.platform !== 'weibo' && task.binding_status !== 'role_ready')
|
||||
(bindingPolicy.bindingRequired && task.binding_status !== 'role_ready')
|
||||
) {
|
||||
throw createHttpError('当前没有待确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
@@ -590,7 +648,7 @@ export async function confirmPublicBinding(
|
||||
assertCustomerProfileReady(task)
|
||||
// 确认绑定是纯本地动作:虎牙侧只读内存快照,不再触发角色查询或换绑提交。
|
||||
const session =
|
||||
task.platform === 'huya'
|
||||
bindingPolicy.bindingRequired && bindingPolicy.queryOwner === 'order_site'
|
||||
? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode)
|
||||
: await getBindingForTask(task, task.connector_session_id)
|
||||
const comparison = compareBindingRole(task, session)
|
||||
@@ -644,13 +702,19 @@ export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unk
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能提交换绑', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (task.platform !== 'huya') {
|
||||
if (
|
||||
!bindingPolicy.supportsRebind ||
|
||||
bindingPolicy.confirmationMode !== 'customer_match' ||
|
||||
bindingPolicy.rebindMode !== 'platform_confirm' ||
|
||||
bindingPolicy.queryOwner !== 'order_site'
|
||||
) {
|
||||
throw createHttpError('当前平台不需要换绑游戏角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_rebind_not_supported',
|
||||
@@ -975,7 +1039,7 @@ export async function loginPublicWeiboSms(
|
||||
})
|
||||
}
|
||||
|
||||
const nextExecutionStatus: ExecutionStatus = 'waiting_operator'
|
||||
const nextExecutionStatus: ExecutionStatus = 'waiting_customer'
|
||||
await withTransaction(async (client) => {
|
||||
const credentialId = storedCredential
|
||||
? await upsertSemiAutoCredentialWithClient(client, {
|
||||
@@ -990,7 +1054,7 @@ export async function loginPublicWeiboSms(
|
||||
SET connector_session_id = $2,
|
||||
credential_id = COALESCE($5, credential_id),
|
||||
login_status = 'authenticated',
|
||||
execution_status = 'waiting_operator',
|
||||
execution_status = $6,
|
||||
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
|
||||
auth_started_at = COALESCE(auth_started_at, NOW()),
|
||||
@@ -999,7 +1063,7 @@ export async function loginPublicWeiboSms(
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, sessionId, mapped.uid, mapped.nickname, credentialId],
|
||||
[task.id, sessionId, mapped.uid, mapped.nickname, credentialId, nextExecutionStatus],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
@@ -1015,6 +1079,13 @@ export async function loginPublicWeiboSms(
|
||||
if (previousSessionId && previousSessionId !== sessionId) {
|
||||
await revokeWeiboSession(previousSessionId, task.connector_mode).catch(() => undefined)
|
||||
}
|
||||
const resetTask = await syncWeiboBindingSnapshot(task, sessionId, 'customer')
|
||||
if (resetTask) {
|
||||
throw createHttpError('微博登录状态已失效,请重新登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_credential_invalid',
|
||||
})
|
||||
}
|
||||
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
|
||||
const updated = await loadTask(task.id)
|
||||
return {
|
||||
|
||||
@@ -63,6 +63,8 @@ import {
|
||||
} from './semi-auto-credential-service.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import { isNumericBindingRoleId } from './binding-role-id.js'
|
||||
import { compareBindingIdentity, resolveServerZone } from '../account-binding/binding-identity.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
|
||||
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
|
||||
const ADMIN_LIST_BACKFILL_INTERVAL_MS = 15_000
|
||||
@@ -227,6 +229,7 @@ export function hasCustomerProfile(
|
||||
}
|
||||
|
||||
export function displayStatus(task: TaskRow) {
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
const status = (
|
||||
key: string,
|
||||
label: string,
|
||||
@@ -249,11 +252,11 @@ export function displayStatus(task: TaskRow) {
|
||||
return status('processing', '处理中', 'operator', '客服继续履约')
|
||||
}
|
||||
if (task.login_status === 'authenticated') {
|
||||
// 虎牙需要客户确认绑定角色后才算授权完成;微博登录即授权。
|
||||
if (task.platform === 'weibo' || task.binding_status === 'confirmed') {
|
||||
// 微博和虎牙都必须在平台侧完成角色绑定后才能进入客服处理。
|
||||
if (!bindingPolicy.bindingRequired || task.binding_status === 'confirmed') {
|
||||
return status('waiting_operator', '等待客服处理', 'operator', '客服领取并履约')
|
||||
}
|
||||
if (task.platform === 'huya' && !hasCustomerProfile(task)) {
|
||||
if (bindingPolicy.requiresCustomerProfile && !hasCustomerProfile(task)) {
|
||||
return status('waiting_profile', '待客户填写资料', 'customer', '客户填写区服、编号和角色名')
|
||||
}
|
||||
if (task.binding_status === 'role_ready') {
|
||||
@@ -277,14 +280,24 @@ export function displayStatus(task: TaskRow) {
|
||||
}
|
||||
|
||||
export function mapTask(task: TaskRow) {
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
return {
|
||||
id: Number(task.id),
|
||||
orderId: Number(task.order_id),
|
||||
orderItemId: Number(task.order_item_id),
|
||||
fulfillmentId: task.fulfillment_id ? Number(task.fulfillment_id) : null,
|
||||
platform: task.platform,
|
||||
platformLabel:
|
||||
task.platform === 'huya' ? '虎牙' : task.platform === 'weibo' ? '微博' : task.platform,
|
||||
platformLabel: bindingPolicy.platformLabel,
|
||||
bindingPolicy: {
|
||||
bindingKind: bindingPolicy.bindingKind,
|
||||
bindingRequired: bindingPolicy.bindingRequired,
|
||||
requiresCustomerProfile: bindingPolicy.requiresCustomerProfile,
|
||||
supportsRebind: bindingPolicy.supportsRebind,
|
||||
queryOwner: bindingPolicy.queryOwner,
|
||||
requiredFields: bindingPolicy.requiredFields,
|
||||
confirmationMode: bindingPolicy.confirmationMode,
|
||||
rebindMode: bindingPolicy.rebindMode,
|
||||
},
|
||||
loginStatus: task.login_status,
|
||||
bindingStatus: task.binding_status,
|
||||
executionStatus: task.execution_status,
|
||||
@@ -489,7 +502,7 @@ export function assertHuyaTask(task: TaskRow) {
|
||||
* 进入绑定/确认/换绑前必须已有完整三项资料。
|
||||
*/
|
||||
export function assertCustomerProfileReady(task: TaskRow) {
|
||||
if (task.platform !== 'huya') return
|
||||
if (!getAccountBindingPolicy(task.platform).requiresCustomerProfile) return
|
||||
if (!hasCustomerProfile(task)) {
|
||||
throw createHttpError('请先提交游戏角色资料', {
|
||||
statusCode: 409,
|
||||
@@ -603,6 +616,22 @@ export async function resetTaskForCustomerLogin(
|
||||
return loadTask(task.id)
|
||||
}
|
||||
|
||||
export async function resetTaskForInvalidCredential(task: TaskRow, error: unknown) {
|
||||
if (task.platform !== 'weibo' || !isInvalidCredentialError(error)) return null
|
||||
await markSemiAutoCredentialCheck(task.credential_id, {
|
||||
status: 'invalid',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}).catch(() => undefined)
|
||||
if (task.connector_session_id) {
|
||||
await revokeSessionForTask(task, task.connector_session_id).catch(() => undefined)
|
||||
}
|
||||
return resetTaskForCustomerLogin(task, {
|
||||
actorType: 'connector',
|
||||
reason: '微博登录凭证已失效,需客户重新登录',
|
||||
eventType: 'credential_invalidated',
|
||||
})
|
||||
}
|
||||
|
||||
export async function ensureConnectorSessionForTask(task: TaskRow): Promise<TaskRow> {
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') return task
|
||||
if (task.connector_session_id) {
|
||||
@@ -835,38 +864,12 @@ export type BindingRoleComparison = {
|
||||
message: string
|
||||
}
|
||||
|
||||
function normalizeRoleText(value: unknown): string {
|
||||
return String(value ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
function normalizeServerZone(value: unknown): string {
|
||||
const text = String(value ?? '').trim()
|
||||
|
||||
if (!text) return ''
|
||||
|
||||
return /区$/.test(text) ? text : `${text}区`
|
||||
}
|
||||
|
||||
/**
|
||||
* 从虎牙渠道串解析区服,例如「安卓(android) · 微信」→ 安卓V区。
|
||||
* 解析不出平台或登录方式时返回空串,比对时按「平台区服缺失」处理(判 unknown)。
|
||||
*/
|
||||
export function detectServerZone(channel: unknown): string {
|
||||
const text = String(channel ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
|
||||
if (!text) return ''
|
||||
|
||||
const platform = /苹果|ios/.test(text) ? '苹果' : /安卓|android/.test(text) ? '安卓' : ''
|
||||
|
||||
if (!platform) return ''
|
||||
|
||||
const login = /qq|q区/.test(text) ? 'Q' : /微信|wechat|v区/.test(text) ? 'V' : ''
|
||||
|
||||
return login ? `${platform}${login}区` : ''
|
||||
return resolveServerZone(channel)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -888,7 +891,7 @@ export function compareBindingRole(
|
||||
): BindingRoleComparison {
|
||||
const customerRoleName = String(task.customer_game_role || '').trim()
|
||||
const customerRoleId = String(task.customer_game_id || '').trim()
|
||||
const customerZone = normalizeServerZone(task.customer_game_server_zone)
|
||||
const customerZone = resolveServerZone(task.customer_game_server_zone)
|
||||
const boundRoleName = String(binding.bindGameRole || '').trim()
|
||||
const rawBoundRoleId = String(binding.bindGameRoleId || '').trim()
|
||||
// 虎牙 gameRole.roleId 是 40 位加密串,客户填写的是数值游戏编号;
|
||||
@@ -909,34 +912,43 @@ export function compareBindingRole(
|
||||
boundZone,
|
||||
}
|
||||
|
||||
// 客户确认的口径:区服、角色名、角色 ID 三项必须全部存在且一致。
|
||||
const missing: string[] = []
|
||||
if (!customerRoleId) missing.push('客户游戏编号')
|
||||
if (!customerRoleName) missing.push('客户角色名')
|
||||
if (!customerZone) missing.push('客户区服')
|
||||
if (!boundRoleId || !isNumericBindingRoleId(boundRoleId)) missing.push('平台可核对角色ID')
|
||||
if (!boundRoleName) missing.push('平台角色名')
|
||||
if (!boundZone) missing.push('平台区服')
|
||||
if (missing.length > 0) {
|
||||
const verifiedBoundRoleId = isNumericBindingRoleId(boundRoleId) ? boundRoleId : ''
|
||||
const comparison = compareBindingIdentity({
|
||||
requiredFields: getAccountBindingPolicy('huya').requiredFields,
|
||||
customer: {
|
||||
roleName: customerRoleName,
|
||||
roleId: customerRoleId,
|
||||
serverZone: customerZone,
|
||||
},
|
||||
platform: {
|
||||
roleName: boundRoleName,
|
||||
roleId: verifiedBoundRoleId,
|
||||
serverZone: boundZone,
|
||||
},
|
||||
})
|
||||
if (comparison.verdict === 'unknown') {
|
||||
const missing: string[] = []
|
||||
if (!customerRoleId) missing.push('客户游戏编号')
|
||||
if (!customerRoleName) missing.push('客户角色名')
|
||||
if (!customerZone) missing.push('客户区服')
|
||||
if (!verifiedBoundRoleId) missing.push('平台可核对角色ID')
|
||||
if (!boundRoleName) missing.push('平台角色名')
|
||||
if (!boundZone) missing.push('平台区服')
|
||||
return {
|
||||
...base,
|
||||
verdict: 'unknown',
|
||||
message: `缺少${missing.join('、')},无法核对绑定角色,请联系客服`,
|
||||
}
|
||||
}
|
||||
|
||||
if (customerRoleId !== boundRoleId) {
|
||||
if (comparison.mismatched.includes('roleId')) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法提交平台绑定' }
|
||||
}
|
||||
|
||||
if (normalizeRoleText(customerRoleName) !== normalizeRoleText(boundRoleName)) {
|
||||
if (comparison.mismatched.includes('roleName')) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法提交平台绑定' }
|
||||
}
|
||||
|
||||
if (customerZone !== boundZone) {
|
||||
if (comparison.mismatched.includes('serverZone')) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧区服不一致,无法提交平台绑定' }
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
verdict: 'match',
|
||||
@@ -986,10 +998,24 @@ export async function updateBindingTask(
|
||||
const mapped = mapBindingUpdate(session)
|
||||
const roleIdVerified = isNumericBindingRoleId(mapped.bindGameRoleId)
|
||||
const requiresSupport =
|
||||
(Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) && !roleIdVerified
|
||||
getAccountBindingPolicy(task.platform).requiresCustomerProfile &&
|
||||
(Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) &&
|
||||
!roleIdVerified
|
||||
const comparison = await withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, task.id)
|
||||
const currentComparison = compareBindingRole(current, mapped)
|
||||
const bindingPolicy = getAccountBindingPolicy(current.platform)
|
||||
const currentComparison: BindingRoleComparison = bindingPolicy.requiresCustomerProfile
|
||||
? compareBindingRole(current, mapped)
|
||||
: {
|
||||
verdict: 'match',
|
||||
customerRoleName: '',
|
||||
customerRoleId: '',
|
||||
customerZone: '',
|
||||
boundRoleName: mapped.bindGameRole,
|
||||
boundRoleId: mapped.bindGameRoleId,
|
||||
boundZone: mapped.bindGameChannel,
|
||||
message: '平台角色绑定状态已确认',
|
||||
}
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return currentComparison
|
||||
}
|
||||
@@ -1003,6 +1029,7 @@ export async function updateBindingTask(
|
||||
bind_game_role = CASE WHEN $4 <> '' THEN $4 ELSE bind_game_role END,
|
||||
bind_game_role_id = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_id END,
|
||||
bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END,
|
||||
binding_started_at = CASE WHEN $2 = 'qr_pending' THEN COALESCE(binding_started_at, NOW()) ELSE binding_started_at END,
|
||||
bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END,
|
||||
execution_status = $6,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $7 ELSE '' END,
|
||||
|
||||
@@ -748,6 +748,104 @@ test(
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'微博平台角色绑定事实收敛为等待客服处理',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
process.env.ENABLE_DEV_MOCK = '1'
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const { createSemiAutoIntegrationMock } = await import('../dev-mock/dev-mock-service.js')
|
||||
const { loadTask, updateBindingTask } = await import('./semi-auto-task-core.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const orderNo = `IT-WEIBO-BINDING-${suffix}`
|
||||
let orderId = 0
|
||||
let configId = 0
|
||||
let mappingId = 0
|
||||
try {
|
||||
const result = await createSemiAutoIntegrationMock({
|
||||
platform: 'weibo',
|
||||
orderNo,
|
||||
skuName: `微博绑定真实链路-${suffix}`,
|
||||
quantity: 1,
|
||||
connectorMode: 'embedded',
|
||||
})
|
||||
orderId = result.orderId
|
||||
configId = result.configId
|
||||
mappingId = result.mappingId
|
||||
assert.equal(result.semiAutoPlatform, 'weibo')
|
||||
assert.ok(result.taskId > 0)
|
||||
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'authenticated',
|
||||
execution_status = 'waiting_customer',
|
||||
authenticated_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[result.taskId, `it-weibo-session-${suffix}`],
|
||||
)
|
||||
const task = await loadTask(result.taskId)
|
||||
const binding = await updateBindingTask(
|
||||
task,
|
||||
{
|
||||
sessionId: `it-weibo-session-${suffix}`,
|
||||
status: 'confirmed',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
bindGameAccount: '集成测试微博',
|
||||
bindGameRole: '微博游戏角色',
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: '微信',
|
||||
hasExistingBinding: true,
|
||||
rebindRequested: false,
|
||||
rebindCooldownDays: 0,
|
||||
nextRebindAt: '',
|
||||
message: '微博账号已绑定角色',
|
||||
},
|
||||
'connector',
|
||||
)
|
||||
|
||||
assert.equal(binding.status, 'confirmed')
|
||||
assert.equal(binding.comparison.verdict, 'match')
|
||||
const stored = await query<{
|
||||
binding_status: string
|
||||
execution_status: string
|
||||
bind_game_role: string
|
||||
bind_game_channel: string
|
||||
}>(
|
||||
`SELECT binding_status, execution_status, bind_game_role, bind_game_channel
|
||||
FROM semi_auto_tasks WHERE id = $1`,
|
||||
[result.taskId],
|
||||
)
|
||||
assert.equal(stored.rows[0]?.binding_status, 'confirmed')
|
||||
assert.equal(stored.rows[0]?.execution_status, 'waiting_operator')
|
||||
assert.equal(stored.rows[0]?.bind_game_role, '微博游戏角色')
|
||||
assert.equal(stored.rows[0]?.bind_game_channel, '微信')
|
||||
} finally {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query("SET LOCAL session_replication_role = 'replica'")
|
||||
if (configId > 0) {
|
||||
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
||||
}
|
||||
if (orderId > 0) {
|
||||
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
}
|
||||
if (mappingId > 0) {
|
||||
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
|
||||
}
|
||||
})
|
||||
delete process.env.ENABLE_DEV_MOCK
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'开发 Mock 可显式选择内置 Mock Connector',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
|
||||
@@ -111,6 +111,15 @@ export async function getWeiboBinding(
|
||||
return weiboNativeConnector.getBinding(sessionId)
|
||||
}
|
||||
|
||||
export async function startWeiboBinding(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = 'embedded',
|
||||
options: { channel?: 'wx' | 'qq'; forceRebind?: boolean } = {},
|
||||
): Promise<ConnectorBindingSession> {
|
||||
assertEmbedded(mode)
|
||||
return weiboNativeConnector.startBinding(sessionId, options)
|
||||
}
|
||||
|
||||
export async function createWeiboBrowserTicket(
|
||||
input: { sessionId: string; targetUrl?: string },
|
||||
mode: SemiAutoConnectorMode = 'embedded',
|
||||
|
||||
@@ -24,6 +24,8 @@ import type {
|
||||
|
||||
const PASSPORT_BASE = 'https://passport.weibo.com'
|
||||
const WEIBO_BASE = 'https://weibo.com'
|
||||
const WEIBO_VIPCLUB_HOME = 'https://vipclub.e.weibo.com/aj/mall/home'
|
||||
const WEIBO_LIVELINK_QRCODE = 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode'
|
||||
const WEIBO_RETURN_URL = 'https://weibo.com/'
|
||||
const WEIBO_LOGIN_URL =
|
||||
`https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0` +
|
||||
@@ -35,6 +37,9 @@ const SIGNIN_REFERER =
|
||||
const PC_UA =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' +
|
||||
'Chrome/155.0.0.0 Safari/537.36'
|
||||
const WEIBO_MOBILE_UA =
|
||||
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) ' +
|
||||
'AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Weibo'
|
||||
|
||||
const LOGIN_QR_TTL_MS = 5 * 60 * 1000
|
||||
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
|
||||
@@ -43,6 +48,8 @@ const SMS_COOKIE_TTL_MS = 10 * 60 * 1000
|
||||
const COUNTRY_CODE_TTL_MS = 60 * 60 * 1000
|
||||
const MAX_SESSIONS = 200
|
||||
const TICKET_PREFIX = 'weibo-ticket-'
|
||||
const WEIBO_BINDING_QR_TTL_MS = 10 * 60 * 1000
|
||||
const WEIBO_AUTH_ERROR_CODES = new Set([100002, 100004, 400000, 400002])
|
||||
export const WEIBO_YIDUN_CAPTCHA_ID = '7cda0ba2785647ada4d6e946ddb2d465'
|
||||
|
||||
export type WeiboCountryCode = {
|
||||
@@ -93,6 +100,29 @@ type WeiboAccount = {
|
||||
avatar: string
|
||||
}
|
||||
|
||||
type WeiboGameRole = {
|
||||
isBound: boolean
|
||||
roleName: string
|
||||
canRebind: boolean
|
||||
rebindRemainDays: number
|
||||
bindUrl: string
|
||||
}
|
||||
|
||||
type WeiboGameRoleError = {
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
type WeiboBindingQrState = {
|
||||
channel: 'wx' | 'qq'
|
||||
qrImage: string
|
||||
qrUrl: string
|
||||
token: string
|
||||
expiresAtMs: number
|
||||
rebindRequested: boolean
|
||||
baselineRoleName: string
|
||||
}
|
||||
|
||||
type WeiboTicket = {
|
||||
ticket: string
|
||||
targetUrl: string
|
||||
@@ -307,6 +337,10 @@ type WeiboSession = {
|
||||
message: string
|
||||
cookies: WeiboCookieJar
|
||||
account: WeiboAccount | null
|
||||
gameRole: WeiboGameRole | null
|
||||
gameRoleError: WeiboGameRoleError | null
|
||||
bindingQr: WeiboBindingQrState | null
|
||||
lastBindingChannel: 'wx' | 'qq' | ''
|
||||
tickets: Map<string, WeiboTicket>
|
||||
}
|
||||
|
||||
@@ -343,6 +377,55 @@ function iso(value: number): string {
|
||||
return new Date(value).toISOString()
|
||||
}
|
||||
|
||||
function weiboErrorCode(error: unknown): string {
|
||||
return error && typeof error === 'object'
|
||||
? String((error as { errorCode?: unknown }).errorCode || '').trim()
|
||||
: ''
|
||||
}
|
||||
|
||||
export function extractWeiboBindRawUrl(bindUrlInput: unknown): string {
|
||||
const bindUrl = String(bindUrlInput || '').trim()
|
||||
if (!bindUrl) {
|
||||
throw createHttpError('微博未返回角色绑定链接', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_bind_url_missing',
|
||||
})
|
||||
}
|
||||
let path = ''
|
||||
try {
|
||||
path = new URL(bindUrl).searchParams.get('path') || ''
|
||||
} catch {
|
||||
throw createHttpError('微博角色绑定链接格式错误', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
const marker = '/pages/gameAccountBind/index?'
|
||||
const markerIndex = path.indexOf(marker)
|
||||
if (markerIndex < 0) {
|
||||
throw createHttpError('微博角色绑定链接缺少绑定页面参数', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
const rawUrl = path.slice(markerIndex + marker.length)
|
||||
if (!rawUrl) {
|
||||
throw createHttpError('微博角色绑定链接参数为空', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
return rawUrl
|
||||
}
|
||||
|
||||
function weiboBindQrImageSrc(value: unknown): string {
|
||||
const text = String(value || '').trim()
|
||||
if (!text) return ''
|
||||
if (/^(https?:\/\/|data:image\/)/i.test(text)) return text
|
||||
const mime = text.startsWith('iVBOR') ? 'image/png' : 'image/jpeg'
|
||||
return `data:${mime};base64,${text}`
|
||||
}
|
||||
|
||||
function readSetCookie(headers: Headers): string[] {
|
||||
const withGetSetCookie = headers as Headers & { getSetCookie?: () => string[] }
|
||||
if (typeof withGetSetCookie.getSetCookie === 'function') {
|
||||
@@ -412,6 +495,10 @@ export class WeiboNativeConnector {
|
||||
message: '请使用微博 App 扫码登录',
|
||||
cookies,
|
||||
account: null,
|
||||
gameRole: null,
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
@@ -703,6 +790,10 @@ export class WeiboNativeConnector {
|
||||
message: '微博登录成功',
|
||||
cookies: state.cookies,
|
||||
account: null,
|
||||
gameRole: null,
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.smsSessions.delete(stateKey)
|
||||
@@ -719,6 +810,67 @@ export class WeiboNativeConnector {
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
try {
|
||||
await this.refreshGameRole(session)
|
||||
} catch (error) {
|
||||
if (weiboErrorCode(error) === 'weibo_credential_invalid') throw error
|
||||
return this.bindingView(session)
|
||||
}
|
||||
const role = session.gameRole
|
||||
const qr = session.bindingQr
|
||||
if (role?.isBound && qr && (!qr.rebindRequested || role.roleName !== qr.baselineRoleName)) {
|
||||
session.bindingQr = null
|
||||
}
|
||||
return this.bindingView(session)
|
||||
}
|
||||
|
||||
async startBinding(
|
||||
sessionId: string,
|
||||
options: { channel?: 'wx' | 'qq'; forceRebind?: boolean } = {},
|
||||
): Promise<ConnectorBindingSession> {
|
||||
const session = this.requireSession(sessionId)
|
||||
if (session.status !== 'authenticated' || !session.account) {
|
||||
throw createHttpError('微博账号尚未登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
const channel = options.channel === 'qq' ? 'qq' : 'wx'
|
||||
const role = await this.refreshGameRole(session)
|
||||
if (role.isBound && !role.canRebind) {
|
||||
session.bindingQr = null
|
||||
const wait = role.rebindRemainDays > 0 ? `,还需等待 ${role.rebindRemainDays} 天` : ''
|
||||
throw createHttpError(
|
||||
`微博账号已绑定角色${role.roleName ? `「${role.roleName}」` : ''},当前不可换绑${wait}`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_rebind_cooldown',
|
||||
},
|
||||
)
|
||||
}
|
||||
if (role.isBound && options.forceRebind !== true) {
|
||||
session.bindingQr = null
|
||||
return this.bindingView(session)
|
||||
}
|
||||
if (!role.bindUrl) {
|
||||
throw createHttpError('微博没有返回当前账号的角色绑定链接', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_bind_url_missing',
|
||||
})
|
||||
}
|
||||
const qr = await this.generateBindQr(role.bindUrl, channel)
|
||||
const nowMs = this.now()
|
||||
session.bindingQr = {
|
||||
channel,
|
||||
qrImage: qr.image,
|
||||
qrUrl: '',
|
||||
token: qr.token,
|
||||
expiresAtMs: nowMs + WEIBO_BINDING_QR_TTL_MS,
|
||||
rebindRequested: role.isBound,
|
||||
baselineRoleName: role.roleName,
|
||||
}
|
||||
session.lastBindingChannel = channel
|
||||
session.message = '请使用微信或 QQ 扫码完成微博游戏角色绑定'
|
||||
return this.bindingView(session)
|
||||
}
|
||||
|
||||
@@ -845,6 +997,10 @@ export class WeiboNativeConnector {
|
||||
...account,
|
||||
nickname: account.nickname || String(input.nickname || ''),
|
||||
},
|
||||
gameRole: null,
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(session.sessionId, session)
|
||||
@@ -885,6 +1041,15 @@ export class WeiboNativeConnector {
|
||||
}
|
||||
session.status = 'authenticated'
|
||||
session.message = '微博登录成功'
|
||||
await this.refreshGameRole(session).catch((error) => {
|
||||
session.gameRoleError = {
|
||||
code: weiboErrorCode(error) || 'weibo_game_role_query_failed',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
logWarn('[weibo/game-role]', '登录后读取微博角色绑定状态失败', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
private async followWithCookies(
|
||||
@@ -917,6 +1082,134 @@ export class WeiboNativeConnector {
|
||||
return { finalUrl: currentUrl, body }
|
||||
}
|
||||
|
||||
private async refreshGameRole(session: WeiboSession): Promise<WeiboGameRole> {
|
||||
if (session.status !== 'authenticated' || !session.account?.uid) {
|
||||
throw createHttpError('微博账号尚未登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
try {
|
||||
const url = `${WEIBO_VIPCLUB_HOME}?F=&_t=${this.now()}`
|
||||
const response = await this.fetchImpl(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'user-agent': WEIBO_MOBILE_UA,
|
||||
accept: 'application/json, text/plain, */*',
|
||||
referer: 'https://vipclub.e.weibo.com/game/homepage',
|
||||
cookie: session.cookies.headerFor('https://vipclub.e.weibo.com/'),
|
||||
},
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
session.cookies.addFromResponse(response.headers, response.url || url)
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
code?: number
|
||||
msg?: string
|
||||
data?: {
|
||||
game_role?: {
|
||||
is_bound?: boolean
|
||||
role_name?: string
|
||||
can_rebind?: boolean
|
||||
rebind_remain_days?: number
|
||||
bind_url?: string
|
||||
}
|
||||
}
|
||||
} | null
|
||||
if (!response.ok) {
|
||||
throw createHttpError(`微博角色信息查询失败:HTTP ${response.status}`, {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_game_role_query_failed',
|
||||
})
|
||||
}
|
||||
const code = Number(payload?.code)
|
||||
if (WEIBO_AUTH_ERROR_CODES.has(code)) {
|
||||
throw createHttpError(payload?.msg || '微博 CK 已失效,请重新登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_credential_invalid',
|
||||
})
|
||||
}
|
||||
if (!payload || code !== 100000) {
|
||||
throw createHttpError(payload?.msg || '微博角色信息查询失败', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_game_role_query_failed',
|
||||
})
|
||||
}
|
||||
const role = payload.data?.game_role || {}
|
||||
const gameRole: WeiboGameRole = {
|
||||
isBound: role.is_bound === true,
|
||||
roleName: String(role.role_name || '').trim(),
|
||||
canRebind: role.can_rebind === true,
|
||||
rebindRemainDays: Math.max(0, Math.trunc(Number(role.rebind_remain_days) || 0)),
|
||||
bindUrl: String(role.bind_url || '').trim(),
|
||||
}
|
||||
session.gameRole = gameRole
|
||||
session.gameRoleError = null
|
||||
return gameRole
|
||||
} catch (error) {
|
||||
session.gameRoleError = {
|
||||
code: weiboErrorCode(error) || 'weibo_game_role_query_failed',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async generateBindQr(
|
||||
bindUrl: string,
|
||||
channel: 'wx' | 'qq',
|
||||
): Promise<{ image: string; token: string }> {
|
||||
const rawUrl = extractWeiboBindRawUrl(bindUrl)
|
||||
const query = new URLSearchParams(rawUrl)
|
||||
const livePlatId = String(query.get('livePlatId') || '')
|
||||
const actId = String(query.get('actId') || '')
|
||||
const fromId = String(query.get('fromId') || '').slice(0, 32)
|
||||
if (!livePlatId || !actId) {
|
||||
throw createHttpError('微博绑定链接缺少活动参数', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
const suffix = crypto.randomBytes(4).toString('hex')
|
||||
const response = await this.fetchImpl(WEIBO_LIVELINK_QRCODE, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json;charset=UTF-8',
|
||||
accept: 'application/json, text/plain, */*',
|
||||
origin: 'https://livelink.qq.com',
|
||||
referer: 'https://livelink.qq.com/',
|
||||
'gap-plat-id': livePlatId,
|
||||
'gap-act-id': actId,
|
||||
'gap-user-from': 'pc',
|
||||
'gap-from-id': fromId,
|
||||
'vulcan-acctype': 'auth_in_h5',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
queryString: `${rawUrl}&sessionId=${Date.now()}_${suffix}`,
|
||||
accountType: channel,
|
||||
}),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
iRet?: number
|
||||
sMsg?: string
|
||||
jData?: { qrcode?: string; qrcodeToken?: string }
|
||||
} | null
|
||||
if (!response.ok || Number(payload?.iRet) !== 0) {
|
||||
throw createHttpError(payload?.sMsg || '微博绑定二维码生成失败', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_qrcode_failed',
|
||||
})
|
||||
}
|
||||
const image = weiboBindQrImageSrc(payload?.jData?.qrcode)
|
||||
if (!image) {
|
||||
throw createHttpError('微博绑定接口没有返回二维码', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_qrcode_failed',
|
||||
})
|
||||
}
|
||||
return { image, token: String(payload?.jData?.qrcodeToken || '') }
|
||||
}
|
||||
|
||||
private async fetchHomePage(cookies: WeiboCookieJar): Promise<{ status: number; body: string }> {
|
||||
try {
|
||||
const response = await this.fetchImpl(`${WEIBO_BASE}/`, {
|
||||
@@ -1071,19 +1364,48 @@ export class WeiboNativeConnector {
|
||||
|
||||
private bindingView(session: WeiboSession): ConnectorBindingSession {
|
||||
const account = session.account
|
||||
const role = session.gameRole
|
||||
const qr = session.bindingQr
|
||||
const qrActive = Boolean(qr && qr.expiresAtMs > this.now())
|
||||
const status: ConnectorBindingSession['status'] = session.gameRoleError
|
||||
? 'failed'
|
||||
: qrActive
|
||||
? 'qr_pending'
|
||||
: qr
|
||||
? 'expired'
|
||||
: role?.isBound
|
||||
? 'confirmed'
|
||||
: 'not_started'
|
||||
const cooldownDays = role?.isBound && !role.canRebind ? Math.max(0, role.rebindRemainDays) : 0
|
||||
const channel = qr?.channel || session.lastBindingChannel
|
||||
const channelLabel = channel === 'qq' ? 'QQ' : channel === 'wx' ? '微信' : '微博'
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
status: 'confirmed',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
status,
|
||||
qrImage: qrActive ? qr?.qrImage || '' : '',
|
||||
qrExpiresAt: qrActive ? iso(Number(qr?.expiresAtMs || 0)) : '',
|
||||
qrUrl: qrActive ? qr?.qrUrl || '' : '',
|
||||
bindGameAccount: account?.nickname || '',
|
||||
bindGameRole: account?.uid || '',
|
||||
bindGameRoleId: account?.uid || '',
|
||||
bindGameChannel: '微博',
|
||||
hasExistingBinding: true,
|
||||
rebindRequested: false,
|
||||
message: '微博账号已授权',
|
||||
bindGameRole: role?.roleName || '',
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: channelLabel,
|
||||
hasExistingBinding: role?.isBound === true,
|
||||
rebindRequested: qr?.rebindRequested === true,
|
||||
rebindCooldownDays: cooldownDays,
|
||||
nextRebindAt: cooldownDays > 0 ? iso(this.now() + cooldownDays * 24 * 60 * 60 * 1000) : '',
|
||||
message: session.gameRoleError
|
||||
? session.gameRoleError.message
|
||||
: qrActive
|
||||
? qr?.rebindRequested
|
||||
? '请扫码选择新的微博游戏角色'
|
||||
: '请扫码完成微博游戏角色绑定'
|
||||
: status === 'expired'
|
||||
? '微博绑定二维码已过期,请重新获取'
|
||||
: status === 'confirmed'
|
||||
? `微博账号已绑定角色${role?.roleName ? `「${role.roleName}」` : ''}`
|
||||
: role
|
||||
? '微博账号尚未绑定游戏角色'
|
||||
: session.message || '微博角色绑定状态尚未就绪',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { WEIBO_TICKET_PREFIX, WeiboNativeConnector } from './weibo-native-connector.js'
|
||||
import {
|
||||
extractWeiboBindRawUrl,
|
||||
WEIBO_TICKET_PREFIX,
|
||||
WeiboNativeConnector,
|
||||
} from './weibo-native-connector.js'
|
||||
|
||||
type CapturedCall = { url: string; init: RequestInit }
|
||||
|
||||
const BIND_URL =
|
||||
'sinaweibo://wbdiversion?username=gh_test&path=%2Fpages%2FgameAccountBind%2Findex' +
|
||||
'%3FactId%3D16722%26code%3Dabc%252Bdef%253D%26gameId%3Dcjm' +
|
||||
'%26livePlatId%3Dweiyouxi%26nonce%3Dabc123%26sig%3D0123456789abcdef' +
|
||||
'%26t%3D1794046086%26v%3D2.0'
|
||||
|
||||
function jsonResponse(payload: unknown): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status: 200,
|
||||
@@ -129,9 +139,209 @@ function defaultHandler(url: string): Response {
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse({
|
||||
code: 100000,
|
||||
msg: 'success',
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: false,
|
||||
role_name: '',
|
||||
can_rebind: true,
|
||||
rebind_remain_days: 0,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode') {
|
||||
return jsonResponse({
|
||||
iRet: 0,
|
||||
sMsg: 'ok',
|
||||
jData: {
|
||||
qrcode: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB',
|
||||
qrcodeToken: 'bind-token-1',
|
||||
},
|
||||
})
|
||||
}
|
||||
return new Response('not found', { status: 404 })
|
||||
}
|
||||
|
||||
async function loginWeiboSession(connector: WeiboNativeConnector) {
|
||||
await connector.sendSmsCode({ taskId: 1, mobile: '13800138000' })
|
||||
const { sessionId } = await connector.loginWithSms({
|
||||
taskId: 1,
|
||||
orderNo: 'MOCKWB1',
|
||||
mobile: '13800138000',
|
||||
code: '123456',
|
||||
})
|
||||
return sessionId
|
||||
}
|
||||
|
||||
test('微博 bind_url 提取保留内层编码并拒绝错误路径', () => {
|
||||
const raw = extractWeiboBindRawUrl(BIND_URL)
|
||||
assert.ok(raw.startsWith('actId=16722&code=abc%2Bdef%3D'))
|
||||
assert.equal(raw.includes('abc+def='), false)
|
||||
assert.throws(
|
||||
() => extractWeiboBindRawUrl('sinaweibo://wbdiversion?path=%2Fwrong'),
|
||||
(error: { errorCode?: string }) => error.errorCode === 'weibo_bind_url_invalid',
|
||||
)
|
||||
})
|
||||
|
||||
test('微博未绑定角色时可生成微信和 QQ 绑定二维码', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
const wxBinding = await connector.startBinding(sessionId, { channel: 'wx' })
|
||||
assert.equal(wxBinding.status, 'qr_pending')
|
||||
assert.equal(wxBinding.bindGameChannel, '微信')
|
||||
assert.match(wxBinding.qrImage, /^data:image\/png;base64,/)
|
||||
|
||||
const qqBinding = await connector.startBinding(sessionId, { channel: 'qq' })
|
||||
assert.equal(qqBinding.status, 'qr_pending')
|
||||
assert.equal(qqBinding.bindGameChannel, 'QQ')
|
||||
|
||||
const qrCalls = calls.filter(
|
||||
(call) => call.url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode',
|
||||
)
|
||||
assert.equal(qrCalls.length, 2)
|
||||
const wxBody = JSON.parse(String(qrCalls[0]?.init.body)) as {
|
||||
accountType: string
|
||||
queryString: string
|
||||
}
|
||||
const qqHeaders = qrCalls[1]?.init.headers as Record<string, string>
|
||||
assert.equal(wxBody.accountType, 'wx')
|
||||
assert.ok(wxBody.queryString.startsWith(`${extractWeiboBindRawUrl(BIND_URL)}&sessionId=`))
|
||||
assert.equal(qqHeaders['gap-act-id'], '16722')
|
||||
assert.equal(qqHeaders['gap-plat-id'], 'weiyouxi')
|
||||
assert.equal(qqHeaders['vulcan-acctype'], 'auth_in_h5')
|
||||
})
|
||||
|
||||
test('微博已绑定且不可换绑时返回冷却期错误', async () => {
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse({
|
||||
code: 100000,
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: true,
|
||||
role_name: '已有角色',
|
||||
can_rebind: false,
|
||||
rebind_remain_days: 7,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
await assert.rejects(
|
||||
() => connector.startBinding(sessionId, { channel: 'wx', forceRebind: true }),
|
||||
(error: { errorCode?: string; message?: string }) => {
|
||||
assert.equal(error.errorCode, 'weibo_rebind_cooldown')
|
||||
assert.match(error.message || '', /还需等待 7 天/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test('微博已有角色时默认直接确认,强制换绑后按新角色名确认', async () => {
|
||||
let roleName = '旧角色'
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse({
|
||||
code: 100000,
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: true,
|
||||
role_name: roleName,
|
||||
can_rebind: true,
|
||||
rebind_remain_days: 0,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
const existing = await connector.startBinding(sessionId, { channel: 'wx' })
|
||||
assert.equal(existing.status, 'confirmed')
|
||||
assert.equal(existing.bindGameRole, '旧角色')
|
||||
|
||||
const rebind = await connector.startBinding(sessionId, {
|
||||
channel: 'qq',
|
||||
forceRebind: true,
|
||||
})
|
||||
assert.equal(rebind.status, 'qr_pending')
|
||||
assert.equal(rebind.rebindRequested, true)
|
||||
|
||||
roleName = '新角色'
|
||||
const confirmed = await connector.getBinding(sessionId)
|
||||
assert.equal(confirmed.status, 'confirmed')
|
||||
assert.equal(confirmed.bindGameRole, '新角色')
|
||||
assert.equal(confirmed.qrImage, '')
|
||||
})
|
||||
|
||||
test('微博角色查询遇到 CK 失效时向服务层抛出凭证错误', async () => {
|
||||
let expired = false
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse(
|
||||
expired
|
||||
? { code: 400002, msg: '未登陆' }
|
||||
: {
|
||||
code: 100000,
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: false,
|
||||
role_name: '',
|
||||
can_rebind: true,
|
||||
rebind_remain_days: 0,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
expired = true
|
||||
|
||||
await assert.rejects(
|
||||
() => connector.getBinding(sessionId),
|
||||
(error: { errorCode?: string }) => error.errorCode === 'weibo_credential_invalid',
|
||||
)
|
||||
})
|
||||
|
||||
test('微博来联二维码失败时不生成虚假绑定状态', async () => {
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode') {
|
||||
return jsonResponse({ iRet: -1, sMsg: '刷新二维码频率过快,请间隔5秒后重试' })
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
await assert.rejects(
|
||||
() => connector.startBinding(sessionId, { channel: 'wx' }),
|
||||
(error: { errorCode?: string; message?: string }) => {
|
||||
assert.equal(error.errorCode, 'weibo_bind_qrcode_failed')
|
||||
assert.match(error.message || '', /间隔5秒/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test('微博二维码会话解析 qrid 并把图片转成 base64', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
|
||||
@@ -260,10 +260,8 @@ export default function SemiAutoTaskHistoryDrawer({
|
||||
label: '绑定状态',
|
||||
children: (
|
||||
<Tag color={bindingTagColor(history.task.bindingStatus)}>
|
||||
{history.task.platform === 'weibo'
|
||||
? '登录即授权'
|
||||
: BINDING_STATUS_LABELS[history.task.bindingStatus] ||
|
||||
history.task.bindingStatus}
|
||||
{BINDING_STATUS_LABELS[history.task.bindingStatus] ||
|
||||
history.task.bindingStatus}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -939,11 +939,11 @@ function SemiAutoMockForm({
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'huya', label: '虎牙(扫码登录 + 游戏角色绑定)' },
|
||||
{ value: 'weibo', label: '微博(短信 / 扫码登录,登录即授权)' },
|
||||
{ value: 'weibo', label: '微博(短信 / 扫码登录 + 游戏角色绑定)' },
|
||||
]}
|
||||
onChange={(value: 'huya' | 'weibo') => {
|
||||
form.setFieldsValue({
|
||||
pageTitle: value === 'weibo' ? '微博发帖授权测试' : '虎牙账号授权测试',
|
||||
pageTitle: value === 'weibo' ? '微博角色绑定测试' : '虎牙账号授权测试',
|
||||
browserTargetUrl: value === 'weibo' ? 'https://weibo.com/' : 'https://www.huya.com/',
|
||||
...(value === 'weibo' ? { connectorMode: 'embedded' } : {}),
|
||||
})
|
||||
@@ -1049,7 +1049,7 @@ function SemiAutoMockForm({
|
||||
style={{ marginBottom: 12 }}
|
||||
message={
|
||||
selectedPlatform === 'weibo'
|
||||
? '微博使用内置真实 Connector:短信验证码会真实发送到客户手机号,扫码需在微博 App 确认;登录成功即视为授权完成。'
|
||||
? '微博使用内置真实 Connector:短信验证码会真实发送到客户手机号,登录后还需客户通过微信或 QQ 扫码绑定游戏角色。'
|
||||
: selectedMode === 'mock'
|
||||
? integration
|
||||
? '订单和履约链路是正式的,只有登录与 CK 获取使用内置 Mock Connector。'
|
||||
|
||||
@@ -480,11 +480,9 @@ export default function AdminSemiAutoTasksPage() {
|
||||
<Text type="secondary">{task.displayStatus.nextAction}</Text>
|
||||
<Text type="secondary">{task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'}</Text>
|
||||
<Text type="secondary">
|
||||
{task.platform === 'huya'
|
||||
? `绑定:${BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus}`
|
||||
: '微博登录即授权'}
|
||||
{`绑定:${BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus}`}
|
||||
</Text>
|
||||
{task.platform === 'huya' && (task.bindGameRole || task.bindGameRoleId) ? (
|
||||
{task.bindGameRole || task.bindGameRoleId ? (
|
||||
<Text type="secondary">
|
||||
{`角色:${task.bindGameRole || '-'}${task.bindGameRoleId ? `(${task.bindGameRoleId})` : '(无角色ID)'}`}
|
||||
</Text>
|
||||
@@ -769,9 +767,7 @@ export default function AdminSemiAutoTasksPage() {
|
||||
{detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="绑定状态">
|
||||
{detail.task.platform === 'weibo'
|
||||
? '微博登录即授权'
|
||||
: BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus}
|
||||
{BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="平台绑定角色">
|
||||
{detail.task.bindGameRole || '-'}
|
||||
@@ -995,7 +991,7 @@ function taskNeedsCustomerReauth(task: SemiAutoTask) {
|
||||
function taskCanUseCredential(task: SemiAutoTask) {
|
||||
return (
|
||||
task.loginStatus === 'authenticated' &&
|
||||
(task.platform === 'weibo' || task.bindingStatus === 'confirmed') &&
|
||||
(!task.bindingPolicy.bindingRequired || task.bindingStatus === 'confirmed') &&
|
||||
task.credentialReady &&
|
||||
task.credentialStatus !== 'invalid' &&
|
||||
task.credentialStatus !== 'error'
|
||||
|
||||
@@ -92,6 +92,7 @@ export default function CustomerFulfillmentPage({
|
||||
const hydratingBindingRef = useRef(false)
|
||||
const autoOpenedRoleRef = useRef('')
|
||||
const redirectingRef = useRef(false)
|
||||
const weiboBindingSyncRef = useRef(false)
|
||||
// Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。
|
||||
const [bindingSessionExpired, setBindingSessionExpired] = useState(false)
|
||||
const [bindingLoadError, setBindingLoadError] = useState('')
|
||||
@@ -177,6 +178,7 @@ export default function CustomerFulfillmentPage({
|
||||
startingBindingRef.current = false
|
||||
hydratingBindingRef.current = false
|
||||
autoOpenedRoleRef.current = ''
|
||||
weiboBindingSyncRef.current = false
|
||||
setBindingSessionExpired(false)
|
||||
setBindingLoadError('')
|
||||
}, [selectedTask?.id])
|
||||
@@ -302,7 +304,7 @@ export default function CustomerFulfillmentPage({
|
||||
setBindingLoadError('')
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
return
|
||||
}
|
||||
@@ -325,9 +327,15 @@ export default function CustomerFulfillmentPage({
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return
|
||||
if (!selectedTask || !orderNo) return
|
||||
const huyaBinding =
|
||||
selectedTask.platform === 'huya' &&
|
||||
['qr_pending', 'scanned'].includes(selectedTask.bindingStatus)
|
||||
const weiboBinding =
|
||||
selectedTask.platform === 'weibo' &&
|
||||
['qr_pending', 'scanned'].includes(selectedTask.bindingStatus)
|
||||
if (!huyaBinding && !weiboBinding) return
|
||||
if (bindingSessionExpired) return
|
||||
if (!['qr_pending', 'scanned'].includes(selectedTask.bindingStatus)) return
|
||||
const tick = async () => {
|
||||
try {
|
||||
const response = await pollCustomerBinding(orderNo, selectedTask.id)
|
||||
@@ -337,7 +345,7 @@ export default function CustomerFulfillmentPage({
|
||||
if (response.data.binding) setBindingInfo(response.data.binding)
|
||||
setBindingLoadError('')
|
||||
} catch (error) {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
setBindingConfirmOpen(false)
|
||||
return
|
||||
@@ -360,6 +368,34 @@ export default function CustomerFulfillmentPage({
|
||||
selectedTask?.platform,
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedTask || !orderNo || selectedTask.platform !== 'weibo') return
|
||||
if (selectedTask.loginStatus !== 'authenticated') return
|
||||
if (selectedTask.bindingStatus !== 'not_started') return
|
||||
if (bindingInfo || weiboBindingSyncRef.current) return
|
||||
weiboBindingSyncRef.current = true
|
||||
void pollCustomerBinding(orderNo, selectedTask.id)
|
||||
.then((response) => {
|
||||
setTasks((current) =>
|
||||
current.map((task) => (task.id === response.data.task.id ? response.data.task : task)),
|
||||
)
|
||||
if (response.data.binding) setBindingInfo(response.data.binding)
|
||||
})
|
||||
.catch((error) => {
|
||||
setBindingLoadError(error instanceof Error ? error.message : '读取微博角色绑定状态失败')
|
||||
})
|
||||
.finally(() => {
|
||||
weiboBindingSyncRef.current = false
|
||||
})
|
||||
}, [
|
||||
bindingInfo,
|
||||
orderNo,
|
||||
selectedTask?.bindingStatus,
|
||||
selectedTask?.id,
|
||||
selectedTask?.loginStatus,
|
||||
selectedTask?.platform,
|
||||
])
|
||||
|
||||
// 进入 role_ready 时补一次绑定详情,保证确认弹窗能拿到两侧角色 ID。
|
||||
useEffect(() => {
|
||||
if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return
|
||||
@@ -376,7 +412,7 @@ export default function CustomerFulfillmentPage({
|
||||
setBindingLoadError('')
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
return
|
||||
}
|
||||
@@ -536,7 +572,7 @@ export default function CustomerFulfillmentPage({
|
||||
)
|
||||
setLoginInfo(response.data.login)
|
||||
setHuyaChallenge(null)
|
||||
message.success(isWeibo ? '微博登录成功,等待客服处理' : '登录成功,请填写游戏角色资料')
|
||||
message.success(isWeibo ? '微博登录成功,请绑定游戏角色' : '登录成功,请填写游戏角色资料')
|
||||
} catch (error) {
|
||||
const errorCode = (error as { errorCode?: string } | null)?.errorCode || ''
|
||||
if (errorCode === 'weibo_sms_mfa_required') {
|
||||
@@ -582,10 +618,14 @@ export default function CustomerFulfillmentPage({
|
||||
setBindingLoadError('')
|
||||
setBindingConfirmOpen(false)
|
||||
} catch (error) {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
setBindingConfirmOpen(false)
|
||||
message.warning('虎牙登录会话已过期,请重新登录')
|
||||
message.warning(
|
||||
selectedTask.platform === 'weibo'
|
||||
? '微博登录已失效,请重新登录'
|
||||
: '虎牙登录会话已过期,请重新登录',
|
||||
)
|
||||
return
|
||||
}
|
||||
const detail = error instanceof Error ? error.message : '创建绑定二维码失败'
|
||||
@@ -596,6 +636,32 @@ export default function CustomerFulfillmentPage({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStartWeiboBinding(channel: 'wx' | 'qq') {
|
||||
if (!selectedTask) return
|
||||
setBindingLoading(true)
|
||||
try {
|
||||
const response = await startCustomerBinding(orderNo, selectedTask.id, { channel })
|
||||
setTasks((current) =>
|
||||
current.map((task) => (task.id === response.data.task.id ? response.data.task : task)),
|
||||
)
|
||||
setBindingInfo(response.data.binding)
|
||||
setBindingLoadError('')
|
||||
setBindingConfirmOpen(false)
|
||||
} catch (error) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
setBindingConfirmOpen(false)
|
||||
message.warning('微博登录已失效,请重新登录')
|
||||
return
|
||||
}
|
||||
const detail = error instanceof Error ? error.message : '生成微博角色绑定二维码失败'
|
||||
setBindingLoadError(detail)
|
||||
message.error(detail)
|
||||
} finally {
|
||||
setBindingLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 二维码区的刷新/重新获取:换绑流程必须 forceRebind。
|
||||
* 否则后端发现账号已有绑定角色会直接返回已有角色(role_ready),页面看起来像「返回上一步」。
|
||||
@@ -638,7 +704,11 @@ export default function CustomerFulfillmentPage({
|
||||
}
|
||||
if (nextTask.bindingStatus === 'confirmed') {
|
||||
setBindingConfirmOpen(false)
|
||||
message.success('已提交平台绑定,等待客服处理')
|
||||
message.success(
|
||||
selectedTask.platform === 'weibo'
|
||||
? '微博角色已绑定,等待客服处理'
|
||||
: '已提交平台绑定,等待客服处理',
|
||||
)
|
||||
return
|
||||
}
|
||||
// 弹窗内点「刷新」:角色不再是待确认状态时收起弹窗,避免展示过期比对。
|
||||
@@ -653,7 +723,11 @@ export default function CustomerFulfillmentPage({
|
||||
return
|
||||
}
|
||||
if (nextTask.bindingStatus === 'qr_pending') {
|
||||
message.warning('还没有检测到扫码记录,请使用微信扫码完成绑定后再点击')
|
||||
message.warning(
|
||||
`还没有检测到扫码记录,请使用${
|
||||
nextBinding?.bindGameChannel === 'QQ' ? 'QQ' : '微信'
|
||||
}扫码完成绑定后再点击`,
|
||||
)
|
||||
return
|
||||
}
|
||||
if (nextTask.bindingStatus === 'expired') {
|
||||
@@ -666,10 +740,14 @@ export default function CustomerFulfillmentPage({
|
||||
}
|
||||
message.info(detail || '绑定状态还没有更新,请稍后再试')
|
||||
} catch (error) {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
setBindingConfirmOpen(false)
|
||||
message.warning('虎牙登录会话已过期,请重新登录')
|
||||
message.warning(
|
||||
selectedTask.platform === 'weibo'
|
||||
? '微博登录已失效,请重新登录'
|
||||
: '虎牙登录会话已过期,请重新登录',
|
||||
)
|
||||
return
|
||||
}
|
||||
const detail = error instanceof Error ? error.message : '刷新绑定状态失败'
|
||||
@@ -701,7 +779,7 @@ export default function CustomerFulfillmentPage({
|
||||
}
|
||||
message.info('已向虎牙提交换绑,正在等待角色生效')
|
||||
} catch (error) {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
setBindingConfirmOpen(false)
|
||||
message.warning('虎牙登录会话已过期,请重新登录')
|
||||
@@ -727,7 +805,7 @@ export default function CustomerFulfillmentPage({
|
||||
setBindingConfirmOpen(false)
|
||||
message.success('已提交平台绑定,等待客服处理')
|
||||
} catch (error) {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
setBindingConfirmOpen(false)
|
||||
message.warning('虎牙登录会话已过期,请重新登录')
|
||||
@@ -767,7 +845,7 @@ export default function CustomerFulfillmentPage({
|
||||
setBindingLoadError('')
|
||||
message.success('已返回上一步,请修改资料后重新提交')
|
||||
} catch (error) {
|
||||
if (isHuyaSessionExpired(error)) {
|
||||
if (isConnectorSessionExpired(error)) {
|
||||
setBindingSessionExpired(true)
|
||||
} else {
|
||||
// 重置失败不阻断客户改资料,保存后会重新识别平台角色。
|
||||
@@ -840,7 +918,7 @@ export default function CustomerFulfillmentPage({
|
||||
}
|
||||
}
|
||||
|
||||
const displayTitle = isWeibo ? '微博账号登录授权' : '绑定游戏角色'
|
||||
const displayTitle = isWeibo ? '登录并绑定微博游戏角色' : '绑定游戏角色'
|
||||
const loginQrVisible =
|
||||
Boolean(selectedTask) && ['qr_pending', 'scanned'].includes(selectedTask.loginStatus)
|
||||
const showBindingStage = Boolean(
|
||||
@@ -850,6 +928,14 @@ export default function CustomerFulfillmentPage({
|
||||
selectedTask.executionStatus !== 'completed' &&
|
||||
selectedTask.executionStatus !== 'cancelled',
|
||||
)
|
||||
const showWeiboBindingStage = Boolean(
|
||||
selectedTask &&
|
||||
selectedTask.platform === 'weibo' &&
|
||||
selectedTask.loginStatus === 'authenticated' &&
|
||||
selectedTask.bindingStatus !== 'confirmed' &&
|
||||
selectedTask.executionStatus !== 'completed' &&
|
||||
selectedTask.executionStatus !== 'cancelled',
|
||||
)
|
||||
const bindingQrVisible =
|
||||
profileComplete &&
|
||||
['not_started', 'qr_pending', 'scanned'].includes(selectedTask?.bindingStatus || '')
|
||||
@@ -1163,6 +1249,124 @@ export default function CustomerFulfillmentPage({
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{showWeiboBindingStage ? (
|
||||
<section className="customer-binding-stage">
|
||||
<div className="customer-auth-section-heading">
|
||||
<span className="customer-auth-section-icon">
|
||||
<QrcodeOutlined />
|
||||
</span>
|
||||
<div>
|
||||
<h2>绑定微博游戏角色</h2>
|
||||
<p>请选择微信或 QQ,使用对应 App 扫码完成角色绑定。</p>
|
||||
</div>
|
||||
</div>
|
||||
{bindingSessionExpired ? (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message="微博登录已失效"
|
||||
description="请重新登录微博后再绑定游戏角色。"
|
||||
action={
|
||||
<Button size="small" onClick={() => void handleStartLogin()}>
|
||||
重新登录
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{bindingInfo?.bindGameRole ? (
|
||||
<div className="customer-binding-info">
|
||||
<h3>当前绑定角色</h3>
|
||||
<div>
|
||||
<span>角色名</span>
|
||||
<strong>{bindingInfo.bindGameRole}</strong>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{bindingInfo?.qrImage ? (
|
||||
<div className="customer-binding-qr-card">
|
||||
<Image
|
||||
src={bindingInfo.qrImage}
|
||||
alt={`${bindingInfo.bindGameChannel || '微博'}角色绑定二维码`}
|
||||
width={260}
|
||||
preview={false}
|
||||
/>
|
||||
<p className="customer-binding-qr-hint">{bindingInfo.message}</p>
|
||||
<p className="customer-binding-qr-countdown">
|
||||
建议 {formatCountdown(bindingSecondsLeft)} 内完成扫码
|
||||
</p>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
className="customer-binding-next"
|
||||
loading={bindingLoading}
|
||||
onClick={() => void handlePollBindingNow()}
|
||||
>
|
||||
已扫码,刷新绑定状态
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="customer-binding-qr-card">
|
||||
{selectedTask.bindingStatus === 'expired' ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="微博绑定二维码已过期"
|
||||
description="请重新选择微信或 QQ 获取新的绑定二维码。"
|
||||
/>
|
||||
) : null}
|
||||
{bindingLoadError ? (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message={bindingLoadError}
|
||||
description={bindingInfo?.message}
|
||||
/>
|
||||
) : selectedTask.bindingStatus === 'failed' && bindingInfo?.message ? (
|
||||
<Alert type="error" showIcon message={bindingInfo.message} />
|
||||
) : null}
|
||||
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
type="primary"
|
||||
loading={bindingLoading}
|
||||
disabled={bindingSessionExpired}
|
||||
onClick={() => void handleStartWeiboBinding('wx')}
|
||||
>
|
||||
微信绑定
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
loading={bindingLoading}
|
||||
disabled={bindingSessionExpired}
|
||||
onClick={() => void handleStartWeiboBinding('qq')}
|
||||
>
|
||||
QQ 绑定
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
className="customer-binding-rebind"
|
||||
loading={bindingLoading}
|
||||
disabled={bindingSessionExpired}
|
||||
onClick={() => void handlePollBindingNow()}
|
||||
>
|
||||
刷新角色状态
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
{Number(bindingInfo?.rebindCooldownDays || 0) > 0 ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message={`当前角色仍在换绑冷却期,剩余约 ${bindingInfo?.rebindCooldownDays || 0} 天`}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{showBindingStage ? (
|
||||
<section id="customer-binding-stage" className="customer-binding-stage">
|
||||
{profileComplete && !profileEditing ? (
|
||||
@@ -1185,7 +1389,9 @@ export default function CustomerFulfillmentPage({
|
||||
|
||||
{bindingSessionExpired ? (
|
||||
<div className="customer-binding-session-card">
|
||||
<p className="customer-binding-session-title">虎牙登录会话已过期</p>
|
||||
<p className="customer-binding-session-title">
|
||||
{isWeibo ? '微博登录已失效' : '虎牙登录会话已过期'}
|
||||
</p>
|
||||
<p className="customer-binding-session-desc">
|
||||
请返回登录重新扫码,已填写的订单资料和绑定状态不会丢失。
|
||||
</p>
|
||||
@@ -1586,6 +1792,7 @@ export default function CustomerFulfillmentPage({
|
||||
|
||||
{isWeibo &&
|
||||
selectedTask?.loginStatus === 'authenticated' &&
|
||||
selectedTask.bindingStatus === 'confirmed' &&
|
||||
selectedTask.executionStatus !== 'completed' ? (
|
||||
<div className="customer-auth-state is-waiting">
|
||||
<div className="customer-auth-state-icon">
|
||||
@@ -1810,8 +2017,13 @@ function CustomerPrivacyNote() {
|
||||
}
|
||||
|
||||
/** Connector 重启或会话被回收时后端返回该错误码,需要引导客户重新登录。 */
|
||||
function isHuyaSessionExpired(error: unknown) {
|
||||
return (error as { errorCode?: string } | null)?.errorCode === 'huya_native_session_not_found'
|
||||
function isConnectorSessionExpired(error: unknown) {
|
||||
return [
|
||||
'huya_native_session_not_found',
|
||||
'weibo_session_not_found',
|
||||
'weibo_login_required',
|
||||
'weibo_credential_invalid',
|
||||
].includes((error as { errorCode?: string } | null)?.errorCode || '')
|
||||
}
|
||||
|
||||
function isValidMainlandMobile(value: string) {
|
||||
|
||||
@@ -45,11 +45,14 @@ export function pollCustomerLogin(orderNo: string, taskId: number) {
|
||||
export function startCustomerBinding(
|
||||
orderNo: string,
|
||||
taskId: number,
|
||||
options: { forceRebind?: boolean } = {},
|
||||
options: { forceRebind?: boolean; channel?: 'wx' | 'qq' } = {},
|
||||
) {
|
||||
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
|
||||
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/start`,
|
||||
options.forceRebind ? { forceRebind: true } : {},
|
||||
{
|
||||
...(options.forceRebind ? { forceRebind: true } : {}),
|
||||
...(options.channel ? { channel: options.channel } : {}),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
export type SemiAutoPlatform = 'huya' | 'weibo'
|
||||
|
||||
export type SemiAutoBindingPolicy = {
|
||||
bindingKind: 'game_role' | 'account_authorization'
|
||||
bindingRequired: boolean
|
||||
requiresCustomerProfile: boolean
|
||||
supportsRebind: boolean
|
||||
queryOwner: 'order_site' | 'live_hub'
|
||||
requiredFields: Array<'roleName' | 'roleId' | 'serverZone' | 'loginChannel'>
|
||||
confirmationMode: 'customer_match' | 'platform_verified'
|
||||
rebindMode: 'platform_confirm' | 'rescan_qr'
|
||||
}
|
||||
|
||||
export type SemiAutoDisplayStatus = {
|
||||
key: string
|
||||
label: string
|
||||
@@ -14,6 +25,7 @@ export type SemiAutoTask = {
|
||||
fulfillmentId: number | null
|
||||
platform: SemiAutoPlatform
|
||||
platformLabel: string
|
||||
bindingPolicy: SemiAutoBindingPolicy
|
||||
loginStatus: string
|
||||
bindingStatus: string
|
||||
executionStatus: string
|
||||
|
||||
@@ -13,6 +13,16 @@ export type CustomerSemiAutoTask = {
|
||||
id: number
|
||||
platform: 'huya' | 'weibo'
|
||||
platformLabel: string
|
||||
bindingPolicy: {
|
||||
bindingKind: 'game_role' | 'account_authorization'
|
||||
bindingRequired: boolean
|
||||
requiresCustomerProfile: boolean
|
||||
supportsRebind: boolean
|
||||
queryOwner: 'order_site' | 'live_hub'
|
||||
requiredFields: Array<'roleName' | 'roleId' | 'serverZone' | 'loginChannel'>
|
||||
confirmationMode: 'customer_match' | 'platform_verified'
|
||||
rebindMode: 'platform_confirm' | 'rescan_qr'
|
||||
}
|
||||
orderNo: string
|
||||
productName: string
|
||||
skuName: string
|
||||
|
||||
@@ -42,6 +42,25 @@ test('二维码切换与虎牙一致:直接切到扫码并发起登录', () =>
|
||||
assert.ok(source.includes('void handleStartLogin()'))
|
||||
})
|
||||
|
||||
test('微博登录后展示微信/QQ 游戏角色绑定,不再登录即完成', () => {
|
||||
assert.ok(source.includes('const showWeiboBindingStage = Boolean('))
|
||||
assert.ok(source.includes('绑定微博游戏角色'))
|
||||
assert.ok(source.includes('handleStartWeiboBinding'))
|
||||
assert.ok(source.includes('微信绑定'))
|
||||
assert.ok(source.includes('QQ 绑定'))
|
||||
assert.ok(source.includes('微博角色已绑定,等待客服处理'))
|
||||
assert.ok(source.includes("selectedTask.bindingStatus === 'confirmed'"))
|
||||
assert.ok(!source.includes('微博登录即授权'))
|
||||
})
|
||||
|
||||
test('微博绑定轮询与虎牙共用会话恢复和失效重新登录入口', () => {
|
||||
assert.ok(source.includes('const weiboBinding ='))
|
||||
assert.ok(source.includes('pollCustomerBinding(orderNo, selectedTask.id)'))
|
||||
assert.ok(source.includes("'weibo_session_not_found'"))
|
||||
assert.ok(source.includes("'weibo_credential_invalid'"))
|
||||
assert.ok(source.includes('微博登录已失效'))
|
||||
})
|
||||
|
||||
test('微博订单卡只展示订单号/商品/平台/状态,不含游戏和角色名称', () => {
|
||||
const weiboBranch = source.slice(
|
||||
source.indexOf("if (task.platform === 'weibo')"),
|
||||
|
||||
+30
-8
@@ -3,7 +3,7 @@ type: 权威架构与实施计划
|
||||
description: 订单、内部 SKU、履约路由、履约执行、商品、成本与财务的唯一权威口径及重构计划。
|
||||
tags: [订单, 内部SKU, 履约, 商品, 成本, 财务, 迁移]
|
||||
status: authoritative
|
||||
version: 2.25
|
||||
version: 2.27
|
||||
updated_at: 2026-11-18
|
||||
---
|
||||
|
||||
@@ -12,7 +12,7 @@ updated_at: 2026-11-18
|
||||
> 状态:**唯一权威文档**。
|
||||
> 最后校准:2026-11-18。
|
||||
> 生产基线:迁移 `166`。
|
||||
> 开发基线:迁移 `167`(仅本地,尚未部署生产)。
|
||||
> 开发基线:迁移 `170`(仅本地,尚未部署生产)。
|
||||
>
|
||||
> 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现,
|
||||
> 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。
|
||||
@@ -300,8 +300,9 @@ terminal 已退款、退款申请、平台取消或商业订单已关闭
|
||||
manual fulfillment
|
||||
→ semi_auto_tasks
|
||||
→ 客户登录平台并获取账号 CK
|
||||
→ 客户填写游戏角色资料(区服 / 游戏编号 / 角色名)
|
||||
→ 核对并绑定平台角色
|
||||
→ 平台查询游戏角色与绑定事实
|
||||
→ 客户填写或扫码确认目标游戏角色
|
||||
→ 确认平台角色绑定
|
||||
→ 客服使用 CK 在平台侧手动处理
|
||||
→ confirmManualFulfillment
|
||||
```
|
||||
@@ -349,6 +350,15 @@ manual fulfillment
|
||||
浏览器注入只下发与目标 URL 匹配的 Cookie;账号级凭证保存完整集合,以便导出、会话恢复和跨域重放。
|
||||
- 微博手机号登录首次发码返回 `mfa_1` 时,客户必须在浏览器完成网易易盾安全验证,再使用同一会话的
|
||||
`mfa_id` 重发短信;服务端不尝试绕过或伪造人机验证。
|
||||
- 微博客户页流程固定为「登录 → 查询微博游戏角色 → 微信/QQ 扫码绑定 → 客服处理」:
|
||||
① 登录只代表取得账号 CK,不得直接写入“绑定已确认”;
|
||||
② order_site 读取 `https://vipclub.e.weibo.com/aj/mall/home` 的
|
||||
`data.game_role.is_bound / role_name / can_rebind / rebind_remain_days / bind_url`;
|
||||
③ `is_bound = false` 时使用 `bind_url` 通过来联生成微信或 QQ 小程序绑定二维码,
|
||||
`is_bound = true` 且角色名变化后才收敛为 `binding_status = confirmed`;
|
||||
④ 已绑定且 `can_rebind = false` 时不得生成换绑二维码,必须展示冷却剩余天数;
|
||||
⑤ 绑定二维码是 10 分钟短期会话状态,不单独落库;Connector 重启后以账号级 CK 恢复会话并重新查询
|
||||
`game_role`,已绑定事实照常确认,未绑定事实回到重新生成二维码。
|
||||
- 半自动任务通过 `connector_mode` 显式记录 Connector 来源:
|
||||
`embedded` 为 order_site 内置真实实现并作为默认值,`external` 为显式配置的远程真实实现,
|
||||
`mock` 为 order_site 内置开发 Mock 且仅在非生产环境可用。开发 Mock 造单时默认选择 `embedded`,
|
||||
@@ -373,6 +383,15 @@ manual fulfillment
|
||||
事务提交后才执行报表刷新、Connector 会话撤销等旁路动作。
|
||||
- 半自动履约状态采用与斗鱼领取一致的同步原则:客户操作、Connector 回调和后台操作都是状态快照输入,
|
||||
统一由一个状态收敛服务在任务行锁内写入正式字段并追加事件;多个入口不得各自拼接或覆盖状态。
|
||||
- 账号绑定能力由平台声明,不由页面或业务服务按平台散落判断。虎牙、斗鱼、微博均为 `game_role`:
|
||||
虎牙必需字段 `roleName / roleId / serverZone`,由 order_site 查询、客户比对确认和提交换绑;
|
||||
斗鱼必需字段 `roleName / serverZone`,由 live-hub 查询和提交换绑;
|
||||
微博必需字段 `roleName`,由 order_site 查询,微信/QQ 扫码完成绑定或换绑,不要求客户重复填写角色资料。
|
||||
公共策略还必须声明 `confirmationMode` 与 `rebindMode`:虎牙、斗鱼为客户资料比对确认,
|
||||
微博为平台角色事实确认;虎牙、斗鱼走平台确认换绑,微博走重新扫码换绑。
|
||||
- 角色文本、区服和身份比对只能使用公共账号绑定策略层;虎牙、斗鱼 Adapter 只把平台事实映射成
|
||||
统一字段,不得各自实现另一套空格、大小写或区服匹配规则。平台 Adapter 仍可保留各自的登录、
|
||||
二维码、换绑、冷却和错误协议,公共层不得直接调用平台 RPC。
|
||||
- 外部 Connector 通过签名 Webhook `POST /api/integration/platform-fulfillment/semi-auto/task-state`
|
||||
提交登录与绑定快照,事件 ID 使用 `integration_inbox` 幂等;Connector 只提交平台观察到的事实,
|
||||
不得直接声明业务履约完成。执行状态由登录、绑定和人工确认规则推导。
|
||||
@@ -667,13 +686,15 @@ has_active_cost
|
||||
客户页 `/c/<平台订单号>` 统一展示:
|
||||
|
||||
```text
|
||||
登录 → 填写资料 → 绑定角色 → 客服处理 → 完成
|
||||
登录 → 查询或填写角色资料 → 绑定角色 → 客服处理 → 完成
|
||||
```
|
||||
|
||||
- 三步进度固定为「登录虎牙账号 → 填写游戏资料 → 绑定游戏角色」,当前步骤高亮,已完成为勾选。
|
||||
- 虎牙三步进度固定为「登录虎牙账号 → 填写游戏资料 → 绑定游戏角色」,当前步骤高亮,已完成为勾选。
|
||||
- 登录成功后才展示资料表单;资料三项(区服 / 游戏编号 / 角色名)未填全时不展示绑定二维码。
|
||||
- 绑定角色页展示平台角色与客户资料的逐项对照:三项完全一致才出现「提交平台绑定」;
|
||||
不一致时固定显示「重新扫码换绑」「上一步修改资料」,换绑后仍不一致时以修改资料为主。
|
||||
- 微博登录成功后直接展示微信/QQ 绑定入口;平台返回已绑定角色时直接进入等待客服,
|
||||
未绑定时展示扫码二维码,扫码后重新读取平台角色,角色名发生变化才视为换绑成功。
|
||||
- 页面只能展示客户完成操作所需的最小信息,不得展示 CK、内部成本或其他订单。后台默认只展示平台 UID、
|
||||
凭证来源、健康状态、更新时间、CK 导出和一次性注入入口。CK 导出不依赖绑定状态、任务领取人或
|
||||
额外权限;导出动作必须留审计且不得复用普通详情接口。
|
||||
@@ -1096,7 +1117,7 @@ docs/archive/
|
||||
|
||||
## 十三、当前下一步
|
||||
|
||||
截至 2026-11-17,生产基线为 `166`,集成分支开发基线为 `170`。迁移 `152` 保护订单来源快照,
|
||||
截至 2026-11-18,生产基线为 `166`,集成分支开发基线为 `170`。迁移 `152` 保护订单来源快照,
|
||||
迁移 `158–160` 收口寄卖登记人同步、寄卖平台与自动匹配设置;
|
||||
迁移 `161` 一次建立人工渠道半自动任务、内置 Connector 默认值、账号级 Cookie JSON 凭证、
|
||||
任务凭证引用和最终约束;迁移 `162` 建立履约待办四桶只读投影、补载体专用索引和新单优先扫描口径。
|
||||
@@ -1127,7 +1148,8 @@ docs/archive/
|
||||
再按窗口执行 `--execute --confirm=REBUILD_DERIVED`,并验证第二次重建幂等。
|
||||
5. 观察一个完整财务期间,确认页面、履约、事实和总账持续对平。
|
||||
6. 半自动平台负责客户登录、账号 CK 获取和游戏角色绑定;微博支持手机号登录、易盾二次验证、
|
||||
完整域名 Cookie 保存和会话恢复;虎牙支持客户手动触发的短信验证码登录和扫码登录。
|
||||
完整域名 Cookie 保存、会话恢复、游戏角色查询和微信/QQ 扫码绑定;虎牙支持客户手动触发的
|
||||
短信验证码登录和扫码登录。
|
||||
虎牙客户登录后必须先填写区服 / 游戏编号 / 角色名,再进入绑定;三项与平台角色完全一致
|
||||
才能提交平台绑定,不一致时只能重新扫码换绑或返回上一步修改资料,不提供直接使用原角色的快捷确认。
|
||||
7. 观察期结束后,再单独发布兼容表、旧脚本别名和 `legacy_*` 字段的删除迁移。
|
||||
|
||||
Reference in New Issue
Block a user