How to jump to the applet through a short link, or jump to an h5 page of the applet webview

theme: channing-cyan

1. Demand background:

The company needs to carry a short link by sending a text message. The user clicks on the short link to jump to a page of the applet, and then opens the webviewh5 page of the page of the applet, and then the link carries parameters.

Technology used:

Mainly use the cloud development of small programs, the relevant documents are here:
Cloud Development Documentation

Operating procedures:

1. The user clicks the short link to jump to the applet

Then open the applet

is such a process

Code flow:

1, We need an h5 routing page on the home page, which can be accessed by the address. I use the vue framework

<template>
  <div class='open-mini-wrapper'>
    <div class="page full">
      <div id="public-web-container" class="hidden">
        <p class="">Opening "Applet"...</p>
        <a id="public-web-jump-button" href="javascript:" @click="openWeapp">
          <van-button type='primary'>open applet</van-button>
        </a>
      </div>

      <div id="wechat-web-container" class="hidden" >
        <p class="">Click the button below to open the "Mini Program"</p>
        <wx-open-launch-weapp id="launch-btn" :username="originId" :path="path">
          <script type="text/wxtag-template">
            <button style="width: 200px; height: 45px; text-align: center; font-size: 17px; display: block; margin: 0 auto; padding: 8px 24px; border: none; border-radius: 4px; background-color: #07c160; color:#fff;">
              open applet
            </button>
          </script>
        </wx-open-launch-weapp>
      </div>
      <div id="desktop-web-container" class="hidden">
        <p class="">Please open the web link on your mobile phone</p>
      </div>
    </div>
  </div>
</template>

<script>
import {getQueryObject} from "@/utils";

