微信内二次分享网页
2023-11-22 本文已影响0人
芸芸众生ing
import fetchData from '@/common/api';
import { SHA1 } from 'crypto-js';
const appId = '';
const secret = '';
// 后端
async function getWxSign(_, { pageUrl }) {
try {
// 获取access_token
const accessRes = await fetch(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secret}`)
const access = await accessRes.json();
console.log('access', access);
// 获取jsapi_ticket
const ticketRes = await fetch(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access.access_token}&type=jsapi`);
const ticket = await ticketRes.json();
console.log('ticket', ticket);
// 时间戳(秒)
const timestamp = Math.ceil(Date.now() / 1000);
// 32 位随机字串
const nonceStr = `${Date.now()}${Date.now()}${Math.floor(Math.random() * 10000)}`.slice(0, 32);
const obj = { appId, timestamp, noncestr: nonceStr, url: pageUrl }
// 根据规则生成字符串
const signature = ['noncestr', 'jsapi_ticket', 'timestamp', 'url'].sort().map(e => {
return `${e}=${obj[e]}`
}).join('&')
return {
data: {
appId, timestamp, nonceStr, link: pageUrl, signature: SHA1(signature) // sha1方式加密根据规则生成的字符串
}
}
} catch (error) {
return Promise.reject(error)
}
}
// 前端
// 浏览器分享
export async function setMetaConent({ title, content, icon }) {
try {
const obj = {
'og:title': title,
'og:description': content,
'og:image': icon,
}
const ele = [...document.head.querySelectorAll("[property^=og]")]
ele.forEach(e => {
const type = e.getAttribute('property');
e.setAttribute('content', obj[type]);
})
} catch (error) {
console.log(error);
}
}
// 微信内二次分享
export async function getShareConfig(params) {
const { title = '默认标题', content = '默认描述', icon = '默认logo' } = params;
let idx = 0;
let steps = [1000, 2000, 3000, 4000, 8000, 16000, 32000, 64000];
let data = {};
let url = ''; // 分享页面地址链接
async function wxConfig() {
url = window.location.href.split('#')[0];
const res = await fetchData('getWxSign', { pageUrl: url }); // 获取签名
data = res.data;
wx.config({
debug: false,// 关闭调试模式
appId: data.appId, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.noncestr, // 必填,生成签名的随机串
signature: data.signature, // 必填,签名
jsApiList: [
"updateTimelineShareData",
"updateAppMessageShareData",
'onMenuShareTimeline',
'onMenuShareAppMessage'
]
});
}
function wxConfigReady() {
let shareParams = {
title,
desc: content,
link: data.link || url,
imgUrl: icon,
success: () => console.log('分享准备完成')
}
console.log('wx=>ready shareParams:', shareParams)
wx.updateAppMessageShareData(shareParams)
wx.updateTimelineShareData(shareParams)
wx.onMenuShareAppMessage(shareParams)
wx.onMenuShareTimeline(shareParams)
}
function wxConfigError() {
console.log('wx=>error 第', idx + 1, '次');
setTimeout(wxConfig, idx < steps.length ? steps[idx++] : steps[steps.length - 1])
}
wx.error(wxConfigError);
wx.ready(wxConfigReady);
wxConfig();
}