uniapp使用微信jssdk自定义分享

前言提示:本文记录的是使用uniapp开发的H5+APP项目,H5端使用微信自定义分享功能,文中有关APP的兼容,如果不需要兼容APP的可以忽略


一、引入

首先安装jweixin-module包

npm install jweixin-module --save  

二、封装工具方法

为了方便使用,新建一个wechat.js文件:

// #ifdef H5
import http from './http'
import wx from 'jweixin-module'
			
// 需要调用的微信api列表
export const WXAPI = [
  'chooseWXPay', 
  'updateAppMessageShareData',
  'updateTimelineShareData',
  'onMenuShareAppMessage',
  'scanQRCode', 
  'getLocation'
]
// 微信分享朋友默认配置
const shareOptionsDefalut = {
  title: '这是标题', // 分享标题
  desc: '这是描述', // 分享描述
  imgUrl: '图片地址', // 封面图
}

export default { 
  /**
   * 判断是否在微信中
   */
  isWechat() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
	  return true;
	} else {
	  return false;
	}
  },

  /**
   * 通过config接口注入权限验证配置
   * @param {Object} cb 需要执行的函数
   */
  getWxConfig(cb) {
	http('POST', '/shop/wx/shareFriend', { url: encodeURIComponent(window.location.href) }).then(res => {
	  if (res.success) {
		wx.config({
		  debug: false, // 是否开启调试模式
		  appId: res.data.appId, // 必填,公众号的唯一标识
		  timestamp: res.data.timestamp, // 必填,生成签名的时间戳
		  nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
		  signature: res.data.signature, // 必填,签名,见附录1
		  jsApiList: WXAPI
		})
		if (cb) {
		  cb()
		}
	  }
	})
  },

  /**
   * 唤起微信分享
   * @param {Object} sharedata 分享需要的参数
   * @param {Object} cb 成功回调
   * @param {Object} errorCb 失败回调
   */
  callWexinShare(sharedata = shareOptionsDefalut, cb = ()=>{}, errorCb = ()=>{}) {
	this.getWxConfig(()=>{
	  wx.ready(()=>{
		console.log('---config注入成功---,开始使用sdk接口')
		// 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
		wx.updateAppMessageShareData({
		  title: sharedata.title || shareOptionsDefalut.title,
		  desc: sharedata.desc || shareOptionsDefalut.desc,
		  // 微信对分享图有限制,具体看踩坑
		  imgUrl: (sharedata.imgUrl || shareOptionsDefalut.imgUrl) + '?x-oss-process=image/resize,w_120,m_lfit/format,png/quality,q_80',
		  link: window.location.href,
		  success:(res)=>{
			cb(res)
		  },
		  cancel:(cancelMsg)=>{
			errorCb(cancelMsg)
		  }
		})
		// 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
		wx.updateTimelineShareData({
		  title: sharedata.title || shareOptionsDefalut.title,
		  imgUrl: (sharedata.imgUrl || shareOptionsDefalut.imgUrl) + '?x-oss-process=image/resize,w_120,m_lfit/format,png/quality,q_80',
		  link: window.location.href,
		  success:(res)=>{
			cb(res)
		  },
		  cancel:(cancelMsg)=>{
			errorCb(cancelMsg)
		  }
		})
	  });
	  wx.error((res)=>{
	    console.log('---注入失败,查看失败原因---',res)
	  });
	})
  }
}
// #endif
  1. 对工具函数简单说明下

    • isWechat 判断当前是否是微信环境
    • getWxConfig(关键) 请求后端接口,注入配置信息
    • callWexinShare 对微信分享接口的二次封装
  2. 注意事项

    • 整个wechat.js文件里最好用条件编译包裹起来【#ifdef H5、#endif】,不然打包APP后会出现报错(APP没有window对象)
    • callWexinShare函数的成功回调和失败回调参数都需要有一个默认值,不然updateAppMessageShareData的success回调中会报错‘cb is not defined’(这个当时我也没注意到,不过在onMenuShareTimeline这个接口倒不会报错,怪不得是即将废弃的接口,新接口更加规范了)

三、页面中使用

  1. 在main.js中将wechat绑定在vue全局对象上,方便后续使用
import wechat from '@/utils/wechat.js'
Vue.prototype.$wechatSdk = wechat
  1. 在App.vue中的onLaunch周期里,使用uni.addInterceptor去监听页面的每次变化

根据官方文档说的“同一个url仅需调用一次,对于变化url的SPA的web app可在每次url变化时进行调用”

onLaunch() {
  // #ifdef H5
  const naviArr = [
	'navigateTo',
	'redirectTo',
	'reLaunch',
	'switchTab',
	'navigateBack',
  ]
  for (let i of naviArr) {
	uni.addInterceptor(i, {
	  success:(e)=>{
		this.watchRouter()
	  },
	})
  }
  this.watchRouter() // 首次进入页面
  // #endif
},
  1. 然后在methods里调用callWexinShare方法
methods:{
  watchRouter() {
	if (this.$wechatSdk?.isWechat()) {  
	  this.$wechatSdk.callWexinShare()
	}
  }
}
  1. (看需求)因为项目需求需要在一些特定页面根据页面的信息配置分享内容,如作者主页、商品详情页
async getInfo() {
  const res = await api()
  this.goodDetail = res.data
  // #ifdef H5
  // 微信自定义分享
  if (this.$wechatSdk?.isWechat()) {
	this.$wechatSdk.callWexinShare({
	  title: this.goodDetail.title,
	  desc: this.goodDetail.desc,
	  imgUrl: this.goodDetail.imgUrl,
	})
  }
  // #endif
}

