官方文档指引:开放标签说明文档 , 静态网站 H5 跳小程序
准备工作
开放标签
跳转小程序需要用到微信提供的开放标签:<wx-open-launch-weapp></wx-open-launch-weapp>
。
wx-open-launch-weapp
:用于页面中提供一个可跳转指定小程序的按钮。使用此标签后,用户在网页内点击标签按钮,即可跳转小程序。
H5通过开放标签打开小程序的场景值为「1167」。
开放对象
开放对象:
1、已认证的服务号,服务号绑定“JS接口安全域名”下的网页可使用此标签跳转任意合法合规的小程序。
2、已认证的非个人主体的小程序,使用小程序云开发的静态网站托管绑定的域名下的网页,可以使用此标签跳转任意合法合规的小程序。
版本要求
系统版本要求:
- 微信版本要求为:7.0.12 及以上
- 系统版本要求为:iOS 10.3及以上、Android 5.0及以上
- 注意:微信开发者工具暂时不支持!建议直接使用手机访问进行测试。
使用步骤
1、 绑定域名
登录 微信公众平台 进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
2、引入 jweixin.js
,需要 1.6.0
版本
在需要调用 JS
接口的页面引入如下 JS
文件:http://res.wx.qq.com/open/js/jweixin-1.6.0.js
(支持https
)。如下:
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
如需进一步提升服务稳定性,当上述资源不可访问时,可改访问:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js
(支持https
)。
备注:支持使用 AMD/CMD
标准模块加载方法加载。
jweixin.js
引入过后,当前的浏览器环境会有一个全局变量 wx
(直接wx
访问,或者window.wx、globalThis.wx
都是可以的)。但是,这个变量不能马上使用,必须将当前网页的路径(不包括#
号以及后面的路径,包括#
号前面的那个斜杠 /
)传给后端,后端根据传的路径返回给前端 appId、timestamp、nonceStr、signature
,然后根据这些参数调用 wx.config
,进行wx
的初始化,也就是下一步骤。
3、设置 wx.config
设置 wx.config
,通过 config
接口注入权限验证配置并申请所需开放标签。
与使用 JS-SDK
配置方式相同,所有需要使用开放标签的页面必须先注入配置信息,并通过 openTagList
字段申请所需要的开放标签,否则将无法使用(同一个 url
仅需调用一次)。开放标签的申请和 JS
接口的申请相互独立,是可以同时申请的。如下:
wx.config({
debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: [], // 必填,需要使用的 JS 接口列表
openTagList: ["wx-open-launch-weapp"] // 需要使用的开放标签列表 小程序跳转按钮:<wx-open-launch-weapp>,app 跳转按钮:['wx-open-launch-app']
});
4、成功验证
通过 ready
接口处理成功验证,如下:
wx.ready(function () {
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中
});
5、失败验证
通过 error
接口处理失败验证,如下:
wx.error(function (res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
});
6、初始化 config 参数
// 请求 config需要的参数
getUrlConfig({url: encodeURIComponent(window.location.href.split("#")[0])}).then(res => {
if (res.code === 100) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.data.appId, // 必填,公众号的唯一标识
timestamp: res.data.timeStamp, // 必填,生成签名的时间戳
nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
signature: res.data.signature, // 必填,签名
jsApiList: ['previewImage', 'chooseImage'],
openTagList: ['wx-open-launch-weapp'] // 需要使用的开放标签列表,例如['wx-open-launch-app']
});
wx.ready(() => {})
wx.error((error) => {})
}
})
7、vue 页面中使用
在 vue
页面中添加 wx-open-launch-weapp
标签:
<wx-open-launch-weapp
id="launch-btn"
username="gh_xxxxxxx"
:path="pagePath"
@ready="handleReadyFn"
@launch="handleLaunchFn"
@error="handleErrorFn"
>
<script type="text/wxtag-template">
<style>.btn{
width: 250px;
height: 44px;
background-color: #FFFFFF;
border-radius: 3px;
color: #ff6611;
font-size: 14px;
line-height: 44px;
text-align: center;
}</style>
<button class="btn">打开小程序</button>
</script>
</wx-open-launch-weapp>
username
:要打开的小程序原始 id
,以 gh_
开头的;
path
:要打开的小程序页面。
在 vue
模板中使用 <wx-open-launch-weapp>
时,需要在 main.js
中忽略 wx-open-launch-weapp
标签检测,如下:
Vue.config.ignoredElements = ['wx-open-launch-weapp']
否则,页面会报错找不到模板 <wx-open-launch-weapp>
。
8、html 页面中使用
在 html
页面中添加 wx-open-launch-weapp
标签:
<wx-open-launch-weapp
id="launch-btn"
username="gh_xxxxxxx"
:path="pagePath"
@ready="handleReadyFn"
@launch="handleLaunchFn"
@error="handleErrorFn"
>
<template>
<style>
.btn {
border: none;
display: block;
width: 250px;
height: 44px;
background: #FFFFFF;
border-radius: 3px;
color: #ff6611;
font-size: 14px;
line-height: 44px;
text-align: center;
}
</style>
<button class="btn">打开小程序</button>
</template>
</wx-open-launch-weapp>
9、注意事项
-
样式中不可添加 position:fixed
样式,不然微信开放标签跳转按钮不展示;
-
在普通 html
页面中,使用 <template></template>
包裹 <wx-open-launch-weapp>
标签;
-
对于 Vue
等视图框架,为了避免 template
标签冲突的问题,可使用 <script type="text/wxtag-template"><script>
进行代替,来包裹插槽模版和样式。
-
还有一种方式,不管冲突不冲突都能用的(动态生成标签内容),如下:
<!-- 用docment对象来动态的生成节点,再加到页面 -->
<template>
<div v-html="html"></div>
</template>
<script>
export default {
data () {
return {
html:'<wx-open-launch-weapp id="launch-btn" username="gh_xxxx" path="/pages/entryPage.html" @launch="handleLaunchFn" @error="handleErrorFn"><template><style>.btn { display:block;border:none;background:#FFFFFF;text-align:center;border-radius:3px;color:#ff6611;font-size:14px;font-weight:400;line-height:44px;width:250px;height: 44px; }</style><button class="btn">跳转小程序</button></template></wx-open-launch-weapp>'
}
},
created() {
},
mounted() {
},
methods: {
handleLaunchFn (e) {
console.log(e)
},
handleErrorFn(e){
console.log('fail', e.detail);
},
}
}
</script>
小程序的 web-view
不支持 wx-open-launch-weapp
,所以,在 h5
页面中使用 wx-open-launch-weapp
跳转 A
小程序时,如果将此 h5
通过 webview
的方式嵌入 B
小程序,这个功能将失效,按钮也不会展示。
10、要点总结
- 保证引入的微信
sdk
是最新的1.6.0
;
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
- 保证当前域名已经加入公众号的安全域名,否则签名会失效;
- 保证已经签名成功,并且在
IDE
上可以看到签名确实是ok;
- 如果是在
vue2.0
下,注意 template
的使用方式,会和脚手架的 template
起冲突;
<wx-open-launch-weapp id="launch-btn" username="gh_xxx" :path="pagePath" env-version="trial" @ready="handleReadyFn" @launch="handleLaunchFn" @error="handleErrorFn" style="position:absolute;top:0;left:0;right:0;bottom:0;width:250px;height:44px;">
<!-- vue 2.x写法 -->
<script type="text/wxtag-template">
<div style="display:block;border:none;background:#FFFFFF;text-align:center;border-radius:3px;
color:#28BECA;font-size:14px;font-weight:400;line-height:44px;width:250px;height: 44px;">
打开小程序
</div>
</script>
</wx-open-launch-weapp>
- 如果是在
vue3.0
下,注意 script
标签是不被允许写在页面上,要通过 v-is
来指定;
<wx-open-launch-weapp id="launch-btn" username="gh_xxx" :path="pagePath" env-version="trial" @ready="handleReadyFn" @launch="handleLaunchFn" @error="handleErrorFn" style="position:absolute;top:0;left:0;right:0;bottom:0;width:250px;height:44px;">
<!-- vue 3.0写法,vue3.0新增指令 v-is,但是v-is已在 3.1.0 中被废弃 -->
<div v-is="'script'" type="text/wxtag-template">
<div style="position:absolute;left:0;top:0;display:block;border:none;background:#FFFFFF;
border-radius:3px;color:#28BECA;font-size:14px;font-weight:400;line-height: 44px;width:100%;height:100%;">
打开小程序
</div>
</div>
</wx-open-launch-weapp>
- 如果显示出来了,但是点击无效,尝试看是否
wx-open-launch-weapp
有大小;
- 不建议在
wx-open-launch-weapp
标签内写内容。可以用相对定位来做,wx-open-launch-weapp
只是一个浮层,就盖在按钮上面;
- 当前
wx-open-launch-weapp
标签中的 Dom
只有在真机下才会显示,所以在 wx-open-launch-weapp
中写样式,实在是太麻烦了,在电脑端的浏览器、微信开发者工具、真机连接本地地址方式按钮都不会显示;这就导致了一个问题 wx-open-launch-weapp
里面的内容控制、样式调试等很难、一点样式改动就需要去部署,到真机上验证。针对这种情况,我的办法是:先不加 <template></template>
或者<script type="text/wxtag-template"><script>
,先在微信开发者工具里面调好样式,然后再加上 <template></template>
或者<script type="text/wxtag-template"><script>
。
11、完整版vue代码
<template>
<!-- <section class="jump-mini-program"> -->
<div class="jump-mini-program">
<div class="main-content">
<!-- 外部手机浏览器页面 -->
<div id="public-web-container" class="hidden">
<img class="jump-bg" src="xxx.png" alt="" />
<p id="public-web-jump-button-loading-text" class="open_tips">
<span id="public-web-jump-button-loading-icon" class="weui-primary-loading weui-primary-loading_transparent">
<i class="weui-primary-loading__dot"></i>
</span> 正在打开小程序…
</p>
<a id="public-web-jump-button" href="javascript:" class="weui-btn open_btn hidden" onclick="openWeapp()">打开小程序</a>
</div>
<!-- 微信手机浏览器页面 -->
<div id="wechat-web-container" class="hidden">
<img class="jump-bg" src="xxx.png" alt="" />
<div class="open-tag-container">
<wx-open-launch-weapp id="launch-btn" username="gh_xxx" :path="pagePath" @ready="handleReadyFn" @launch="handleLaunchFn" @error="handleErrorFn"
style="position:absolute;top:0;left:0;right:0;bottom:0;width:250px;height:44px;" env-version="trial">
<!-- vue 2.x写法 -->
<script type="text/wxtag-template">
<div style="display:block;border:none;background:#FFFFFF;text-align:center;border-radius:3px;
color:#28ca7e;font-size:14px;font-weight:400;line-height:44px;width:250px;height: 44px;">
打开小程序
</div>
</script>
</wx-open-launch-weapp>
</div>
</div>
<!-- PC浏览器页面 -->
<div id="desktop-web-container" class="hidden">
<div id="qrcode"></div>
<p class="">请在手机打开网页链接</p>
</div>
</div>
</div>
<!-- </section> -->
</template>
<script>
import wx from "weixin-js-sdk";
import QRCode from "../../../static/js/qrcode.min.js"
export default {
components: {},
name: "openminiprogram",
data () {
return {
randomCode: '',
pagePath: '/pages/home/home'
};
},
created () {
// const oScript = document.createElement('script');
// oScript.type = 'text/javascript';
// oScript.src = 'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js';
// oScript.onload = this.wxmini
// document.body.appendChild(oScript);
},
mounted () {
this.$nextTick(() => {
this.randomCode = this.getQueryVariable('code')
this.startHandle()
})
},
methods: {
/**
* 微信版本要求为:7.0.12及以上。 系统版本要求为:iOS 10.3及以上、Android 5.0及以上。
参考文档
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html#%E5%BC%80%E6%94%BE%E6%A0%87%E7%AD%BE%E8%AF%B4%E6%98%8E%E6%96%87%E6%A1%A3
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html
*/
getURLScheme () {
// 获取URLScheme,这里是固定死的,需要后端开发人员为你准备个接口或云函数返回URLScheme
// (每个独立的链接被用户访问后,仅此用户可以再次访问并打开对应小程序,其他用户无法再次通过相同链接打开该小程序;)
return new Promise((resolve, reject) => {
this.$http({
method: 'get',
url: `xxx/shortUrl/getByRandom?random=${this.randomCode}`,
}).then(response => {
const resData = response.data.mobBaseRes
if (resData.code === 100) {
resolve(resData.result)
} else {
resolve()
}
}).catch(error => {
// handle error
resolve()
}).then(() => {
// always executed
resolve()
});
})
},
// 外部手机浏览器打开URL Scheme,一般会有提示,接受打开即可
async openWeapp (onBeforeJump) {
const res = await this.getURLScheme()
//获取url scheme
const openlink = res.wxScheme
if (onBeforeJump) {
onBeforeJump()
}
if (openlink) {
location.href = openlink
}
setTimeout(() => {
window.location.href = 'xxx'
}, 3000);
},
// 使用开放标签打开小程序时调用,注入wx.config的配置信息,使用小程序云开发静态网站托管的网页可以绕过鉴权,公众号需要后端接口配合返回鉴权参数
getWXConfig () {
return new Promise((resolve, reject) => {
let url = window.location.href.split("#")[0]
let arg = encodeURIComponent(url)
this.$http({
//调用接口
method: "GET",
url: `xxx/getticket?url=${arg}`,
}).then(res => {
if (res && res.data && res.data.mobBaseRes && res.data.mobBaseRes.result) {
const { noncestr, timestamp, signature } = res.data.mobBaseRes.result
const config = {
appId: 'wxxxx', // 已认证的小程序appid或已认证的服务号appid
timestamp: timestamp, // 必填,使用小程序云开发静态网站托管的网页填任意数字即可,无须鉴权
nonceStr: noncestr, // 必填,使用小程序云开发静态网站托管的网页填任意非空字符串即可,无须鉴权
signature: signature, // 必填,使用小程序云开发静态网站托管的网页填任意非空字符串即可,无须鉴权
jsApiList: ['previewImage', 'chooseImage'],// 必填,随意一个接口即可
openTagList: ["wx-open-launch-weapp"], // 填入打开小程序的开放标签名
}
resolve(config)
} else {
resolve()
}
}).catch(err => { resolve() })
})
},
async startHandle () {
const ua = navigator.userAgent.toLowerCase()
// 企业微信
const isWXWork = ua.match(/wxwork/i) == 'wxwork'
// 微信浏览器
const 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 (isDesktop) {
// 在 pc 上则给提示引导到手机端打开
const containerEl = document.getElementById('desktop-web-container')
containerEl.classList.remove('hidden')
containerEl.classList.add('full', 'desktop-web-container')
// 生成当前页面二维码
new QRCode('qrcode', {
text: document.URL,
width: 200,
height: 200,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
});
} else if (isWeixin) {
//如果微信浏览器,通过开放标签打开小程序
const containerEl = document.getElementById('wechat-web-container')
containerEl.classList.remove('hidden')
containerEl.classList.add('full', 'wechat-web-container')
this.pagePath = `/pages/entryPage/entryPage?random=${this.randomCode}`
const config = await this.getWXConfig()
wx.config({
...config
})
wx.ready(() => {
});
// 通过error接口处理失败验证
wx.error((res) => {
console.log("wx.error", res);
// window.location.reload();
});
} else {
// 在非微信的外部手机浏览器使用URLScheme打开小程序
const containerEl = document.getElementById('public-web-container')
containerEl.classList.remove('hidden')
containerEl.classList.add('full', 'public-web-container')
var buttonEl = document.getElementById('public-web-jump-button')
var buttonLoadingEl = document.getElementById('public-web-jump-button-loading-text')
try {
// 自动执行,打开URLScheme
await openWeapp(() => {
buttonEl.classList.remove('hidden')
buttonLoadingEl.classList.add('hidden')
})
} catch (e) {
buttonEl.classList.remove('hidden')
buttonLoadingEl.classList.add('hidden')
this.jumpToAppDownloadPage()
}
}
},
handleReadyFn () {
console.log('handleReadyFn');
},
handleLaunchFn (e) {
console.log('success', e);
},
handleErrorFn (e) {
console.log('用户拒绝跳转或跳转异常', e.detail)
},
jumpToAppDownloadPage () {
setTimeout(() => {
window.location.href = 'xxx'
}, 10);
},
getQueryVariable (variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) { return pair[1]; }
}
return (false);
}
}
};
</script>
<style lang="less" scoped>
.jump-mini-program {
.hidden {
display: none;
}
.main-content {
background: linear-gradient(
180deg,
#04606b 0%,
#0c727c 65%,
#177d87 65%,
#75ced7 100%
);
height: 100vh;
}
.public-web-container {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
top: 50%;
/*偏移*/
transform: translateY(-50%);
}
.jump-bg {
width: 100%;
}
.wechat-web-container {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
top: 50%;
/*偏移*/
transform: translateY(-50%);
text-align: left;
}
.wechat-web-container p {
position: absolute;
top: 40%;
}
.open-tag-container {
width: 250px;
height: 44px;
position: relative;
}
.wechat-web-container wx-open-launch-weapp {
// display: flex;
// flex-direction: column;
// align-items: center;
// text-align: center;
}
.desktop-web-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.desktop-web-container p {
margin-top: 30px;
}
.open_btn {
width: 250px;
height: 44px;
background: #ffffff;
border-radius: 3px;
color: #28ca7e;
font-size: 14px;
line-height: 28px;
font-weight: 400;
}
.open_tips {
font-size: 14px;
font-weight: 400;
color: #ffffff;
/* opacity: 0.8; */
}
.weui-primary-loading:after,
.weui-primary-loading:before {
opacity: 1;
}
}
</style>
12、完整版html代码
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
<meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
<title>打开小程序</title>
<link rel="stylesheet" type="text/css" href="css.css" />
<!-- weui 样式 -->
<link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.1/weui.min.css">
</link>
<style>
.hidden {
display: none;
}
.page {
background: linear-gradient(180deg, #04606B 0%, #0C727C 65%, #177D87 65%, #75CED7 100%);
height: 100vh;
}
.public-web-container {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
top: 50%;
/*偏移*/
transform: translateY(-50%);
}
.jump-bg {
width: 100%;
}
.viomi-logo {
width: 102px;
text-align: center;
margin-bottom: -20px;
}
.wechat-web-container {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
top: 50%;
/*偏移*/
transform: translateY(-50%);
text-align: center;
}
.wechat-web-container p {
position: absolute;
top: 40%;
}
.wechat-web-container wx-open-launch-weapp {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.desktop-web-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.desktop-web-container p {
margin-top: 30px;
}
.open_btn {
width: 250px;
height: 44px;
background: #FFFFFF;
border-radius: 3px;
color: #28ca59;
font-size: 14px;
line-height: 28px;
font-weight: 400;
}
.open_tips {
font-size: 14px;
font-weight: 400;
color: #FFFFFF;
/* opacity: 0.8; */
}
.weui-primary-loading:after,
.weui-primary-loading:before {
opacity: 1;
}
</style>
<!-- 公众号 JSSDK -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<!-- 生成二维码 -->
<script type="text/javascript" src="./static/js/qrcode.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div class="page">
<!-- 外部手机浏览器页面 -->
<div id="public-web-container" class="hidden">
<img class="jump-bg" src="xxx.png" alt="" />
<p id="public-web-jump-button-loading-text" class="open_tips">
<span id="public-web-jump-button-loading-icon" class="weui-primary-loading weui-primary-loading_transparent">
<i class="weui-primary-loading__dot"></i>
</span> 正在打开小程序…
</p>
<a id="public-web-jump-button" href="javascript:" class="weui-btn open_btn hidden" onclick="openWeapp()">打开小程序</a>
</div>
<!-- 微信手机浏览器页面 -->
<div id="wechat-web-container" class="hidden">
<img class="jump-bg" src="xxx.png" alt="" />
<wx-open-launch-weapp id="launch-btn" username="gh_xxx" path="/pages/home/home">
<template>
<style>
button {
border: none;
display: block;
width: 250px;
height: 44px;
background: #FFFFFF;
border-radius: 3px;
color: #28ca59;
font-size: 14px;
line-height: 28px;
font-weight: 400;
}
</style>
<button>打开小程序</button>
</template>
</wx-open-launch-weapp>
</div>
<!-- PC浏览器页面 -->
<div id="desktop-web-container" class="hidden">
<div id="qrcode"></div>
<p class="">请在手机打开网页链接</p>
</div>
</div>
<script>
/*
微信版本要求为:7.0.12及以上。 系统版本要求为:iOS 10.3及以上、Android 5.0及以上。
参考文档
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html#%E5%BC%80%E6%94%BE%E6%A0%87%E7%AD%BE%E8%AF%B4%E6%98%8E%E6%96%87%E6%A1%A3
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html
*/
const getURLScheme = (path, query) => {
// 获取URLScheme,这里是固定死的,需要后端开发人员为你准备个接口或云函数返回URLScheme
// (每个独立的链接被用户访问后,仅此用户可以再次访问并打开对应小程序,其他用户无法再次通过相同链接打开该小程序;)
return new Promise((resolve, reject) => {
axios({
method: 'get',
url: `xxx/shortUrl/getByRandom?random=${getQueryVariable("code")}`,
}).then(response => {
if (response.data.mobBaseRes.code === 100) {
resolve(response.data.mobBaseRes.result.wxScheme)
} else {
resolve()
}
}).catch(error => {
// handle error
resolve()
}).then(() => {
// always executed
resolve()
});
})
}
// 外部手机浏览器打开URL Scheme,一般会有提示,接受打开即可
async function openWeapp (onBeforeJump) {
//获取url scheme
const openlink = await getURLScheme()
if (onBeforeJump) {
onBeforeJump()
}
if (openlink) {
location.href = openlink
}
setTimeout(() => {
window.location.href = 'xxx'
}, 3000);
}
// 使用开放标签打开小程序时调用,注入wx.config的配置信息,使用小程序云开发静态网站托管的网页可以绕过鉴权,公众号需要后端接口配合返回鉴权参数
const getWXConfig = async () => {
return new Promise((resolve, reject) => {
let url = window.location.href;
let ut = url.split("#");
let data = {
url: ut[0]
};
axios({
//调用接口
method: "GET",
url: `xxx/getticket?url=${data.url}`,
}).then(res => {
if (res && res.data && res.data.mobBaseRes && res.data.mobBaseRes.result) {
const { noncestr, timestamp, signature } = res.data.mobBaseRes.result
const config = {
appId: 'wxxxx', // 已认证的小程序appid或已认证的服务号appid
timestamp: timestamp, // 必填,使用小程序云开发静态网站托管的网页填任意数字即可,无须鉴权
nonceStr: noncestr, // 必填,使用小程序云开发静态网站托管的网页填任意非空字符串即可,无须鉴权
signature: signature, // 必填,使用小程序云开发静态网站托管的网页填任意非空字符串即可,无须鉴权
jsApiList: ['previewImage', 'chooseImage'],// 必填,随意一个接口即可
openTagList: ["wx-open-launch-weapp"], // 填入打开小程序的开放标签名
}
resolve(config)
} else {
resolve()
}
}).catch(err => { resolve() })
})
}
const start = async () => {
const ua = navigator.userAgent.toLowerCase()
// 企业微信
const isWXWork = ua.match(/wxwork/i) == 'wxwork'
// 微信浏览器
const 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 (isDesktop) {
// 在 pc 上则给提示引导到手机端打开
const containerEl = document.getElementById('desktop-web-container')
containerEl.classList.remove('hidden')
containerEl.classList.add('full', 'desktop-web-container')
// 生成当前页面二维码
new QRCode('qrcode', {
text: document.URL,
width: 200,
height: 200,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
});
} else if (isWeixin) {
//如果微信浏览器,通过开放标签打开小程序
const containerEl = document.getElementById('wechat-web-container')
containerEl.classList.remove('hidden')
containerEl.classList.add('full', 'wechat-web-container')
const launchBtn = document.getElementById('launch-btn')
launchBtn.addEventListener('error', function (e) {
console.log('用户拒绝跳转或跳转异常', e.detail)
})
const config = await getWXConfig()
wx.config({
...config
})
} else {
// 在非微信的外部手机浏览器使用URLScheme打开小程序
const containerEl = document.getElementById('public-web-container')
containerEl.classList.add('full', 'public-web-container')
var buttonEl = document.getElementById('public-web-jump-button')
var buttonLoadingEl = document.getElementById('public-web-jump-button-loading-text')
try {
// 自动执行,打开URLScheme
await openWeapp(() => {
buttonEl.classList.remove('hidden')
buttonLoadingEl.classList.add('hidden')
})
} catch (e) {
buttonEl.classList.remove('hidden')
buttonLoadingEl.classList.add('hidden')
setTimeout(() => {
window.location.href = 'xxx'
}, 1000);
}
}
}
start()
function getQueryVariable (variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) { return pair[1]; }
}
return (false);
}
</script>
</body>
</html>