微信分享遇到的問題
一開始的時候,微信的sdk,是通過script引入的。
但是,因為我們的頁面是短鏈接,會有一次轉換變成長鏈接,這就造成了在我們的系統不能正常使用微信分享。
最終經過N多次失敗,不得不重頭再來,一步步的走下來,最終發現是還是短鏈接轉長鏈接造成的問題,因為在初始化的時候是進來的時候是短鏈接,因為是通過script在開頭引入的,所以微信sdk已經監控到了,但是我們 wxsdk 配置裏面的 link 是我們要分享的長鏈接,微信會認為這是無效配置,所以微信分享不生效。
如果你的微信分享還是使用script引入的方式,但是微信分享不生效,可以試試換一種方式
解決問題的代碼
PS:多餘代碼就不寫了
main.js
import wxInit from '@/utils/wxjsdk'
wxInit.install()
wxsdk.js
// 微信的配置
import Vue from 'vue'
// 我們自己查要分享的數據的接口
import { getWxConfig, getWxShareData } from '../api/bvent.js'
import Store from '@/store'
// 引入微信sdk的包
import wx from 'weixin-js-sdk'
window.wx = wx
const wxSdk = {
install() {
Vue.prototype.$wxSdkInit = wxSdk.init
},
init() {
getWxConfig({ url: location.href }).then(res => {
wx.config({
debug: false, // 生產環境需要關閉debug模式
appId: res.appId, // appId通過微信服務號後台查看
timestamp: res.timestamp, // 生成簽名的時間戳
nonceStr: res.nonceStr, // 生成簽名的隨機字符串
signature: res.signature, // 簽名
jsApiList: [
// 需要調用的JS接口列表
'updateTimelineShareData', // 分享給好友
'updateAppMessageShareData', // 分享到朋友圈
'onMenuShareAppMessage', // 1.0 分享到朋友
'onMenuShareTimeline' // 1.0分享到朋友圈
]
})
wx.ready(function() {
getWxShareData({ id: Store.getters.bventId }).then(e => {
let shareData = {
title: e.shareTitle, // 分享標題
desc: e.shareDescribe, // 分享描述
link: e.shareLink, // 分享鏈接
imgUrl:
e.shareImage && e.shareImage.indexOf('http') === -1
? window.domainConfig.fileServer + '/' + e.shareImage
: e.shareImage // 分享圖標
}
wx.ready(function() {
wx.onMenuShareAppMessage(shareData)
wx.onMenuShareTimeline(shareData)
wx.updateAppMessageShareData(shareData)
wx.updateTimelineShareData(shareData)
})
})
})
})
}
}
export default wxSdk
App.vue
<template>
<router-view />
</template>
<script>
export default {
name: 'App',
mounted() {
// 微信分享使用的,所以判斷微信瀏覽器執行該方法
let ua = navigator.userAgent.toLowerCase()
var isWeixin = ua.indexOf('micromessenger') !== -1
if (isWeixin && !/miniprogram/.test(ua)) {
this.$wxSdkInit()
}
}
}
</script>