Skip to content

js判断微信环境

javascript
function isWeixin()
{
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true; //是微信浏览器
    } else {
    return false; //其他设备
    }

}

js跳转至微信小程序

使用开放标签跳转小程序:wx-open-launch-weapp

限制条件
  • 目前仅支持在微信内打开H5页面;

  • 已认证的服务号,服务号绑定“JS接口安全域名”下的网页可使用此标签跳转任意合法合规的小程序;

  • 已认证的非个人主体的小程序,使用小程序云开发的静态网页托管绑定的域名下的网页,可以使用此标签跳转任意合法合规的小程序。

绑定安全域名

登录微信公众平台进入【公众号设置】-->【功能设置】里设置好 “js接口安全域名”。

IP白名单设置

登录微信公众平台进入【开发】-->【基本配置】,这里填写你服务器的IP

代码

流程: 1.获取accesstoken 2.得到token后,获取js-sdk的使用签名 签名算法文档 所有 JS 接口列表 html

html
<wx-open-launch-weapp
  id="launch-btn"
  username="gh_xxxxxxxx"  //小程序原生id
  path="pages/index/index">

   <button class="btn">打开小程序</button>
</wx-open-launch-weapp>

js

js
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
    wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印
        appId: '', // 必填,公众号的唯一标识
        timestamp: , // 必填,生成签名的时间戳
        nonceStr: '', // 必填,生成签名的随机串
        signature: '',// 必填,签名
        jsApiList: [], // 必填,需要使用的JS接口列表
        openTagList: ['wx-open-launch-app'] // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
    });
    wx.ready(function () {
        // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中
    });
    wx.error(function (res) {
        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
    });

  var btn = document.getElementById('launch-btn');
  btn.addEventListener('launch', function (e) {
    console.log('success');
  });
  btn.addEventListener('error', function (e) {
    console.log('fail', e.detail);
  });
</script>

css

css
.btn{
    padding:12px
}

跳转至小程序微信官方文档

真实的案例

constroller

csharp
public async Task< IActionResult> OpenMp()
{
    string scheme = HttpContext.Request.Scheme;
    string host=HttpContext.Request.Host.ToString();
    string path = HttpContext.Request.Path;
    if(HttpContext.Request.IsHttps)
    {
        scheme = "https";
    }
    scheme = "https";
    string url = $"{scheme}://{host}{path}";
    var s = await tokenManager.UrlSignature(appId, url);
    
    TempData["signature"] = s;

    TempData["url"] = url;
    return View();
}

view

js
@model RsCode.WeChat.UrlSignatureResult
@{
    Layout = null;
    var m = TempData["signature"] as RsCode.WeChat.UrlSignatureResult;
    string url = TempData["url"] as string;
}
<!DOCTYPE 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>
    <script>eruda.init();</script>
    <!-- 公众号 JSSDK -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.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: false, // 调试时可开启
            appId: '@m.AppId', 
            timestamp: @m.Timestamp, // 必填,填任意数字即可
            nonceStr: '@m.nonceStr', // 必填,填任意非空字符串即可
            signature: '@m.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')
        }
      })

      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_353df1d8bad8" path="/pages/index/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>