Files
BYW-VoiceHub/server/api/user/wechat-subscribe-status.get.ts
T

43 lines
1.9 KiB
TypeScript

import { inspectWechatSubscribe } from '~~/server/services/wechatSubscribeService'
/**
* 小程序「微信通知」卡片读的**只读**状态:能不能收到、为什么收不到、还能收几条。
*
* 为什么不直接放 `wx.getSetting` 的结果:那只是「用户上次在弹窗里选了什么」,
* 不代表服务端还有额度(微信按「发一条扣一条」算,也没有查询余额的接口)。
* 这里返回的是服务端自己记的账 + 真正能发出去的前提条件。
*
* 只返回结论与人话,不回传 openid 原文。
*/
export default defineEventHandler(async (event) => {
const user = event.context.user
if (!user) {
throw createError({ statusCode: 401, message: '未授权访问' })
}
const inspection = await inspectWechatSubscribe(Number(user.id))
const remainingTotal = inspection.templates.reduce((sum, t) => sum + t.remainingApprox, 0)
return {
enabled: inspection.enabled,
canReceive:
inspection.user.hasOpenid && inspection.user.notificationEnabled && inspection.tokenOk,
hasOpenid: inspection.user.hasOpenid,
notificationEnabled: inspection.user.notificationEnabled,
verdict: inspection.user.verdict,
/** 所有模板加起来还剩几条(只是服务端自己记的账,不代表微信侧的真实余额) */
remainingTotal,
templates: inspection.templates.map((t) => ({
kind: t.kind,
title: t.title,
remaining: t.remainingApprox,
granted: t.grantedCount,
sent: t.sentCount,
lastErrorCode: t.lastErrorCode,
verdict: t.verdict
})),
actions: inspection.actions,
note: 'remaining 只是服务端自己记的账(微信不提供剩余授权查询),**不影响能不能发**:服务端一律照常尝试发送,真没额度时微信会回 43101,此时用户在小程序里点一次「开启」就补 1 条'
}
})