WeChat applet h5 page jump applet (super detailed explanation)

h5 jump applet

Actual projects from scratch to complete h5 jump applet experience, jump methods are divided into cloud function jump and open tag jump.

Open tags are used for browsers in WeChat, while cloud function redirection can be used both externally and in WeChat.

It is recommended that students who need it read through this article first. The content is longer and more verbose.

1. No open label (wx-open-launch-weapp)

Official website link: https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html
The official website is well written, but it is not detailed enough and there are many pitfalls. The following is Example code:
Example code link: https://postpay-2g5hm2oxbbb721a4-1258211818.tcloudbaseapp.com/jump-mp.html

<html>
  <head>
    <title>打开小程序</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
    <script>
      window.onerror = e => {
    
    
        console.error(e)
        alert('发生错误' + e)
      }
    </script>
    <!-- weui 样式 -->
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.1/weui.min.css"></link>
    <!-- 调试用的移动端 console -->
    <script src="https://cdn.jsdelivr.net/npm/eruda"></script>
    <script>eruda.init();</script>
    <!-- 公众号 JSSDK -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <!-- 云开发 Web SDK -->
    <script src="https://res.wx.qq.com/open/js/cloudbase/1.1.0/cloud.js"></script>
    <script>
      function docReady(fn) {
    
    
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
    
    
          fn()
        } else {
    
    
          document.addEventListener('DOMContentLoaded', fn);
        }
      }

      docReady(async function() {
    
    
        var ua = navigator.userAgent.toLowerCase()
        var isWXWork = ua.match(/wxwork/i) == 'wxwork'
        var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger'
        var isMobile = false
        var isDesktop = false
        if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {
    
    
          isMobile = true
        } else {
    
    
          isDesktop = true
        }
        console.warn('ua', ua)
        console.warn(ua.match(/MicroMessenger/i) == 'micromessenger')
        var m = ua.match(/MicroMessenger/i)
        console.warn(m && m[0] === 'micromessenger')

        if (isWeixin) {
    
    
          var containerEl = document.getElementById('wechat-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'wechat-web-container')

          var launchBtn = document.getElementById('launch-btn')
          launchBtn.addEventListener('ready', function (e) {
    
    
            console.log('开放标签 ready')
          })
          launchBtn.addEventListener('launch', function (e) {
    
    
            console.log('开放标签 success')
          })
          launchBtn.addEventListener('error', function (e) {
    
    
            console.log('开放标签 fail', e.detail)
          })

          wx.config({
    
    
            // debug: true, // 调试时可开启
            appId: 'wxe5f52902cf4de896', 
            timestamp: 0, // 必填,填任意数字即可
            nonceStr: 'nonceStr', // 必填,填任意非空字符串即可
            signature: 'signature', // 必填,填任意非空字符串即可
            jsApiList: ['chooseImage'], // 安卓上必填一个,随机即可
            openTagList:['wx-open-launch-weapp'], // 填入打开小程序的开放标签名
          })
        } else if (isDesktop) {
    
    
          // 在 pc 上则给提示引导到手机端打开
          var containerEl = document.getElementById('desktop-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'desktop-web-container')
        } else {
    
    
          var containerEl = document.getElementById('public-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'public-web-container')
          var c = new cloud.Cloud({
    
    
            // 必填,表示是未登录模式
            identityless: true,
            // 资源方 AppID
            resourceAppid: 'wxe5f52902cf4de896',
            // 资源方环境 ID
            resourceEnv: 'postpay-2g5hm2oxbbb721a4',
          })
          await c.init()
          window.c = c

          var buttonEl = document.getElementById('public-web-jump-button')
          var buttonLoadingEl = document.getElementById('public-web-jump-button-loading')
          try {
    
    
            await openWeapp(() => {
    
    
              buttonEl.classList.remove('weui-btn_loading')
              buttonLoadingEl.classList.add('hidden')
            })
          } catch (e) {
    
    
            buttonEl.classList.remove('weui-btn_loading')
            buttonLoadingEl.classList.add('hidden')
            throw e
          }
        }
      })

      async function openWeapp(onBeforeJump) {
    
    
        var c = window.c
        const res = await c.callFunction({
    
    
          name: 'public',
          data: {
    
    
            action: 'getUrlScheme',
          },
        })
        console.warn(res)
        if (onBeforeJump) {
    
    
          onBeforeJump()
        }
        location.href = res.result.openlink
      }
    </script>
    <style>
      .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>
  </head>
  <body>
    <div class="page full">
      <div id="public-web-container" class="hidden">
        <p class="">正在打开 “小程序示例”...</p>
        <a id="public-web-jump-button" href="javascript:" class="weui-btn weui-btn_primary weui-btn_loading" onclick="openWeapp()">
          <span id="public-web-jump-button-loading" class="weui-primary-loading weui-primary-loading_transparent"><i class="weui-primary-loading__dot"></i></span>
          打开小程序
        </a>
      </div>
      <div id="wechat-web-container" class="hidden">
        <p class="">点击以下按钮打开 “小程序示例”</p>
        <!-- 跳转小程序的开放标签。文档 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html -->
        <wx-open-launch-weapp id="launch-btn" username="gh_d43f693ca31f" path="/page/component/index">
          <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;">打开小程序</button>
          </template>
        </wx-open-launch-weapp>
      </div>
      <div id="desktop-web-container" class="hidden">
        <p class="">请在手机打开网页链接</p>
      </div>
    </div>
  </body>
</html>

The code module written in pure es5 can be transformed into any architecture code. Let's talk about how to change it into your own project and pitfalls:
1. The debugging tool can be removed:

<!-- 调试用的移动端 console -->
    <script src="https://cdn.jsdelivr.net/npm/eruda"></script>
    <script>eruda.init();</script>

2. Appid replacement: how to find the id we need? Where are the replacements?
1) Log in to the WeChat public platform
insert image description here
2) After logging in, click on the name of the avatar in the upper right corner, and at the bottom of the basic settings, the appid and original id are here.
insert image description here
insert image description here
3) Replace the location

