requestSubscribeMessage 是微信提供的方法
封装的调用requestSubscribeMessage的方法
示例图如下
import {
getWechatTemplates,
postSubscribeNotice
} from '@/magic-sdk/apis/wechat-service';
import {
WechatTemplateType,
SubscribeNoticeObjTypeOptions,
WechatTemplateEvent
} from '@/magic-sdk/types/wechat-service';
import {
getSetting,
requestSubscribeMessage /**, showToast */,
nextTick,
SubscriptionsSetting
} from '@tarojs/taro';
import Modal from '@/components/Modal/Modal';
import { isEmpty } from 'lodash-es';
import { captureException } from '../sentry';
import { showSubscribeGuidePopup } from './popup';
import {} from './platform';
export interface OtherParams {
objValue: string | number | undefined;
}
/**
* 通过类型从后端获取订阅模板id并尝试订阅
* @param type
* @returns
*/
export async function tryWechatSubscribeByType(
type: WechatTemplateType,
otherParams: OtherParams = {
objValue: undefined
},
successCb?: () => void
): Promise<boolean> {
try {
const { data: templateList } = await getWechatTemplates(type);
const isWeapp = process.env.TARO_ENV === 'weapp';
if (!templateList || !templateList.length) {
// showToast({ title: '抱歉,暂时还未开通该订阅消息服务', icon: 'none' });
return false;
}
const templateIds = templateList.map(({ templateId }) => templateId);
const subscriptionsSetting =
(await getSubscriptionsSetting()) as SubscriptionsSetting;
const noSettings =
isWeapp &&
(isEmpty(subscriptionsSetting.itemSettings) ||
(subscriptionsSetting.itemSettings &&
templateIds.some((id) =>
isEmpty(subscriptionsSetting.itemSettings[id])
)));
let response: Record<string, string> = {};
if (process.env.TARO_ENV === 'alipay') {
response = await my.requestSubscribeMessage({
entityIds: templateIds
});
} else if (process.env.TARO_ENV === 'weapp') {
if (noSettings) {
nextTick(showSubscribeGuidePopup);
}
response = (await requestSubscribeMessage({
tmplIds: templateIds,
complete: () => {
Modal.destroy();
}
})) as Record<string, string>;
}
let isAccept = false;
templateList.forEach((item) => {
if (response[item.templateId] === 'accept') {
const objType = SubscribeNoticeObjTypeOptions[item.event];
const newOtherParams =
item.event === WechatTemplateEvent.ActivityNotice
? { objValue: objType }
: otherParams;
postSubscribeNotice({
event: item.event,
templateId: item.templateId,
objType,
...newOtherParams
});
isAccept = true;
}
});
if (isAccept) {
if (successCb) {
if (noSettings) {
Modal.destroy();
//关闭指导弹窗再执行回调
nextTick(successCb);
} else {
successCb();
}
}
return true;
}
// 如果用户勾选了总是保持以上选择的订阅选项
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// XXX: Taro的类型不正确, 下同
// 参考:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/wx.getSetting.html
if (
isWeapp &&
subscriptionsSetting.itemSettings &&
templateIds.some(
(id) => subscriptionsSetting.itemSettings[id] === 'reject'
)
) {
// showToast({
// title: '您已拒绝接收通知,请前往微信 - 服务通知 设置接收',
// icon: 'none'
// });
return false;
}
} catch (error) {
// 模板id不正确的情况
// if (error.errCode === 20001) {
// showToast({ title: '抱歉,暂时还未开通消息服务', icon: 'none' });
// }
if (process.env.TARO_ENV === 'weapp') {
Modal.destroy();
}
captureException(error);
}
return false;
}
export async function getSubscriptionsSetting() {
if (process.env.TARO_ENV === 'weapp') {
const { subscriptionsSetting } = await getSetting({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
withSubscriptions: true
});
return subscriptionsSetting;
}
return { itemSettings: {} };
}
tryWechatSubscribeByType 调用公用方法
import React, { Component, CSSProperties } from 'react';
import { View, Text } from '@tarojs/components';
import { WechatTemplateType } from '@/magic-sdk/types/wechat-service';
import {
getColorByTheme,
getTextStyleByTheme
} from '@/application/utils/theme';
import { hexToRgba } from '@/application/utils/format';
import {
OtherParams,
tryWechatSubscribeByType
} from '@/application/utils/subscribe';
import './index.scss';
interface Props {
text: string;
btnText: string;
type: WechatTemplateType;
otherParams?: OtherParams;
successCb?: () => void;
}
const prefix = 'cm-subscrible';
export default class CmSubscribe extends Component<Props> {
/**
* @name subscribeMessage
* @description 消息订阅
*/
private subMsg = async () => {
const { type, otherParams, successCb } = this.props;
await tryWechatSubscribeByType(type, otherParams, successCb);
};
/**
* @name renderSubscribe
* @description 商场活动订阅消息区域结构渲染
*/
private renderSub = () => {
const { text, btnText } = this.props;
const subStyle: CSSProperties = {
color: getColorByTheme('primary'),
backgroundColor: hexToRgba(getColorByTheme('primary'), 0.1)
};
const btnStyle: CSSProperties = {
borderColor: getColorByTheme('primary')
};
const txtStyle = getTextStyleByTheme('primary');
return (
<View className={innerClassNames.subscribe} style={subStyle}>
<Text className={innerClassNames.subscribeText} style={txtStyle}>
{text}
</Text>
<View
className={innerClassNames.subscribeBtn}
onClick={this.subMsg}
style={btnStyle}
>
<Text className={innerClassNames.subscribeBtnText} style={txtStyle}>
{btnText}
</Text>
</View>
</View>
);
};
render(): React.ReactNode {
return <View className={prefix}>{this.renderSub()}</View>;
}
}
const innerClassNames = {
subscribe: `${prefix}__subscribe`,
subscribeText: `${prefix}__subscribe-text`,
subscribeBtn: `${prefix}__subscribe-btn`,
subscribeBtnText: `${prefix}__subscribe-btn-text`
};