小程序onShareTimeline()分享朋友圈

目前小程序分享到朋友圈有以下2个限制:

a.仅支持Android平台,ios平台暂不支持
b.微信基础库限制2.11.3及以上

开发者设置分享小程序到朋友圈,有2种方式:

  1. wx.showShareMenu(),支持快速分享到朋友圈使用默认小程序标题,分享图为小程序logo,不可自定义参数。(uni-app已支持)
wx.showShareMenu({
  menus: ['shareAppMessage', 'shareTimeline'] //shareAppMessage必须得有
})
  1. onShareTimeline(),支持自定义分享到朋友圈的小程序标题、分享图,自定义query参数。(uni-app截止发文暂不支持)
//注意必须得设置允许“发送给朋友”onShareAppMessage,是设置onShareTimeline的前提,否则不支持分享到朋友圈
onShareAppMessage: () => {
},
onShareTimeline: () => {
  return {
    title: "测试小程序朋友圈分享",
    query: "id=110101&name=heyzqt",
    imageUrl: "https://example.cn/test.png"
  }
},

单页模式

用户在朋友圈打开分享的小程序页面,虽然是小程序里的一个页面,但是不会真正打开小程序,可以理解成只用来预览的一个单页。

 
Page({
	//页面的初始数据
	data:{
	},
	//自定义函数
	// 用户点击右上角分享给好友,要先在分享好友这里设置menus的两个参数,才可以分享朋友圈
	onShareAppMessage: function() {
		wx.showShareMenu({
	      withShareTicket: true,
	      menus: ['shareAppMessage', 'shareTimeline']
	    })
	},
	//用户点击右上角分享朋友圈
	onShareTimeline: function () {
		return {
	      title: '',
	      query: {
	        key: value
	      },
	      imageUrl: ''
	    }
	},
	//生命周期函数--监听页面加载
    onLoad: function(options) {
    },
})

  

项目示例

