Vue 微信小程序 分享到朋友圈

2020-07-20  本文已影响0人  squidbrother
概述

分享到朋友圈

代码

安装 axios
安装 weixin-js-sdk

import axios from 'axios'
import wx from "weixin-js-sdk";

请求数据

const BASE_API = 'http://www.xxx.com/student/mobile';
const reqWx = () => ajax(BASE_API + '/works/signature', '', 'GET');

function ajax (url, data={}, type='GET') {

  return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
    let promise
    if (type === 'GET') {
      // 准备url query参数数据
      let dataStr = '' //数据拼接字符串
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      // 发送get请求
      promise = axios.get(url, data)
    } else {
      // 发送post请求
      promise = axios.post(url, data)
    }
    promise.then(function (response) {
      // 成功了调用resolve()
      resolve(response.data)
    }).catch(function (error) {
      //失败了调用reject()
      reject(error)
    })
  })
}

//某个生命周期函数....
mounted(){
    this.wxRegister();
},
methods: {
    wxRegister() {
  var that = this;
  // 获取签名
  reqWx().then(function(response){
      // console.log(response);
      wx.config({
        debug: false, // 开启调试模式
        appId: response.data.appId, // 必填,公众号的唯一标识
        timestamp: response.data.timestamp, // 必填,生成签名的时间戳
        nonceStr: response.data.nonceStr, // 必填,生成签名的随机串
        signature: response.data.signature, // 必填,签名,见附录1
        jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
      });

      wx.checkJsApi({
        jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"], // 需要检测的JS接口列表
        success: function(res) {}
      });

      wx.ready(function() {
        //需在用户可能点击分享按钮前就先调用
        wx.updateAppMessageShareData({
          title: '标题', // 分享标题
          desc: '描述', // 分享描述
          link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: '图片地址', // 分享图标
          success: function(){
            //设置成功
          }
        });
        wx.updateTimelineShareData({
          title: '标题', // 分享标题
          desc: '描述', // 分享描述
          link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: '图片地址', // 分享图标
          success: function() {
            //设置成功
          }
        });
      });
    })
    .catch(function(error) {
      console.log(error);
    });
}
}
上一篇下一篇

猜你喜欢

热点阅读