微信开发现在很普遍,微信分享基本都有涉及,下面是记录一下微信分享开发需要注意到的地方。
1. 公众号配置
需要登录微信公众平台,进入“公众号设置”的“功能设置”里填写“JS接口安全域名”,不然无法验证。
2. 后端配置
后端根据ACCESS_TOKEN,APPID等参数,获取前端校验需要使用的签名信息,返回给前端。
3. 前端配置
1. 安装微信sdk,并引用
npm install weixin-js-sdk --save import wx from 'weixin-js-sdk'
wx.config 参数说明:
debug 是否开启调试模式,调用的所有api的返回值会在客户端alert出来(仅PC端)。
appId 必填,公众号的唯一标识
timestamp 生成签名的时间戳
nonceStr 生成签名的随机串
signature 签名
jsApiList 需要使用的JS接口列表
wx.onMenuShareTimeline 参数说明:
title 分享标题
desc 分享介绍
link 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl 分享图标
success 分享成功回调方法
cancel 取消分享回调方法
// 微信分享 let postDate = {}; postDate.url = '需要校验的地址'; POST(postDate) .then(res => { let data = res.data; wx.config({ debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] }); wx.ready(function() { wx.onMenuShareTimeline({ title: shareData.title, desc: shareData.desc, link: shareData.url, imgUrl: shareData.img, success: function() { Toast('分享成功!!!'); }, cancel: function() { Toast('取消分享!!!'); } }); wx.onMenuShareAppMessage({ title: shareData.title, desc: shareData.desc, link: shareData.url, imgUrl: shareData.img, success: function() { Toast('分享成功!!!'); }, cancel: function() { Toast('取消分享!!!'); } }); }); wx.error(function(res) { console.log('wx.err', res) }); }) .catch(err => { console.log(err); });
4. 遇到的坑
vue路由如果用的是hash的话,微信分享打开以后一直是首页。
解决办法--使用url重定向
在public下面也就是index.html同级下面,创建redirect.html.
分享链接处理如下
let shareUrl = window.location.href.split('#')[0] + '#' + window.location.href.split('#')[1];let redirectShareUrl = shareUrl.split('#')[0] + 'redirect.html?app3Redirect=' + encodeURIComponent(shareUrl);
redirect.html处理如下
html><html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge">head><body>body><script> let url = location.href.split('?') let pars = url[1].split('&') let data = {} console.log(pars) pars.forEach((n, i) => { let p = n.split('=') data[p[0]] = p[1] }) console.log(data.app3Redirect) if (!!data.app3Redirect) { self.location = decodeURIComponent(data.app3Redirect) }script>html>