import { generateNewIdAsync } from 'oak-domain/lib/utils/uuid'; import WechatSDK from 'oak-external-sdk/lib/WechatSDK'; import { composeUrl } from 'oak-domain/lib/utils/domain'; export const wechatMpHandler = async (notification, context) => { const { data, templateId, messageSystemId, data1, id } = notification; const [messageSystem] = await context.select('messageSystem', { data: { id: 1, messageId: 1, message: { id: 1, userId: 1, router: 1, type: 1, }, system: { id: 1, application$system: { $entity: 'application', data: { id: 1, type: 1, config: 1, }, }, } }, filter: { id: messageSystemId, } }, { dontCollect: true }); const { system, message } = messageSystem; const { router } = message; const { application$system: applications } = system; const app = applications.find(ele => ele.type === 'wechatMp'); const { config } = app; const { appId, appSecret } = config; const instance = WechatSDK.getInstance(appId, 'wechatMp', appSecret); let page; if (router) { const pathname = router.pathname; const url = pathname.startsWith('/') ? `pages${pathname}/index` : `pages/${pathname}/index`; page = composeUrl(url, Object.assign({}, router.props, router.state)); } // 根据当前环境决定消息推哪个版本 const StateDict = { 'development': 'developer', 'staging': 'trial', 'production': 'former', }; try { await instance.sendSubscribedMessage({ templateId: templateId, data: data, openId: data1.openId, page, state: StateDict[process.env.NODE_ENV], }); await context.operate('notification', { id: await generateNewIdAsync(), action: 'succeed', data: {}, filter: { id, } }, { dontCollect: true }); } catch (err) { console.warn('发微信小程序消息失败', err); await context.operate('notification', { id: await generateNewIdAsync(), action: 'fail', data: {}, filter: { id, } }, { dontCollect: true }); } };