vue使用sdk实现微信分享功能

357 阅读1分钟

一 丶安装weixin-js-sdk

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> //引入js文件

二丶在util文件夹下新建文件wxApi封装js

import { getOpenId } from "@/api";  // 获取签名信息/* 微信自定义分享*/
export const wxShare = (url, shareInfo) => { 
  let { title , imgUrl , desc} = shareInfo;  
  let shareLink = url; // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  let param = {    pageUrl: window.location.href.split("#")[0]  }; 
  // 获取签名信息  
  getOpenId(param).then(res => { 
    let { timestamp, nonceStr, signature, appId } = res;  
    wx.config({        
       debug: false,        
        appId: appId,        
        timestamp: timestamp, //必填,生成签名的时间戳        
        nonceStr: nonceStr, // 必填,生成签名的随机串        
        signature: signature, // 必填,签名        
        // 必填,需要使用的JS接口列表        
        jsApiList: ["onMenuShareAppMessage" , "onMenuShareTimeline"]       
     });      // 检测      
     wx.ready(() => {          
        //需在用户可能点击分享按钮前就先调用         
        // 分享给朋友         
        wx.onMenuShareAppMessage({           
            title: title, // 分享标题          
            desc: desc, // 分享描述          
            link: shareLink, // 分享链接          
            imgUrl: imgUrl, //分享图标          
            success: function () {}})          
        // 分享到朋友圈        
      wx.onMenuShareTimeline({          
            title: title, // 分享标题          
            desc: desc, // 分享描述          
            link: shareLink, // 分享链接          
            imgUrl: imgUrl, //分享图标          
            success: function () {}});      
     });    
  }) .catch(err => { console.log(err);});};

三丶在app.vue 文件使用wxApi.js

import { wxShare } from '@/util/wxApi';
mounted() {  
    // 微信分享  
    let authUrl = window.location.href;//页面链接  
    let logoStr = 'http://XXX.com/img/logo.png';//分享图标  
    setTimeout(() => {    
        wxShare(authUrl, {      
            nameCn: '标题',      
            shareDesc: '详细介绍',      
            sharePic: logoStr,    
        });}, 400);
}

四丶需要注意的

分享链接link可以做处理,但是向后端获取签名时传的url必须是当前页面的地址,也就是 window.location.href,url不能带‘#’,反正这里获取签名很严格;请求链接域名还要和公众号配置的域名一致; 不然分享过程中各种情况出现。

五丶项目入口需要在公众号平台或者自己转二维码才能分享成功如以下效果,不然分享的就是一条普通的链接