四、踩坑

  1. 使用uni.addInterceptor去监听页面跳转的api,忽略了浏览器的返回按钮(会出现分享的页面的配置内容还是上一个页面的),所以要在onUnload页面卸载的时候重置回默认配置
onUnload() {
  // #ifdef H5
  if (this.$wechatSdk?.isWechat()) {
	this.$wechatSdk.callWexinShare()
  }
  // #endif
},
  1. 有一种场景:A页面进入B页面,B页面调接口获取详情,然后用详情去配置分享内容,B页面进入C页面再返回B页面,不管是uni.navigateBack返回页面还是浏览器返回页面都会把分享内容重置回默认配置,这时候再分享B页面,就不是根据接口返回的内容配置的了。因为配置B页面分享内容是放在调接口的时候,所以想了两个方法解决:第一种简单粗暴,直接在onShow的时候再去调接口获取详情,这种不太友好;第二种是第一次进入页面的时候把详情信息存在本地,然后返回的时候在onShow里判断是否有详情信息,如果有则更新分享配置:
async getInfo() {
  const res = await api()
  this.goodDetail = res.data
  // #ifdef H5
  uni.setStorageSync("wxshareData", this.goodDetail)
  // 微信自定义分享
  if (this.$wechatSdk?.isWechat()) {
	this.$wechatSdk.callWexinShare({
	  title: this.goodDetail.title,
	  desc: this.goodDetail.desc,
	  imgUrl: this.goodDetail.imgUrl,
	})
  }
  // #endif
}
 onShow() {
  // #ifdef H5
  // 从上一个页面返回到这个页面的时候判断缓存,有则更新微信分享配置
  const wxshareData = uni.getStorageSync('wxshareData');
  if (wxshareData) {
    if (this.$wechatSdk?.isWechat()) {
      this.$wechatSdk.callWexinShare({
		title: wxshareData.title,
		desc: wxshareData.desc,
		imgUrl: wxshareData.imgUrl,
	  })
	}
  }
  // #endif
}
  1. 微信SDK对分享图标是有限制的!!!

图片格式:微信SDK支持的分享图标格式为JPEG、PNG格式,不支持GIF格式。
图片大小:微信SDK对分享图标的大小有限制,图片大小不能超过32KB。
图片尺寸:微信SDK对分享图标的尺寸也有限制,建议分享图标的尺寸为120px * 120px。
图片质量:为了保证分享图标的清晰度,建议分享图标的质量在80%以上。

这个是最坑的,sdk文档也没有说明,最后还是GPT上找到的!(内心os:怪不得江湖上都吐槽微信,这次算是领教了)

我的解决方案是采用oss图片压缩对图片进行压缩处理,就是在图片链接后拼接"?x-oss-process=image/resize,w_120,m_lfit/format,png/quality,q_80",详细参数可以参考oss图片缩放

五、其他


总结

以上就是我的学习分享,如果你有什么不同的看法,欢迎在评论区交流~

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
UniApp是一种基于Vue.js的跨平台开发框架,可以用于同时开发iOS、Android和Web应用。要实现微信分享到朋友圈,你可以按照以下步骤进行操作: 1. 在UniApp项目中安装并引入微信JSSDK,可以通过npm安装或者直接引入CDN链接。 2. 在项目的`main.js`文件中,使用`Vue.prototype`将微信JSSDK挂载到Vue实例上,以便在全局使用。 3. 在需要分享的页面中,调用微信JSSDK提供的接口进行分享配置和分享操作。 具体的实现步骤如下: 1. 安装微信JSSDK: ``` npm install weixin-js-sdk ``` 2. 在`main.js`中引入并挂载微信JSSDK: ```javascript import wx from 'weixin-js-sdk' Vue.prototype.$wx = wx ``` 3. 在需要分享的页面中,调用微信JSSDK提供的接口进行分享配置和分享操作。例如,在`Share.vue`组件中: ```javascript export default { mounted() { this.wxConfig() }, methods: { wxConfig() { // 获取后端提供的微信配置信息 // 这里假设后端返回的配置信息为wxConfigData const wxConfigData = { appId: 'your_appId', timestamp: 'your_timestamp', nonceStr: 'your_nonceStr', signature: 'your_signature' } // 调用微信JSSDK的config方法进行配置 this.$wx.config({ debug: false, appId: wxConfigData.appId, timestamp: wxConfigData.timestamp, nonceStr: wxConfigData.nonceStr, signature: wxConfigData.signature, jsApiList: ['onMenuShareTimeline'] // 需要使用的接口列表 }) // 配置成功后,调用微信JSSDK的ready方法 this.$wx.ready(() => { // 在ready回调中进行分享操作 this.wxShareTimeline() }) }, wxShareTimeline() { // 调用微信JSSDK的onMenuShareTimeline方法进行分享到朋友圈 this.$wx.onMenuShareTimeline({ title: '分享标题', link: '分享链接', imgUrl: '分享图片链接', success: function () { // 分享成功的回调函数 console.log('分享成功') }, cancel: function () { // 取消分享的回调函数 console.log('取消分享') } }) } } } ``` 以上就是使用UniApp实现微信分享到朋友圈的基本步骤。你可以根据自己的需求进行配置和定制化。如果有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值