微信分享功能

This commit is contained in:
2026-07-14 17:48:07 +08:00
parent 5222ec82b0
commit 9b13d02dde
9 changed files with 271 additions and 19 deletions
+97
View File
@@ -0,0 +1,97 @@
import Taro from '@tarojs/taro';
import { BRAND_LOGO_URL } from '@dukang/shared-types';
import type { WechatShareData } from '@dukang/weixin-sdk';
import { getWechatShareLink, isWechatBrowser, isMiniProgram } from '@dukang/weixin-sdk';
import { toast } from './api';
import { isWechatEnv, weixinSdk } from './weixin';
export const DEFAULT_SHARE_TITLE = '你吃饭,杜康买单';
export const DEFAULT_SHARE_DESC = '杜康好客 · 买酒享权益,全城门店可用';
export const WECHAT_SHARE_HINT = '请点击右上角 ··· 分享给好友';
export function getDefaultShareImageUrl(): string {
return BRAND_LOGO_URL;
}
export function buildDefaultShareData(
overrides?: Partial<WechatShareData>,
): WechatShareData {
let link = overrides?.link;
if (!link) {
if (process.env.TARO_ENV === 'h5' && typeof window !== 'undefined') {
link = getWechatShareLink();
} else {
link = '';
}
}
return {
title: overrides?.title ?? DEFAULT_SHARE_TITLE,
desc: overrides?.desc ?? DEFAULT_SHARE_DESC,
link,
imgUrl: overrides?.imgUrl ?? getDefaultShareImageUrl(),
};
}
/** 配置 H5 微信内右上角分享卡片 */
export async function applyWechatShare(
overrides?: Partial<WechatShareData>,
): Promise<void> {
if (process.env.TARO_ENV !== 'h5') return;
if (!isWechatBrowser()) return;
await weixinSdk.setShare(buildDefaultShareData(overrides));
}
export type PageSharePayload = {
title?: string;
desc?: string;
/** 小程序分享 path,如 /pages/product-detail/index?id=1 */
path?: string;
imgUrl?: string;
/** H5 自定义分享 link,默认当前页 */
link?: string;
};
/** 点击「分享」按钮 */
export async function handleShareButtonClick(payload?: PageSharePayload): Promise<void> {
// 小程序:由 Button open-type="share" 触发,无需在此拉起
if (process.env.TARO_ENV === 'weapp' || isMiniProgram()) {
try {
await Taro.showShareMenu({ withShareTicket: true, showShareItems: ['shareAppMessage', 'shareTimeline'] });
} catch {
/* 旧基础库可能不支持 showShareItems */
try {
await Taro.showShareMenu({ withShareTicket: true });
} catch {
/* ignore */
}
}
toast(WECHAT_SHARE_HINT);
return;
}
if (!isWechatEnv()) {
toast('请在微信内打开后分享');
return;
}
try {
await applyWechatShare({
title: payload?.title,
desc: payload?.desc,
imgUrl: payload?.imgUrl,
link: payload?.link,
});
toast(WECHAT_SHARE_HINT);
} catch {
toast('分享配置失败,请刷新后重试');
}
}
/** 供 useShareAppMessage 使用的标题/路径/图 */
export function toWeappShareMessage(payload?: PageSharePayload) {
return {
title: payload?.title || DEFAULT_SHARE_TITLE,
path: payload?.path || '/pages/home/index',
imageUrl: payload?.imgUrl || getDefaultShareImageUrl(),
};
}