export default {
  name: "OpenMini",
  data() {
    return {
      xxx: '', // Parameters that need to be passed
      path: '', // Jump to the path of the applet
      originId: '',//Mini Program Original ID
      resourceAppid: '', //applet appid
      resourceEnv: '' //Mini Program cloud environment id
    }
  },
  created() {
    this.xxx = getQueryObject().xxx
    const url = `https://xxx?xxx=${this.xxx}`
    this.path = 'pages/h5/h5?url=' + encodeURIComponent(url)
    this.$getWeChatParams(this.xxx, window.location.href); // For the configuration method of WeChat development function, see the bottom
  },
  mounted() {
    this.init()
  },
  methods: {
    // Prepare
    docReady(fn) {
      if (document.readyState === 'complete' || document.readyState === 'interactive') {
        fn()
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    init() {
      this.docReady(async () => {
        let ua = navigator.userAgent.toLowerCase()
        let isWXWork = ua.match(/wxwork/i) == 'wxwork'
        let isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger'
        // let isMobile = false
        let isDesktop = false
        if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {
          // isMobile = true
        } else {
          isDesktop = true
        }
        if (isWeixin) {
          let containerEl = document.getElementById('wechat-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'wechat-web-container')
          let launchBtn = document.getElementById('launch-btn')
          launchBtn.addEventListener('ready', function (e) {
            console.log('open tab ready')
          })
          launchBtn.addEventListener('launch', function (e) {
            console.log('open tab success')
          })
          launchBtn.addEventListener('error', function (e) {
            console.log('open tab fail', e.detail)
          })

        } else if (isDesktop) {
          // On the pc, a prompt will be given to guide the mobile phone to open
          let containerEl = document.getElementById('desktop-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'desktop-web-container')
        } else {
          let containerEl = document.getElementById('public-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'public-web-container')
          let c = new cloud.Cloud({
            // Mandatory, means not logged in mode
            identityless: true,
            // Resource side AppID
            resourceAppid: this.resourceAppid,
            // Resource side environment ID
            resourceEnv: this.resourceEnv,
          })

          await c.init()
          window.c = c
          await this.openWeapp()
        }
      })
    },

    async openWeapp() {
      let c = window.c
      const res = await c.callFunction({
        name: 'public',
        data: {
          action: 'getUrlScheme',
          option: {
            xxx: this.xxx,
          }
        },
      })
      location.href = res.result.openlink
    }
  }
}
</script>

<style scoped lang='scss'>
.open-mini-wrapper {
  .hidden {
    display: none;
  }

  .full {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }

  .public-web-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .public-web-container p {
    position: absolute;
    top: 40%;
  }

  .public-web-container a {
    position: absolute;
    bottom: 40%;
  }

  .wechat-web-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .wechat-web-container p {
    position: absolute;
    top: 40%;
  }

  .wechat-web-container wx-open-launch-weapp {
    position: absolute;
    bottom: 40%;
    left: 0;
    right: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .desktop-web-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .desktop-web-container p {
    position: absolute;
    top: 40%;
  }
}
</style>

The above code is the code to open the applet, but it has no effect at this time, and the cloud function needs to be configured

The cloud development service needs to be activated in the background of the applet first, and a cloud environment cloudID will be assigned at this time

Open the Mini Program Developer Tools - "Click Cloud Development to activate the static website function

Click Settings in the cloud development console,

Then click Cloud Function to configure custom security rules

public is the name of the cloud function, the rules are as follows

{
    "*": {
        "invoke": "auth != null"
    },
    "public": {
        "invoke": true
    }
}

At this time, the lack of cloud functions needs to create a new cloud function in the code

Add a new folder named cloud

Add configuration to the project.config.josn file

"cloudbaseRoot": "cloud/",

Add a new cloud function named public, and then synchronize the cloud function to the server (WeChat applet itself)

Code writing in cloud function index.js

// Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // Use the current cloud environment

// Cloud function entry function
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  switch (event.action) {
    case 'getUrlScheme': {
      return getUrlScheme(event.option)
    }
  }

  return {
    event
  }
}


async function getUrlScheme(option) {
  let query = 'xxx=' + option.xxx + '&from=yunhanshu' // The parameters that need to be carried
 

  const result = await cloud.openapi.urlscheme.generate({
    jumpWxa: {
      path: 'pages/h5/h5', // <!-- replace -->
      query: query
    },
    // If you don't want to expire, set it to false and save it to the database
    isExpire: false,
    // Valid for one minute
    expireTime: parseInt(Date.now() / 1000 + 60),
  })
  return {
    ...result,
    query
  }
}

Then sync the cloud function

At this point, the cloud function department has been developed, and the rest is to jump to the specified page path of the applet, and the final code

2, and then it is necessary to configure the function that accepts parameters in the applet

The h5.wxml part is simple because the webview

 <web-view src="{{url}}"></web-view>

h5.js only needs to accept parameters

// pages/webview/h5.js
const {
  getOpenId,
} = require('../../utils/userUtils')
Page({
  data: {
    url:''
  },
  onLoad(options) {
    // console.log(options, 'optionsaaa')
    if(options.from && options.from === 'yunhanshu') {
      const url = `https://xxx/#/?xxx=${options.xxx}`
      this.setData({
        url: url
      })
    }else {
      this.setData({
        url:decodeURIComponent(options.url)
      })
    }
  }
})

3. The function of the external package is used above

This function needs to be used in conjunction with the back-end interface, mainly to obtain parameter information such as signature, there are many on the Internet, search by yourself

const getWeChatParams = async function (agentID, path, isHidden = false) {
  if (agentID) {
    let result = await wxticket({agentID, path})
    if (result.code === S_OK) {
      if (isHidden) {
        getHiddenWeChatShare(result.data)
      } else {
        getWeChatShare(result.data)
      }
    }
  }
}

const getWeChatShare = function (params) {
  let title = shareTitle;
  let desc = shareDesc
  weChat.config({
    debug: false,
    appId: appId,
    timestamp: params.timestamp,
    nonceStr: params.nonceStr,
    signature: params.signature,
    jsApiList: ['hideMenuItems', 'onMenuShareAppMessage', 'onMenuShareTimeline'],
    openTagList:['wx-open-launch-weapp'], // Fill in the name of the open label to open the applet
  });
  weChat.ready(function () {
    // Bulk hide menu items
    weChat.hideMenuItems({
      menuList: [
        'menuItem:readMode', // reading mode
        'menuItem:share:qq',
        'menuItem:share:weiboApp',
        'menuItem:share:facebook',
        'menuItem:share:QZone'
      ]
    });
    // Monitor "Share to friends", button click, custom share content and share result interface
    weChat.onMenuShareAppMessage({
      title: title, // share title
      desc: desc, // share description
      link: params.url, // share link
      imgUrl: `${urlDomain}/logo.png` // share icon
    });
    //Monitor the "Share to Moments" button click, customize the shared content and share the result interface
    weChat.onMenuShareTimeline({
      title: title, // share title
      desc: desc, // share description
      link: params.url, // share link
      imgUrl: `${urlDomain}/logo.png` // share icon
    })
  });
}

At this point, the entire development process is over, haha, isn't it very simple.

If it is helpful, please like, comment, and add favorites, so that you can find it later. If it is not realized, you can leave a message to communicate.

Welcome to comment, like and support, this article is developed by Snail Laoshi Butterfly One-click release system release, need to contact qq 1520521891

Tags: Vue

Posted by eazyefolife on Thu, 24 Nov 2022 20:37:15 +1030