feat(douyin-mashida): 抖音码速达最小接入后端(消息建单/券码同步/兑换核销/退款作废)
- 签名:出网 md5(secret+Σ(名+值)+secret) 与推送 md5(secret+data+pub_time+topic+secret) 两套独立实现,含文档 golden 向量单测(与 91 大写 / affiliate_dash HMAC 都不通用) - 进单:trade_TradePaid 推送 → 验签 → webhook_events 幂等 → order.orderDetail → upsertOrderFromSource(provider=douyin_mashida / platform=doudian) - 精度:19 位订单号超出 JS 安全整数,JSON.parse 会把 p_id 抹成 ...000; 故解析后从原始 JSON 文本用正则抓回精确数字(单测同时证明"不修会错") - 券码:迁移 094 redeem_certificates((provider,order_id) 唯一做发券幂等) + DYC 券码生成 + coupons.syncV2 同步(子单号优先、父单兜底) - 兑换:POST /api/v1/redeem/lookup|confirm,按 orderNo+IP 限流; 核销成功后 order.message 通知买家(best-effort,失败只记错误日志) - 退款/取消:作废未核销券;券已核销时打 WARN 资损告警(已消费不可回滚) - 后台:GET/POST /api/v1/admin/platform-config/douyin-mashida, secret 出参置空 + 掩码,掩码回写不覆盖原值 - 消息路由挂在全局 body parser 之前(app.ts),验签必须用 body 原始字符串
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { query } from '../db/client.js'
|
||||
|
||||
/**
|
||||
* 兑换券仓储(表 `redeem_certificates`,迁移 094)。
|
||||
*
|
||||
* 幂等键是 `(provider, order_id)`:平台重复推消息 / 我们重试发券时,
|
||||
* 同一订单只会有一张券(重复插入直接返回 null,由上层取已有券)。
|
||||
*/
|
||||
|
||||
export const REDEEM_CERT_CODE_PREFIX = 'DYC'
|
||||
const CERT_CODE_RANDOM_BYTES = 10
|
||||
const CERT_CODE_MAX_GENERATE_ATTEMPTS = 5
|
||||
const CROCKFORD_BASE32_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
|
||||
|
||||
export type RedeemCertificateStatus = 'issued' | 'synced' | 'verified' | 'invalid'
|
||||
export type RedeemCertificateSyncStatus = 'pending' | 'success' | 'failed'
|
||||
|
||||
export type RedeemCertificateRow = {
|
||||
id: number
|
||||
provider: string
|
||||
cert_no: string
|
||||
order_id: string
|
||||
parent_order_id: string
|
||||
local_order_id: number | null
|
||||
order_item_id: number | null
|
||||
cert_link: string
|
||||
status: RedeemCertificateStatus
|
||||
sync_status: RedeemCertificateSyncStatus
|
||||
sync_error: string
|
||||
grant_time: string | null
|
||||
synced_at: string | null
|
||||
verified_at: string | null
|
||||
raw_payload_json: unknown
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export function generateRedeemCertificateCode(
|
||||
randomBytes: (size: number) => Uint8Array = crypto.randomBytes,
|
||||
): string {
|
||||
return `${REDEEM_CERT_CODE_PREFIX}${encodeCrockfordBase32(randomBytes(CERT_CODE_RANDOM_BYTES))}`
|
||||
}
|
||||
|
||||
export async function findRedeemCertificateByOrder(input: {
|
||||
provider: string
|
||||
orderId: string
|
||||
}): Promise<RedeemCertificateRow | null> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`SELECT * FROM redeem_certificates WHERE provider = $1 AND order_id = $2 LIMIT 1`,
|
||||
[String(input.provider || '').trim(), String(input.orderId || '').trim()],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function findRedeemCertificateByCertNo(
|
||||
certNo: string,
|
||||
): Promise<RedeemCertificateRow | null> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`SELECT * FROM redeem_certificates WHERE cert_no = $1 LIMIT 1`,
|
||||
[String(certNo || '').trim()],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function listRedeemCertificatesByLocalOrder(
|
||||
localOrderId: number | string,
|
||||
): Promise<RedeemCertificateRow[]> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`SELECT * FROM redeem_certificates WHERE local_order_id = $1 ORDER BY id ASC`,
|
||||
[Number(localOrderId)],
|
||||
)
|
||||
return result.rows
|
||||
}
|
||||
|
||||
/**
|
||||
* 幂等插入:同一 (provider, order_id) 已存在时返回 null(调用方改取已有券)。
|
||||
* 券码随机,撞唯一键(23505)时自动重试换码。
|
||||
*/
|
||||
export async function insertRedeemCertificate(input: {
|
||||
provider: string
|
||||
orderId: string
|
||||
parentOrderId?: string | undefined
|
||||
localOrderId?: number | null | undefined
|
||||
orderItemId?: number | null | undefined
|
||||
certLink: string
|
||||
grantTime?: string | null | undefined
|
||||
rawPayload?: unknown
|
||||
}): Promise<RedeemCertificateRow | null> {
|
||||
for (let attempt = 1; attempt <= CERT_CODE_MAX_GENERATE_ATTEMPTS; attempt += 1) {
|
||||
const certNo = generateRedeemCertificateCode()
|
||||
|
||||
try {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`
|
||||
INSERT INTO redeem_certificates (
|
||||
provider, cert_no, order_id, parent_order_id, local_order_id, order_item_id,
|
||||
cert_link, status, sync_status, grant_time, raw_payload_json, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 'issued', 'pending', $8, $9::jsonb, NOW(), NOW())
|
||||
ON CONFLICT (provider, order_id) DO NOTHING
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
String(input.provider || '').trim(),
|
||||
certNo,
|
||||
String(input.orderId || '').trim(),
|
||||
String(input.parentOrderId || '').trim(),
|
||||
input.localOrderId == null ? null : Number(input.localOrderId),
|
||||
input.orderItemId == null ? null : Number(input.orderItemId),
|
||||
String(input.certLink || '').trim(),
|
||||
input.grantTime || null,
|
||||
JSON.stringify(input.rawPayload || {}),
|
||||
],
|
||||
)
|
||||
|
||||
// 没有 RETURNING 行 = 撞了 (provider, order_id):券已存在,交给上层取已有券
|
||||
return result.rows[0] || null
|
||||
} catch (error) {
|
||||
// 券码随机、全局唯一:极小概率撞码时换一个重试
|
||||
if (attempt < CERT_CODE_MAX_GENERATE_ATTEMPTS && isUniqueViolation(error)) {
|
||||
continue
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function isUniqueViolation(error: unknown): boolean {
|
||||
return Boolean(
|
||||
error &&
|
||||
typeof error === 'object' &&
|
||||
String((error as { code?: unknown }).code || '') === '23505',
|
||||
)
|
||||
}
|
||||
|
||||
export async function markRedeemCertificateSynced(input: {
|
||||
id: number | string
|
||||
certLink?: string | undefined
|
||||
rawPayload?: unknown
|
||||
}): Promise<RedeemCertificateRow | null> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`
|
||||
UPDATE redeem_certificates
|
||||
SET status = CASE WHEN status = 'issued' THEN 'synced' ELSE status END,
|
||||
sync_status = 'success',
|
||||
sync_error = '',
|
||||
cert_link = COALESCE(NULLIF($2, ''), cert_link),
|
||||
synced_at = NOW(),
|
||||
raw_payload_json = CASE WHEN $3::jsonb = '{}'::jsonb THEN raw_payload_json ELSE $3::jsonb END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING *
|
||||
`,
|
||||
[Number(input.id), String(input.certLink || '').trim(), JSON.stringify(input.rawPayload || {})],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function markRedeemCertificateSyncFailed(input: {
|
||||
id: number | string
|
||||
error: string
|
||||
}): Promise<RedeemCertificateRow | null> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`
|
||||
UPDATE redeem_certificates
|
||||
SET sync_status = 'failed', sync_error = $2, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING *
|
||||
`,
|
||||
[Number(input.id), String(input.error || '').slice(0, 500)],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
/** 核销上报成功:`verified`(已核销的重复调用不再改状态,保持幂等)。 */
|
||||
export async function markRedeemCertificateVerified(
|
||||
id: number | string,
|
||||
): Promise<RedeemCertificateRow | null> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`
|
||||
UPDATE redeem_certificates
|
||||
SET status = 'verified', verified_at = COALESCE(verified_at, NOW()), updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING *
|
||||
`,
|
||||
[Number(id)],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
/** 退款/取消:把该订单下未核销的券全部作废(已核销的不动,留给人工/售后处理)。 */
|
||||
export async function invalidateRedeemCertificatesByLocalOrder(input: {
|
||||
localOrderId: number | string
|
||||
reason: string
|
||||
}): Promise<RedeemCertificateRow[]> {
|
||||
const result = await query<RedeemCertificateRow>(
|
||||
`
|
||||
UPDATE redeem_certificates
|
||||
SET status = 'invalid',
|
||||
sync_error = CASE WHEN sync_error = '' THEN $2 ELSE sync_error END,
|
||||
updated_at = NOW()
|
||||
WHERE local_order_id = $1 AND status <> 'verified' AND status <> 'invalid'
|
||||
RETURNING *
|
||||
`,
|
||||
[Number(input.localOrderId), String(input.reason || '').slice(0, 500)],
|
||||
)
|
||||
return result.rows
|
||||
}
|
||||
|
||||
function encodeCrockfordBase32(bytes: Uint8Array): string {
|
||||
let bits = 0
|
||||
let value = 0
|
||||
let output = ''
|
||||
|
||||
for (const byte of bytes) {
|
||||
value = (value << 8) | byte
|
||||
bits += 8
|
||||
|
||||
while (bits >= 5) {
|
||||
output += CROCKFORD_BASE32_ALPHABET[(value >>> (bits - 5)) & 31] || ''
|
||||
bits -= 5
|
||||
}
|
||||
}
|
||||
|
||||
if (bits > 0) {
|
||||
output += CROCKFORD_BASE32_ALPHABET[(value << (5 - bits)) & 31] || ''
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
Reference in New Issue
Block a user