公众号分享功能的实现
1.公众平台配置ip白名单 https://mp.weixin.qq.com/
设置与开发 》 基本配置 》 公众号开发信息 》 ip白名单 接口地址对应的ip
2.业务域名和JS安全域名的设置
设置与开发 》 公众号设置 》 功能设置 》 业务域名和JS安全域名
在设置的时候有个txt需要放到前端的public文件夹下面
3.weixin-js-sdk 的安装
npm install weixin-js-sdk
4.开始贴代码了
在main.ts 引入 import '@/utils/wx/wx.config'
wx.config.ts 文件
import wx from 'weixin-js-sdk'
import { getWxJssdk } from '@/apis/wx.api'
import { Toast } from 'vant'
const w = (window as any)
if (typeof w.entryUrl === 'undefined' || w.entryUrl === '') {
w.entryUrl = location.href.split('#/')[0]
}
// 进行签名的时候 Android 不用使用之前的链接, ios 需要
const signLink = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : w.entryUrl;
(async function () {
const config:any = await getWxJssdk(signLink)
// Toast({
// message: `${JSON.stringify(config)} --- ${signLink}`,
// duration: 10000
// })
// console.log(signLink, 'signLink')
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
beta: false,
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timestamp, // 必填,生成签名的时间戳
nonceStr: config.nonceStr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名,见附录1
jsApiList: [
'updateAppMessageShareData',
'updateTimelineShareData'
] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2,
})
})()
wx.function
import wx from 'weixin-js-sdk'
interface ShareOptionsProps {
title: string;
desc?: string;
link: string;
imgUrl?: string;
success?: (res?:any) => {}
}
/**
* 分享链接
* @param data
*/
export function setWxShare (shareOptions: ShareOptionsProps) {
const { title, desc, link, imgUrl, success } = shareOptions
console.log(title, desc, link, imgUrl)
wx.ready(function () {
// 分享给朋友
wx.updateAppMessageShareData({
title, // 分享标题
desc, // 分享描述
link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl, // 分享图标
success: function (res: any) {
success && success(res)
}
})
// 分享给朋友圈
wx.updateTimelineShareData({
title, // 分享标题
link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl, // 分享图标
success: function (res: any) {
success && success(res)
}
})
})
}
在routes路由文件配置mate
meta: {
title: '爆品构件推荐',
shareTitle: 'PC构件目录',
shareDesc: '大乐装 | 装配式建筑一站式交付平台',
shareUrl: location.origin
}
最后路由守卫里的处理 main.ts 引入 import '@/routers/guard'
guard.ts
import { setWxShare } from '@/utils/wx/wx.function'
import router from './index'
const DETAULT_SHARE_IMG_URL = 'https://cz-filemino.dalezhuang.com/template/799008d73916462d88dc4976417e6cf0.png'
router.beforeEach((to, from, next) => {
const url = location.href
if (to.meta) {
document.title = to.meta.title as string
const { shareTitle, shareDesc, shareUrl, shareImgUrl } = to.meta as any
setWxShare({
title: shareTitle,
desc: shareDesc,
link: shareUrl || url,
imgUrl: shareImgUrl || DETAULT_SHARE_IMG_URL
})
}
next()
})
router.afterEach((to) => {
if (!to.meta?.keepAlive) {
window.scrollTo(0, 0)
}
})
完了!!!

浙公网安备 33010602011771号