Ability to share basic pages

For basic Page sharing, you only need to set onShareAppMessage on the Page. If the shared content is the same on each Page, you are advised to encapsulate it, for example, into the Page capability.

App({
  // Get the share card content
  getShareMessage(path) {
    return {
      title: 'Share title'.imageUrl: 'Share pictures'.path: path || 'Share default path'
    };
  },
  enhancePage() {
    const oPage = Page;
    Page = config= > oPage(Object.assign(config, {
      getShareMessage: this.getShareMessage,
    }));
  },
  onLaunch() {
    this.enhancePage(); }})Copy the code
Page({
  onShareAppMessage() {
    return this.getShareMessage(1); }})Copy the code

Users click the button to actively trigger sharing

Simply set the open-type of the button to Share to trigger the onShareAppMessage automatically.

<button open-type="share">Share button</button>
Copy the code

Get shared information in group chats

Due to privacy protection, the information shared by individuals is no longer available, but we can access the information shared by the group.

  • 1. You need to set it on the share pageticketinformation
onLoad() {
  // Configure sharing to distinguish between sharing to individuals and groups
  wx.showShareMenu({withShareTicket: true});
}
Copy the code
  • In 2.onShareAppMessageTo obtain group information
onShareAppMessage() {
  return {
    title: 'sharing'.path: '/pages/index'.success: (res) = > {
      const tickets = res.shareTickets;
      if (res.shareTickets) {
        wx.getShareInfo({
          shareTicket: tickets[0].success: (data) = > {
            console.log('Share to group:', data); }}); }else {
        console.log('Share to individuals'); }}}; }Copy the code
  • In 3.APP.onLaunchorApp.onShowTo obtain group information
