Files
yunzerwebsiteallinone/uniapp/utils/subscribe.js
T
2026-11-16 17:22:50 +08:00

67 lines
1.9 KiB
JavaScript

import { getSubscribeTemplates, authorizeSubscribe } from '@/api/subscribe.js'
const MAX_TMPL_PER_CALL = 3
export async function requestSubscribeNotice(options = {}) {
const silent = !!options.silent
// #ifdef MP-WEIXIN
let templates = []
try {
const data = await getSubscribeTemplates()
templates = (data && data.list) || []
} catch (e) {
if (!silent) uni.showToast({ title: '获取订阅模板失败', icon: 'none' })
return { ok: false, reason: 'template_fetch_failed' }
}
const tmplIds = templates.map((t) => t.template_id).filter(Boolean)
if (!tmplIds.length) {
if (!silent) uni.showToast({ title: '暂未配置订阅消息模板', icon: 'none' })
return { ok: false, reason: 'no_template' }
}
const accepted = []
for (let i = 0; i < tmplIds.length; i += MAX_TMPL_PER_CALL) {
const batch = tmplIds.slice(i, i + MAX_TMPL_PER_CALL)
let result = {}
try {
result = await new Promise((resolve, reject) => {
uni.requestSubscribeMessage({
tmplIds: batch,
success: resolve,
fail: reject
})
})
} catch (e) {
if (!silent) uni.showToast({ title: '订阅授权失败', icon: 'none' })
return { ok: false, reason: 'request_failed' }
}
batch.forEach((id) => {
if (result[id] === 'accept') accepted.push(id)
})
}
if (!accepted.length) {
if (!silent) uni.showToast({ title: '你取消了订阅授权', icon: 'none' })
return { ok: false, reason: 'refuse' }
}
try {
await authorizeSubscribe(accepted)
} catch (e) {
if (!silent) uni.showToast({ title: '授权结果上报失败', icon: 'none' })
return { ok: false, reason: 'report_failed' }
}
if (!silent) {
uni.showToast({ title: options.tip || '已开启消息提醒', icon: 'success' })
}
return { ok: true, accepted }
// #endif
// #ifndef MP-WEIXIN
if (!silent) uni.showToast({ title: '请在微信小程序中开启消息提醒', icon: 'none' })
return { ok: false, reason: 'not_mp' }
// #endif
}