H5实现微信的自定义分享功能

微信开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

H5不支持点击页面内按钮直接唤起分享面板,可以显示一个引导图,引导用户使用右上角的分享功能。

实现步骤:

  1. 绑定域名,先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”,即后端接口的域名。
  2. 引入微信官方的JS-SDK文件:<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>
  3. 请求后端接口:前端需要将encodeURIComponent(location.href.split('#')[0])作为参数传给后端(后端需要用到它来获取签名),获取配置所需要的参数:appid、timestamp、noncestr和signature;
  4. 通过config接口注入权限验证配置;
  5. 通过ready接口处理成功验证;
<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>

handleShare(){
            this.$api.adopt
                .getShareParams({
                    url:encodeURIComponent(location.href.split('#')[0])
                })
                .then(res => {
                    wx.config({
                        debug: false,// 是否开启调试模式
                        appId: res.appId,//appid
                        timestamp: res.timestamp,// 时间戳
                        nonceStr: res.nonceStr,// 随机字符串
                        signature: res.signature,// 签名
                        jsApiList: [
                            'checkJsApi',
                   		    'onMenuShareTimeline',
                   			'onMenuShareAppMessage',
                    		'onMenuShareQQ',
                   			 'onMenuShareQZone',
                        ]// 需要使用的JS接口列表
                    })

					 let shareData = {
                            title: '这是自定义的分享的标题', // 分享标题
                            desc: '这是自定义的分享的描述', // 分享描述
                            link: location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: ‘这是自定义的分享的图标’, // 分享图标
                            success: function () {},//分享成功的回调函数
                            cancel:function(){}//分享失败的回调函数
                     }

					//所有接口调用都必须在config接口获得结果之后。
					//config信息验证后会执行ready方法。
					//config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
                    wx.ready(function(){                  
                         wx.onMenuShareAppMessage(shareData); // 微信好友
                		 wx.onMenuShareTimeline(shareData); // 微信朋友圈
               			 wx.onMenuShareQQ(shareData); // QQ
               			 wx.onMenuShareQZone(shareData) // QQ空间
                    });
                })
                .catch(err => {})
}

在这里插入图片描述

报错问题:

invalid signature签名错误:

  1. 确认签名算法正确,可用http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign 页面工具进行校验。
  2. 确认config中nonceStr(js中驼峰标准大写S), timestamp与用以签名中的对应noncestr, timestamp一致。
  3. 确认 config 中的 appid 与用来获取 jsapi_ticket 的 appid 一致。
  4. 确保一定缓存access_token和jsapi_ticket。
  5. 确认url是页面完整的url,包括’http(s)😕/‘部分,以及’?‘后面的GET参数部分,但不包括’#‘hash后面的部分。可以在当前页面alert(location.href.split(’#’)[0])确认。
  6. 确保获取用来签名的url是动态获取的。在前端通过ajax将url传到后台签名,前端需要用js获取当前页面除去’#‘hash部分的链接(可用location.href.split(’#’)[0]获取,而且需要encodeURIComponent),因为页面一旦分享,微信客户端会在你的链接末尾加入其它参数,如果不是动态获取当前链接,将导致分享后的页面签名失败。
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现定义微信分享当前页,需要在uniapp中使用微信JS-SDK,以下是大致的步骤: 1. 在公众号后台开启JS接口安全域名,并将当前网站的域名加入安全域名列表。 2. 在uniapp项目中安装并引入jweixin-1.6.0.js,可以通过npm命令安装,也可以手动下载并引入。 3. 在vue组件的mounted钩子函数中初始化微信JS-SDK,代码如下: ``` mounted() { // 初始化微信JS-SDK this.initWXSDK() }, methods: { initWXSDK() { // 替换为你自己的appId和当前页面地址 const appId = 'yourAppId' const url = window.location.href const timestamp = new Date().getTime() const nonceStr = 'yourNonceStr' // 调用后端接口获取微信JS-SDK的签名signature axios.get('/api/getSignature?url=' + encodeURIComponent(url)) .then(res => { const signature = res.data.signature // 配置微信JS-SDK wx.config({ debug: false, appId: appId, timestamp: timestamp, nonceStr: nonceStr, signature: signature, jsApiList: [ 'updateAppMessageShareData', 'updateTimelineShareData' ] }) // 初始化成功后调用分享函数 wx.ready(() => { this.shareToWechat() }) }) .catch(err => { console.error(err) }) }, shareToWechat() { // 获取当前页面的标题、描述和图片 const title = '分享标题' const desc = '分享描述' const imgUrl = '分享图片地址' // 分享给朋友 wx.updateAppMessageShareData({ title: title, desc: desc, link: window.location.href, imgUrl: imgUrl, success: function () { // 分享成功后的回调函数 } }) // 分享到朋友圈 wx.updateTimelineShareData({ title: title, link: window.location.href, imgUrl: imgUrl, success: function () { // 分享成功后的回调函数 } }) } } ``` 4. 在后端接口中生成微信JS-SDK的签名signature,代码如下: ``` const crypto = require('crypto') const request = require('request') const config = { appId: 'yourAppId', appSecret: 'yourAppSecret' } async function getSignature(url) { const access_token = await getAccessToken() const nonceStr = createNonceStr() const timestamp = Math.floor(Date.now() / 1000) const jsapi_ticket = await getJsApiTicket(access_token) // 按照微信JS-SDK的规则生成签名signature const str = `jsapi_ticket=${jsapi_ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}` const signature = crypto.createHash('sha1').update(str, 'utf-8').digest('hex') return { appId: config.appId, timestamp: timestamp, nonceStr: nonceStr, signature: signature } } function createNonceStr() { return Math.random().toString(36).substr(2, 15) } function getAccessToken() { return new Promise((resolve, reject) => { const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appId}&secret=${config.appSecret}` request(url, (err, res, body) => { if (err) { reject(err) } else { const data = JSON.parse(body) if (data.access_token) { resolve(data.access_token) } else { reject(data.errmsg) } } }) }) } function getJsApiTicket(access_token) { return new Promise((resolve, reject) => { const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi` request(url, (err, res, body) => { if (err) { reject(err) } else { const data = JSON.parse(body) if (data.ticket) { resolve(data.ticket) } else { reject(data.errmsg) } } }) }) } module.exports = { getSignature } ``` 这样就完成了在uniapp h5中自定义微信分享当前页的实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值