// 这里是给开放性标签准备的,第一种方式暂时用不到
 wx.config({
    
    
            debug: true, // 调试时可开启
            appId: '替换的位置', 
            timestamp: 0, // 必填,填任意数字即可
            nonceStr: 'nonceStr', // 必填,填任意非空字符串即可
            signature: 'signature', // 必填,填任意非空字符串即可
            jsApiList: ['chooseImage'], // 安卓上必填一个,随机即可
            openTagList:['wx-open-launch-weapp'], // 填入打开小程序的开放标签名
          })
 <wx-open-launch-weapp id="launch-btn" username="原始id" path="跳转页面的路径">
          <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;">打开小程序</button>
          </template>
        </wx-open-launch-weapp>
else {
    
    
          var containerEl = document.getElementById('public-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'public-web-container')
          var c = new cloud.Cloud({
    
    
            // 必填,表示是未登录模式
            identityless: true,
            // 资源方 AppID
            resourceAppid: '替换位置',
            // 资源方环境 ID
            resourceEnv: '云函数id', // 这里下面会讲
          })
          await c.init()

4) Modify the logic
insert image description here
Here, the judgment is fixed and written as false, just to make the webpage always follow the logic of the last else, and if you want to use open tags in the future, just restore it here. The code block is below.

docReady(async function() {
    
    
        var ua = navigator.userAgent.toLowerCase()
        var isWXWork = ua.match(/wxwork/i) == 'wxwork'
        var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger'
        var isMobile = false
        var isDesktop = false
        if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {
    
    
          isMobile = true
        } else {
    
    
          isDesktop = true
        }
        console.warn('ua', ua)
        console.warn(ua.match(/MicroMessenger/i) == 'micromessenger')
        var m = ua.match(/MicroMessenger/i)
        console.warn(m && m[0] === 'micromessenger')

        if (false) {
    
    
          var containerEl = document.getElementById('wechat-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'wechat-web-container')

5) Jump function modification

 async function openWeapp(onBeforeJump) {
    
    
        var c = window.c
        const res = await c.callFunction({
    
    
          name: 'test111', // 这里是创建云函数的云函数名称,下面文章有说道
          data: {
    
    
            action: 'getUrlScheme', // 这是云函数中函数名字
          },
        })
        console.warn(res)
        if (onBeforeJump) {
    
    
          onBeforeJump()
        }
        location.href = res.result.openlink
      }

3. Construction of the cloud function:
1) I have built it: the cloud function ID mentioned in the last picture in the replacement column above is the red check box in the picture. If it is
insert image description here
not built, you can go to: https://jingyan.baidu .com/article/a3aad71ac25f86f0fb0096ee.htmlJust
follow the pictures and texts step by step, so I won’t write so much here.
Click Cloud Functions, then click New Build Function:
insert image description here
insert image description here

Pay attention when filling in the cloud function name, the function name test111 is the name of the cloud function we will use !
2) When calling, the log here will display the print console content you wrote in the cloud function.
insert image description here
3) Cloud function permission, it is recommended to modify it to be accessible to all users during testing! 4) When creating, it is not necessary to create a cloud function directory. At this time, you need to create it manually. First, create a file name you like under the root directory, and then add the directory name
insert image description here
insert image description here
you created in project.config.json.
insert image description here
insert image description here
When you click on this directory, these options appear in the pop-up box. After the development is complete, you can choose to upload or not to upload the node_modules option. (This is directly sent to the online, as long as the online code does not call it, it will have no effect, feel free to use it)
insert image description here
There will be a test111 folder in this directory, then open this folder, execute npm init, and write in package.json:

