[Vue function] weixin-js-sdk implements vue sharing function

weixin-js-sdk implements vue sharing function

The h5 link is shared with WeChat friends and Moments. The content of the link card can be customized
and installed with WeChat sdk

cnpm install weixin-js-sdk -S

Use to
create a new file: plugins/wechat.js

import wx from 'weixin-js-sdk'
import axios from 'axios'
let config = {
    
    
	debug: false, // 查看初始化结果,成功与否
	appId: "", //公众号的APPID
	nonceStr: "", // 生成签名的随机字符串
	timestamp: 0, // 生成签名的时间戳
	signature: "", // :微信生成的签名
	jsApiList: ["updateAppMessageShareData",'choosehXPay ','miniprogram.navigateTo',"invokeMiniprogramAPI"] // 必填,需要使用的JS接口列表,需要在项目当中使用的那些方法,比如说支付chooseWXPay,直接把方法写进jsApiList里面既可
}
export default {
    
    
	init() {
    
    
		axios({
    
    
			method: "POST",
			// url:注意,每次url变化之后都需要重新微信jssdk授权,虽然每次授权url除去#后都是一样的,但是必须这么做,微信的机制
			url: process.env.VUE_APP_GUIGUI_API_HOST + "/api/wechat/getHmcSDKConfig",
		}).then(res => {
    
    
			let configData = res.data.data
			if (configData) {
    
    
				config.appId = configData.appId
				config.nonceStr = configData.nonceStr
				config.timestamp = configData.timestamp
				config.signature = configData.signature
			}
			wx.config(config)
		})
	},
	setWechatShareInfo(link, title, desc, imgUrl, callBack) {
    
    
		wx.ready(function () {
    
     //需在用户可能点击分享按钮前就先调用
			wx.updateAppMessageShareData({
    
    
				title: title || '', // 分享标题
				desc: desc || '', // 分享描述
				link: link || '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: imgUrl || '', // 分享图标
				success: function () {
    
    
					callBack()
				}
			})
		})
	}

}

Page usage
Note: When using the WeChat custom sharing function, when there is Chinese in the sharing link, encodeURIComponent() must be performed. The
reason: the custom sharing can be successfully customized on the Android phone, but cannot be successfully shared on the iOS phone, and the Android phone Will automatically encodeURIComponent, but IOS will not.

			handleShareWechat() {
    
    
				import('@/plugins/wechat.js').then(mod => {
    
    
					let wx = mod.default
					wx.init()
					wx.setWechatShareInfo(location.href, '分享标题', '分享描述')
				})
			},

Guess you like

Origin blog.csdn.net/weixin_44590591/article/details/128220545