H5网页跳转微信小程序

官方文档

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html

适用于微信浏览器、外部浏览器打开小程序。

需要的工具和资料

微信开发者工具、非个人主体并且已认证的小程序

步骤

打开微信开发者工具申请云开发

购买云开发

购买成功后会有一个云开发ID,这个很重要后面会用到

然后点击更多申请静态网站

如果没有的静态网站这个选项需要到腾讯云后台开通,大概需要几分钟的样子

下一步需要创建一个云开发的小程序

创建成功后应该会有这样的一个文件夹

这个就是云函数调用的库。

如果目前的项目是传统的小程序项目那么需要转成云开发的小程序的步骤是

在目录内创建一个cloudfunctions的文件夹

然后打开

project.config.json的文件,添加以下语句

如果你的账号已经开通了云开发,那么开发者工具会把cloudfunctions去自动绑定云开发。

然后在app.js中添加以下语句。

curr_env这个变量就是,云开发的环境Id

然后查看官方文档,下载H5跳小程序的云函数示例代码。

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html#:~:text=%3A-,%E7%82%B9%E5%87%BB%E4%B8%8B%E8%BD%BD,-%E6%96%B0%E5%BB%BA%E4%B8%80%E4%B8%AA%E4%BA%91

下载之后应该有下面的两个文件夹

打开clouldfunctions 可以看到里面的public文件夹

将public文件夹拷贝到 项目小程序cloudfunctions文件夹下

打开index.js 文件

填入你要跳转小程序的页面,

改好之后,然后选中public文件右键

选中在内建终端中打开

填入命令npm install

安装完成后

再次选中public文件夹右键

点击:上传并部署:不上传node_modules 这个选项

打开云开发环境查看部署是否成功。

查看是否部署成功

下一步添加静态网站网页

看官方文档的示例代码

<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
        }

        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: '小程序 AppID', // <!-- replace -->
            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: '小程序 AppID', // <!-- replace -->
            // 资源方环境 ID
            resourceEnv: '云开发环境 ID', // <!-- replace -->
          })
          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> <!-- replace -->
        <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> <!-- replace -->
        <!-- 跳转小程序的开放标签。文档 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html -->
        <wx-open-launch-weapp id="launch-btn" username="小程序原始账号 ID(gh_ 开头的)" path="要跳转到的页面路径"> <!-- replace -->
          <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>

官方代码需要改的的地方有以下两处

  wx.config({
            // debug: true, // 调试时可开启
            appId: '小程序 AppID', // <!-- replace 填入你要跳转的小程序的APPId -->
            timestamp: 0, // 必填,填任意数字即可
            nonceStr: 'nonceStr', // 必填,填任意非空字符串即可
            signature: 'signature', // 必填,填任意非空字符串即可
            jsApiList: ['chooseImage'], // 必填,随意一个接口即可 
            openTagList:['wx-open-launch-weapp'], // 填入打开小程序的开放标签名
          })
 var c = new cloud.Cloud({
            // 必填,表示是未登录模式
            identityless: true,
            // 资源方 AppID
            resourceAppid: '小程序 AppID', // <!-- 填入你要跳转的小程序的APPId replace -->
            // 资源方环境 ID
            resourceEnv: '云开发环境 ID', // <!-- 填入你自己的云开发的环境Id replace -->
          })
   <wx-open-launch-weapp id="launch-btn" username="小程序原始账号 ID(gh_ 开头的) 打开你的微信小程序管理平台 在设置中可以找到 你的小程序原始账号 填入即可" path="要跳转到的页面路径"> <!-- replace -->
          <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>

下一步将改好的静态index.html 上传到云开发环境中

 上传成功后就可以冲网络配置中查看测试域名访问就行了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是实现 H5 网页跳转微信小程序的完整代码: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>跳转小程序</title> </head> <body> <button onclick="jumpToMiniProgram()">跳转微信小程序</button> <script> // 小程序的 appid var appid = '小程序的appid'; // 跳转小程序的页面路径 var path = '/pages/index/index'; // 监听“跳转小程序”的按钮点击事件 function jumpToMiniProgram() { // 判断是否在微信浏览器中打开 if (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger') { // 如果在微信浏览器中打开,则使用微信 JS-SDK 跳转 // 获取微信 JS-SDK 的配置信息 var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://yourserver/getJsSdkConfigInfo.php?url=' + encodeURIComponent(location.href.split('#')[0]), true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText); if (data && data.appId) { // 配置微信 JS-SDK 的权限验证参数 wx.config({ debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: ['checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard', 'openLocation', 'onMenuShareTimeline', 'onMenuShareAppMessage'] }); // 配置微信 JS-SDK 的权限验证成功后的回调函数 wx.ready(function () { // 调用微信 JS-SDK 的跳转小程序接口 wx.miniProgram.navigateTo({ appId: appid, path: path, extraData: { // 携带的参数 key1: 'value1', key2: 'value2' }, success: function () { // 跳转成功的回调函数 } }); }); } } }; xhr.send(); } else { // 如果没有在微信浏览器中打开,则提示用户在微信中打开 alert('请在微信中打开!'); } } </script> <script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script> </body> </html> ``` 需要注意的是,该代码需要在微信公众平台中进行配置,具体可以参考 [微信官方文档](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_JS-SDK.html)。同时,该代码需要在服务器中进行部署,具体可以参考 [微信官方文档](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Platform.html)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值