小程序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
  }
})

  

 

  




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM