记录一下通过微信网页分享时,需要自定义标题、描述和图片的功能。参考 JSSDJ 使用步骤 。
步骤解读
步骤一:JS 接口安全域名,指的是后端 API 接口域名。
步骤二:使用ES MODULE
加载微信 JS SDK
文件。
pnpm i weixin-js-sdk
步骤三:注入权限验证配置
1 2 3 4 5 6 7 8
| wx.config({ debug: true, appId: '', timestamp: , nonceStr: '', signature: '', jsApiList: [] });
|
jsApiList
指的是微信 JS 提供的接口,如“分享给朋友”接口updateAppMessageShareData
。
timestamp
、nonceStr
、signature
三个签名信息,让后端参考使用签名算法 将其返回给前端即可。
后端需要做的是:
- 获取
access_token
- 通过
access_token
获取jsapi_ticket
,并为jsapi_ticket
做缓存处理
- 返回签名信息:签名、生产签名的时间戳和随机串
步骤四:
获取签名信息是异步的,并且如果页面加载时就调用微信 JS 提供的接口,需将微信 JS 提供的接口放在wx.ready()
中调用。
步骤五:
通过 wx 对象的通用参数来验证微信 JS 提供的接口是否调用成功,如success
参数
1 2 3 4 5 6 7 8 9
| wx.updateAppMessageShareData({ title: '分享标题', desc: '分享描述', imgUrl: '分享图片链接', link: '分享页面链接', success: () => { alert('updateAppMessageShareData接口调用成功'); }, });
|
封装和使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import wx from 'weixin-js-sdk'; import request from '@/api'; import urlMap from '@/api/url-map';
const { weChat } = urlMap; const appId = 'xxxxxxxxxxxxx';
interface ShareData { title: string; desc?: string; link: string; imgUrl: string; success?: any; }
const useWXShare = () => { const updateAppMessageShareData = (props: ShareData) => { wx.updateAppMessageShareData(props); };
const updateTimelineShareData = (props: ShareData) => { wx.updateTimelineShareData(props); };
const getSign = () => { request .post(weChat.sign, { url: location.href, }) .then((res) => { const { timestamp, nonceStr, signature } = res.data; wx.config({ appId, timestamp, nonceStr, signature, jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData'], }); }); };
return { wx, updateAppMessageShareData, updateTimelineShareData, getSign, }; }; export default useWXShare;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import { useWXShare } from '@/hooks';
export default () => { const { wx, getSign, updateAppMessageShareData, updateTimelineShareData } = useWXShare();
useEffect(() => { getSign();
onLoading(); request .get(home.articlesDetail, { uri }) .then((res) => { const { title, description } = res.data; offLoading();
wx.ready(() => { updateAppMessageShareData({ title, desc: description, imgUrl: 'https:xx.jpeg', link: detailLink, }); updateTimelineShareData({ title, imgUrl: 'https:xx.jpeg', link: detailLink, }); }); }) .finally(() => offLoading()); }, []);
return ( <>微信网页分享<> ) }
|
微信网页分享朋友圈无法显示图片?