{
    
    
  "name": "test111",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    
    
    "wx-server-sdk": "~2.3.2"
  }
}

Then create an index.js file and write:

// 云函数入口文件
const cloud = require('wx-server-sdk')
let page = false;
cloud.init();


// 云函数入口函数
exports.main = async (event, context) => {
    
    
  const wxContext = cloud.getWXContext();
  console.log('---------------')
  console.log(event)
  var query = {
    
    }
  if (event.query && event.query.page && event.query.page == 'showImage'){
    
    
    page = true;
    query.id = event.query.id;
  } else {
    
    
    page = false;
  }
  switch (event.action) {
    
    
    case 'getUrlScheme': {
    
     // 自定义函数名
      return getUrlScheme(page,query)
    }
  }

  return '没有找到对应的函数'
}

async function getUrlScheme(flag,param) {
    
     // 自定义函数
  console.log('-------getUrlScheme-----')
      console.log(flag)
      console.log(param)
      param = param || {
    
    };
  return cloud.openapi.urlscheme.generate({
    
    
    jumpWxa: {
    
    
      path: '',  // 跳转路径,一定是线上有的页面路径,否则会报错
      query: `id=${
      
      param.id}`, // 注意传参格式,可以不传参
    },
    // 如果想不过期则置为 false,并可以存到数据库
    isExpire: false,
    // 一分钟有效期
    expireTime: parseInt(Date.now() / 1000 + 60),
  })
}

At this point, the cloud function jump is over, if you have any questions, please comment and tell me.

2. Use open tags

Use the open label to restore the above modified logic code.
Then there are a few questions:
1. The pitfalls of the domain name:
1. The developer user must be an authenticated service-service-account (the service account can be set to the top, but the subscription account cannot), and the service account is bound to the "JS interface security domain name" Web pages can use this tag to jump to any legal and compliant applet.
2. The developer must be an authenticated non-personal Mini Program. Use the static website developed by Mini Program Cloud to host the web pages under the bound domain name. You can use this tag to jump to any legal and compliant Mini Program.
3. It must be deployed to the official server, and the test official account does not display the icon.
4. The JS interface security domain name verification must be done in the certified service account, "JS interface security domain name" and "IP white list" are required, and the IP refers to the IP of the server that obtains the WeChat signature.

Note: One of the two conditions of 1 and 2 must be met; the two conditions of 3 and 4 must be met, otherwise the button in the label will not be displayed (WeChat documents do not talk about martial arts, the writing is not clear, if you don’t pay attention, you will fall into the pit ).
Official document entry: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html#21

A few more points:
1. The WeChat developer tool, "verifyOpenTagList": [], cannot display icons. The test results of WeChat development tools and the real device may be different, so be sure to use the real device for testing. Android and ios test results may also be different, both must be tested.

2. The web-view of the applet does not support wx-open-launch-weapp.

3. jsApiList:['chooseImage', 'previewImage'] (must have, otherwise Android will not display)

4. WeChat version requirements: 7.0.12 and above. System version requirements: iOS 10.3 and above, Android 5.0 and above

Original text link: https://blog.csdn.net/chaishen10000/article/details/120712839
2: config configuration pit: the signature must be requested from the server, and the generated rules let the server see it by itself.

// 这里是给开放性标签准备的,第一种方式暂时用不到
 wx.config({
    
    
            debug: true, // 调试时可开启
            appId: '替换的位置', 
            timestamp: 0, // 必填,填任意数字即可
            nonceStr: 'nonceStr', // 必填,填任意非空字符串即可
            signature: 'signature', // 必填,服务端生成的,不能任意
            jsApiList: ['chooseImage'], // 安卓上必填一个,
            openTagList:['wx-open-launch-weapp'], // 填入打开小程序的开放标签名
          })

ps: It is best to use the online homepage test when testing small programs~

Guess you like

Origin blog.csdn.net/weixin_44265066/article/details/125673122