oak-general-business/es/utils/notification/wechatPublic.js

107 lines
3.3 KiB
JavaScript

import { generateNewIdAsync } from 'oak-domain/lib/utils/uuid';
import WechatSDK from 'oak-external-sdk/lib/WechatSDK';
import { composeUrl } from 'oak-domain/lib/utils/domain';
import { composeDomainUrl } from '../domain';
export const wechatPublicHandler = 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 === 'wechatPublic');
const { config, id: applicationId } = app;
const { appId, appSecret } = config;
const [domain] = await context.select('domain', {
data: {
id: 1,
url: 1,
apiPath: 1,
protocol: 1,
port: 1,
},
filter: {
system: {
application$system: {
id: applicationId,
},
},
},
}, { dontCollect: true });
const instance = WechatSDK.getInstance(appId, 'wechatPublic', appSecret);
const { openId, wechatMpAppId } = data1;
let page;
// message 用户不需要跳转页面
if (router) {
const pathname = router.pathname;
if (wechatMpAppId) {
const url = pathname.startsWith('/')
? `pages${pathname}/index`
: `pages/${pathname}/index`;
page = composeUrl(url, Object.assign({}, router.props, router.state));
}
else {
const url = composeDomainUrl(domain, pathname);
page = composeUrl(url, Object.assign({}, router.props, router.state));
}
}
try {
await instance.sendTemplateMessage({
openId,
templateId: templateId,
url: !wechatMpAppId ? page : undefined,
data: data,
miniProgram: wechatMpAppId
? {
appid: wechatMpAppId,
pagepath: page,
}
: undefined,
clientMsgId: id,
});
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 });
}
};