App({
  onShow: (options) = > {
    wx.getShareInfo({
      shareTicket: options.shareTicket,
      success: (res) = > {
        // Request the wechat server to obtain group information}})}})Copy the code

Share it on moments

The mini program does not support direct sharing to moments, only by saving pictures and guiding users to actively send moments. The following example is a share dynamically generated image.

  1. Step 1: Material pre-download, material does not support remote URL, need to download to local (such as small program TWO-DIMENSIONAL code and book seal)
// Get the code of the applet
downloadAppCode() {
    return new Promise((resolve, rej) = > {
      wx.downloadFile({
        url: 'Background access to QR code interface'.success: (res) = > { resolve(res.tempFilePath); },
        fail: (res) = > { resolve(' '); }}); }); },// Download the file
downloadFile(url) {
  return new Promise((resolve, rej) = > {
    if (url){
      wx.downloadFile({
        url: url,
        success: (res) = >{ resolve(res.tempFilePath); }}); }else resolve();
  });
},

// Download all books and seal them locally
downloadCovers(books) {
  const urls = books.map((book) = > this.getBookCover(book.bookId));
  Promise.all([
    this.downloadFile(urls[0]),
    this.downloadFile(urls[1]),
    this.downloadFile(urls[2]),
    this.downloadFile(urls[3]),
    this.downloadFile(urls[4]),
    this.downloadAppCode(),
  ]).then((res) = > {
    const appCode = res[res.length - 1];  // Get the code address of the applet
    res = res.splice(0, res.length - 1);  // All book cover addresses
    res = res.filter(item= > item);       // Filter empty book seals
    this.setData({ localCovers: res, appCode });
    this.drawShareImg();
  });
}
Copy the code
  1. Step 2: Draw images to be saved and shared on the canvas
// Draw a shared image
drawShareImg() {
    const ctx = wx.createCanvasContext('shareImg');
    const covers = this.data.localCovers;

    / / the background
    ctx.save()
    ctx.setFillStyle('white')
    ctx.fillRect(0.0.260.370);
    ctx.restore()

    // nickname
    ctx.setFillStyle('# 111111');
    ctx.setFontSize(14);
    ctx.setTextAlign('center');
    ctx.fillText(this.data.userInfo.nickName, 130.42.260);

    // Copy wish library
    // ctx.drawImage('.. /assets/images/share/share_icon_xysw.svg', 70, 52, 120, 30);
    ctx.setFillStyle('# 111111');
    ctx.setTextAlign('center');
    ctx.font = "30px SourceHanSerifCNMedium";
    ctx.fillText(Wish Library.130.82.260);

    // Book seal frame
    ctx.setStrokeStyle('rgba (0,0,0,0.1)');
    if(covers[3]) ctx.strokeRect(21.150.42.56);
    if(covers[4]) ctx.strokeRect(197.150.42.56);
    if(covers[1]) ctx.strokeRect(51.126.60.80);
    if(covers[2]) ctx.strokeRect(149.126.60.80);
    if(covers[0]) ctx.strokeRect(91.102.78.104);

    / / book closure
    if(covers[3]) ctx.drawImage(covers[3].21.150.42.56);
    if(covers[4]) ctx.drawImage(covers[4].197.150.42.56);
    if(covers[1]) ctx.drawImage(covers[1].51.126.60.80);
    if(covers[2]) ctx.drawImage(covers[2].149.126.60.80);
    if(covers[0]) ctx.drawImage(covers[0].91.102.78.104);

    // Rectangle background
    ctx.rect(0.226.260.66);
    ctx.setFillStyle('#FFDCE7');
    ctx.fill();

    / / quotes
    ctx.drawImage('/assets/images/share/share_icon_left.png'.20.242.20.12);
    ctx.drawImage('/assets/images/share/share_icon_right.png'.220.264.20.12);

    / / qr code
    ctx.drawImage(this.data.appCode, 108.309.44.44);

    // I have received 129 books
    ctx.setFillStyle('#773A4D');
    ctx.font = "14px SourceHanSerifCNMedium";
    ctx.setTextAlign('center');
    ctx.fillText('I have received 129 books.'.130.254.260);

    // Copy every day get coins, free reading
    ctx.setFillStyle('#773A4D');
    ctx.font = "14px SourceHanSerifCNMedium";
    ctx.setTextAlign('center');
    ctx.fillText('Get coins every day, read books for free'.130.274.260);

    // copy recognition small program code
    ctx.setFillStyle('#9B9B9B');
    ctx.setFontSize(12);
    ctx.setTextAlign('left');
    ctx.fillText('Recognition of small code'.30.337.260);

    // Enter the wish library
    ctx.setFillStyle('#9B9B9B');
    ctx.font = "12px SourceHanSerifCNMedium";
    ctx.setTextAlign('left');
    ctx.fillText('Enter The Wish Library'.158.337.260);

    ctx.draw();
},
Copy the code
  1. Step 3: Download pictures to mobile phone album through wechat API
canvasToFile() {
    wx.canvasToTempFilePath({
      x: 0.y: 0.width: 260.// Canvas area width
      height: 370.// Canvas area height
      destWidth: 260 * 4.// Save the image width
      destHeight: 370 * 4.// Save the image height
      canvasId: 'shareImg'.success: (res) = > {
        this.saveImage(res.tempFilePath);
      },
      fail: function (err) {
        console.log('Failed to generate image'); }}); },// Save the image
saveImage(filePath) {
    wx.saveImageToPhotosAlbum({
      filePath:filePath,
      success: (res) = > {
        this.showSuccess('Image saved successfully');
      },
      fail: (a)= > {
        this.showError('Image failed to save to album'.'Picture cannot be saved to album, please try again later'); }}); },Copy the code
  • The local image processing considerations on the simulator are all lies
1. Do not use relative path, only use absolute path 2. Images do not support SVG Do not support SVG 3. If you use relative path, SVG, Base64, the emulator will run smoothly without flaw, but in the real machine is not drawn out!!Copy the code
Or honestly into the network pictures to download it!! Issues related to: https://developers.weixin.qq.com/community/develop/doc/00048c046f0028e62247f403651800?highLine=drawimage%2520base64Copy the code
  • The simulator is a mess
Why is it the default font on the real phone when it works on the emulator? Want to use fonts? Then let the design cut a picture for youCopy the code

Share parameter problem: New user processes scene value after scanning

The two-dimensional code will be generated with the scene value, when others scan the scene value can be resolved from the useful parameters

decodeURLParams(str) {
  const result = {}
  const params = str.split('&');
  for (let param of params) {
    const keyValue = param.split('=');
    result[keyValue[0]] = keyValue[1];
  }
  return result;
},
onLoad() {
  let  bookId = ' ';
  if (options.bookId) bookId = options.bookId;
  else if (options.scene) bookId = this.decodeURLParams(decodeURIComponent(options.scene)).bookId || ' ';
  this.setData({ bookId: bookId });
}
Copy the code