微信分享
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
import { ensureJssdkReady, normalizeJssdkPageUrl } from './jssdk';
|
||||
import { getRuntimePlatform, isWechatBrowser } from './env';
|
||||
import type { WeixinSdkConfig } from './types';
|
||||
|
||||
export type WechatShareData = {
|
||||
title: string;
|
||||
desc: string;
|
||||
link: string;
|
||||
imgUrl: string;
|
||||
};
|
||||
|
||||
export function canUseWechatShare(): boolean {
|
||||
return isWechatBrowser() || getRuntimePlatform() === 'mini';
|
||||
}
|
||||
|
||||
function applyShareData(data: WechatShareData): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const wx = window.wx;
|
||||
if (!wx?.updateAppMessageShareData || !wx.updateTimelineShareData) {
|
||||
reject(new Error('当前微信版本不支持分享,请升级微信后重试'));
|
||||
return;
|
||||
}
|
||||
|
||||
let pending = 2;
|
||||
let failed = false;
|
||||
const done = (err?: Error) => {
|
||||
if (err && !failed) {
|
||||
failed = true;
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
pending -= 1;
|
||||
if (pending === 0 && !failed) resolve();
|
||||
};
|
||||
|
||||
wx.updateAppMessageShareData({
|
||||
title: data.title,
|
||||
desc: data.desc,
|
||||
link: data.link,
|
||||
imgUrl: data.imgUrl,
|
||||
success: () => done(),
|
||||
fail: (res) => done(new Error(res.errMsg || '设置分享给朋友失败')),
|
||||
});
|
||||
|
||||
wx.updateTimelineShareData({
|
||||
title: data.title,
|
||||
link: data.link,
|
||||
imgUrl: data.imgUrl,
|
||||
success: () => done(),
|
||||
fail: (res) => done(new Error(res.errMsg || '设置分享到朋友圈失败')),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** 配置微信内分享卡片(好友 / 朋友圈) */
|
||||
export async function setWechatShareData(
|
||||
config: WeixinSdkConfig,
|
||||
data: WechatShareData,
|
||||
): Promise<void> {
|
||||
if (!canUseWechatShare()) return;
|
||||
|
||||
await ensureJssdkReady({
|
||||
apiBase: config.apiBase ?? '/api/v1',
|
||||
clientApp: config.clientApp,
|
||||
getAccessToken: config.getAccessToken,
|
||||
});
|
||||
|
||||
await applyShareData(data);
|
||||
}
|
||||
|
||||
/** 获取当前页分享链接(去掉 hash、OAuth 回跳参数) */
|
||||
export function getWechatShareLink(rawUrl?: string): string {
|
||||
if (typeof window === 'undefined') return rawUrl ?? '';
|
||||
return normalizeJssdkPageUrl(rawUrl ?? window.location.href);
|
||||
}
|
||||
Reference in New Issue
Block a user