很坑阿
在vue里面使用jssdk前端
安装jssdk: npm install weixin-js-sdk --save-dev
vue
只展现部分重要代码
const openCode = getQueryString('code') ? getQueryString('code') : ''
const tokenPromisr = new Promise((resolve, reject) => { checkOpenId({ openCode }).then(res => { resolve() }).catch(error => { reject(error) }) })
**用Promise是由于要等拿到accessToken了再继续** tokenPromisr.then(() => { jsSDK({ url }).then(res => { wechatConfig(res.data) }) })
**暂时只用了分享和支付的权限** export function wechatConfig(config) { wx.config({ debug: false, // 开启调试模式,调用的全部api的返回值会在客户端alert出来,若要查看传入的参数,能够在pc端打开,参数信息会经过log打出,仅在pc端时才会打印。 appId: config.appId, // 必填,公众号的惟一标识 timestamp: config.timeStamp, // 必填,生成签名的时间戳 nonceStr: config.nonceStr, // 必填,生成签名的随机串 signature: config.signature, // 必填,签名,见附录1 jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'chooseWXPay'] // 必填,须要使用的JS接口列表,全部JS接口列表见附录2 }) }
分享
export function groupWechatShare(data, cb, errorCb) { const img = data.pictureKeys ? data.pictureKeys[0] : '' const wechatState = store.getters.wechatState const SHARE_URL = process.env.SHARE_URL const IMG_URL = process.env.IMG_URL wx.ready(function() { // 分享到朋友圈 wx.onMenuShareTimeline({ title: data.goodsName, // 分享标题 link: SHARE_URL, // 分享连接,该连接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: IMG_URL + img, // 分享图标 success: function(res) { // 用户确认分享后执行的回调函数 // cb(res) }, cancel: function(res) { // 用户取消分享后执行的回调函数 // errorCb(res) } }) // 分享给朋友 wx.onMenuShareAppMessage({ title: data.goodsName, // 分享标题 desc: '邀请您一块儿拼团啊', // 分享描述 link: SHARE_URL, // 分享连接,该连接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: IMG_URL + img, // 分享图标 type: '', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 若是type是music或video,则要提供数据连接,默认为空 success: function(res) { // 用户确认分享后执行的回调函数 // cb(res) }, cancel: function(res) { // 用户取消分享后执行的回调函数 // errorCb(res) } }) }) }
支付
export function wexinPay(data, cb, errorCb) { wx.ready(function() { wx.chooseWXPay({ timestamp: parseInt(data.timeStamp), // 支付签名时间戳,注意微信jssdk中的全部使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 nonceStr: data.nonce_str, // 支付签名随机串,不长于 32 位 package: 'prepay_id=' + data.prepay_id, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***) signType: 'MD5', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5' paySign: data.paySign, // 支付签名 success: function(res) { // 支付成功后的回调函数 cb(res) }, fail: function(res) { errorCb(res) } }) }) wx.error(function(res) { // config信息验证失败会执行error函数,如签名过时致使验证失败,具体错误信息能够打开config的debug模式查看,也能够在返回的res参数中查看,对于SPA能够在这里更新签名。 /* alert("config信息验证失败");*/ }) }
========================npm
const url = window.location.href.split('#')[0]