const app = getApp();
const request = require('../../utils/request.js');
const util = require('../../utils/util.js');
const cart = require('../../utils/cart.js');
Page({
  data: {
    store: null,
    productList: [],
    bannerList: [],
    pageSize: 10,
    pageNum: 1,
    isMore: true,
    floorstatus: false,
    scrollTop: 90,
    checkIndex: 0,
    update: false,
    cartLock: false,
    rotate: 68,
    isShare: '',
    shareId: '',
    shareImg:'',
    shareMsg:{},
  },
  cartMinus: function (e) {
    if (this.data.cartLock) {
      return;
    } else {
      this.data.cartLock = true;
    }
    const idx1 = e.currentTarget.dataset.index1;
    const idx2 = e.currentTarget.dataset.index2;
    const list = this.data.productList;
    let that = this;
    if (idx1 >= 0 && idx2 >= 0) {
      const product = list[idx1][idx2];
      if (product) {
        const id = product.id;
        const number = product.cartNum || 0;
        const str = "productList[" + idx1 + "][" + idx2 + "].cartNum";
        cart.minus(id, res => {
          that.data.cartLock = false;
          if (res.data.code == 200) {
            that.setData({
              [str]: number - 1 >= 0 ? number - 1 : 0
            })
            util.showCartNumber(that)
          } else if (res.data.code == 500) {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          } else {
            wx.navigateTo({
              url: '/pages/load/load',
            })
          }
        }, err => {
          that.data.cartLock = false;
        });
      }
    }
  },
  joinCart: function (e) {
    if (this.data.cartLock) {
      return;
    } else {
      this.data.cartLock = true;
    }
    const idx1 = e.currentTarget.dataset.index1;
    const idx2 = e.currentTarget.dataset.index2;
    const list = this.data.productList;
    let that = this;
    if (idx1 >= 0 && idx2 >= 0) {
      const product = list[idx1][idx2];
      if (product) {
        const id = product.id;
        const number = product.cartNum || 0;
        const str = "productList[" + idx1 + "][" + idx2 + "].cartNum";
        cart.add(id, res => {
          that.data.cartLock = false;
          if (res.data.code == 200) {
            that.setData({
              [str]: number + 1
            })
            util.showCartNumber(that)
          } else if (res.data.code == 500) {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          } else {
            wx.navigateTo({
              url: '/pages/load/load',
            })
          }
        }, err => {
          that.data.cartLock = false;
        });
      }
    }
  },
  joinCartAll: function (e) {
    if (this.data.cartLock) {
      return;
    } else {
      this.data.cartLock = true;
    }
    const idx1 = e.currentTarget.dataset.index1;
    const idx2 = e.currentTarget.dataset.index2;
    const list = this.data.productList;
    let that = this;
    if (idx1 >= 0 && idx2 >= 0) {
      const product = list[idx1][idx2];
      if (product) {
        const id = product.id;
        const number = product.cartNum || 0;
        const str = "productList[" + idx1 + "][" + idx2 + "].cartNum";
        cart.addAll(id, res => {
          that.data.cartLock = false;
          if (res.data.code == 200) {
            that.setData({
              [str]: number + res.data.data
            })
            util.showCartNumber(that)
          } else if (res.data.code == 500) {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          } else if (res.data.code == 303) {
            // 多规格跳转到详情选规格
            wx.navigateTo({
              url: '../product/product?pid=' + id + '&attr=1',
            })
          } else {
            wx.navigateTo({
              url: '/pages/load/load',
            })
          }
        }, err => {
          that.data.cartLock = false;
        });
      }
    }
  },
  toPoster: function (e) {
    let that = this;
    let banner = e.currentTarget.dataset.banner;
    //jumpType:1 跳转webview ,2 跳转当前小程序的其他页面 ,3跳转其他小程序
    if (banner.jumpType == "1") {
      wx.navigateTo({
        url: `../h5/h5?url=${banner.url}`,
      })
    } else if (banner.jumpType == "2") {
      wx.navigateTo({
        url: banner.url,
      })
    } else if (banner.jumpType == "3") {
      let params = that.getUrlkey(banner.url);
      wx.navigateToMiniProgram({
        appId: params.appId,
        path: params.path,
        extraData: {},
        envVersion: 'release'
      })
    }
  },
  getUrlkey(url) {
    let params = {};
    let arr = url.split("&");
    for (let i = 0, l = arr.length; i < l; i++) {
      let a = arr[i].split("=");
      params[a[0]] = a[1];
    }
    return params;
  },
  toSearch: function () {
    wx.navigateTo({
      url: '../search/search',
    })
  },
  toProduct: function (e) {
    let that = this;
    let pid = e.currentTarget.dataset.id;
    let isPrice = e.currentTarget.dataset.isprice;
    if (pid && isPrice == 0) {
      wx.navigateTo({
        url: '../product/product?pid=' + pid,
      })
    } else {
      wx.showToast({
        title: '敬请期待!',
        icon: 'none',
        duration: 2000
      })
    }
  },
  addCart(e) {
    let pid = e.currentTarget.dataset.id;
    let that = this;
    util.addCart(pid);
  },
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showToast({
        title: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试',
        icon: 'none'
      })
    }
  },
  getData: function () {
    let that = this;
    let pageSize = this.data.pageSize;
    let pageNum = this.data.pageNum;
    let dataList = this.data.productList;
    let index = pageNum - 1;
    let url = app.globalData.url + '/wechat/api/index/getData';
    let data = {
      "pageSize": pageSize,
      "pageNum": pageNum
    };
    let header = app.globalData.header;
    request._post(url, header, data, res => {
      if (res.data.code == 200) {
        let list = res.data.data.products;
        //let flag = list.length == pageSize;
        that.data.isMore = list.length == pageSize;
        that.setData({
          ['productList[' + index + ']']: list,
          //products: res.data.data.products,
          bannerList: res.data.data.bannerList,
          store: res.data.data.store,
          //isMore: flag
        })
      } else {
        wx.showToast({
          title: '获取数据失败',
          icon: 'none',
        })
      }
    });
  },

  checked: function (e) {
    this.setData({
      checkIndex: e.currentTarget.dataset.index
    })
  },

  getAngle: function () {
    let height = wx.getSystemInfoSync().windowHeight;
    let width = wx.getSystemInfoSync().windowWidth;
    let rotate = Math.atan(width / height * 92 / 24) / (Math.PI / 180);
    rotate = Math.round(rotate);
    this.setData({
      rotate
    })
  },
  share:function(e){
    let item=e.currentTarget.dataset.item;
    console.log('item:',item)
    this.setData({
      shareId:item.id,
      shareImg:item.image,
      item:item,
    })
  },
  getDetail: function () {
    let that = this;
    let pid = that.data.shareId;
    let url = app.globalData.url + "/wechat/api/index/detail";
    let data = {
      "pid": pid
    };
    let header = app.globalData.header;
    request._post(url, header, data, res => {
      console.log(res.data.data);
      that.setData({
        shareMsg:res.data.data
      })
    }, err => {});
  },
  elseRec:function(){
    let that = this;
    that.setData({
      isShare:!app.globalData.isShare,
      shareId:!app.globalData.shareId,
    })
    app.globalData.shareId=!app.globalData.shareId;
    app.globalData.shareId=!app.globalData.shareId;
  },
  shareCar:function(){
    let that = this;
    let productId=that.data.shareId;
    cart.add(productId, res => {
      wx.showToast({
        title: res.data.msg,
        icon:'none'
      })
      if(res.data.code==200){
        that.elseRec();
      }
    });
  },
  onLoad: function (options) {
    let that = this;
    let isShare = app.globalData.isShare;
    let shareId = app.globalData.shareId;
    that.setData({
      isShare,
      shareId
    })
    if (app.globalData.share) {
      setTimeout(function () {
        that.getData();
      }, 2500);
    }
    that.getData();
    that.getAngle();
    that.getDetail();
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });  
  },


  /**
   * 获取滚动条当前位置
   * 1. 此处利用防抖函数 减少触发次数 无论滚动多少次此函数都只执行最后一次
   * 2. 函数中加入判断,将setData的调用降到最低
   */
  onPageScroll: util.debounce(function (e) {
    if (e[0].scrollTop > 100) {
      if (!this.data.floorstatus) {
        this.setData({
          floorstatus: true
        });
      }
    } else {
      if (this.data.floorstatus) {
        this.setData({
          floorstatus: false
        });
      }
    }
  }),
  onShow: function () {
    if (this.data.update) {
      this.updateData();
    } else {
      this.data.update = true;
    }
    this.showCartNumber(this);
  },
  showCartNumber: util.throttle(function () {
    let that = this;
    util.showCartNumber(that);
  }),
  updateData: util.throttle(function () {
    let num = this.data.pageNum;
    let size = this.data.pageSize;
    let total = num * size;
    let url = app.globalData.url + '/wechat/api/index/getIndexData';
    let data = {
      "pageSize": total,
      "pageNum": 1
    };
    let header = app.globalData.header;
    request.quietly_post(url, header, data, res => {
      if (res.data.code == 200) {
        let list = res.data.data;
        for (let i = 0; i < list.length; i++) {
          this.setData({
            ['productList[' + i + ']']: list[i],
          })
        }
      }
    });
  }),
  reloadData() {
    let list = this.data.productList;
    this.data.pageNum = 1;
    for (let i = 1; i < list.length; i++) {
      this.setData({
        ['productList[' + i + ']']: [],
      })
    }
    this.getData();
  },
  onPullDownRefresh: function () {
    this.reloadData();
    wx.stopPullDownRefresh(); //停止下拉刷新
  },

  onReachBottom: function () {
    if (this.data.isMore) {
      let pageNumber = this.data.pageNum + 1;
      // this.setData({
      //   pageNum:pageNumber
      // })
      this.data.pageNum = pageNumber;
      this.getData();
    }
  },
  onShareAppMessage: function (e) {
    let that=this;
    console.log(that.data);
    
    return {
      title: "优选生活每天不一样", 
      path: `/pages/loading/loading?scene=${that.data.store.id}&isShare=true&shareId=${that.data.shareId}`, 
      imageUrl: 'http://static.fengleyouxuan.com/profile/imgs/user/share/userShare.png',
    };
  },
  onShareTimeline:function(){
    return
  }
})

  

  



原文地址:https://www.cnblogs.com/wang-sai-sai/p/13370145.html