客户有需求,要短信或者其它场景中的链接静态H5页面,触发打开自家的小程序,官方也提供了 静态网站 H5 跳小程序技术文档(https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html ),不过里面只描述跳转到小程序本身绑定的云开发环境,那么是多个小程序共享的云开发环境如何实现跳转呢,该文档并没有说。
为每个小程序购买一个云开发环境当然是可以,然而,成本似乎似乎太高,不合算,为了给客户节省成本,就给一个小程序买了云开发环境,按照跨账号环境共享设置,实现共享给同主体下的不同小程序(参考:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/resource-sharing/)。
接下来我把最终结果和解决方案,贴出来共享。
场景:首先同公司名下有4个小程序:A、B、C、D,只为A小程序购买了最基础的云开发环境19块,开通静态网站,添加跨账号共享功能,实现访问同一个静态H5页面携带不同参数,打开B、C、D不同小程序的指定页面,无论是微信里还是在手机浏览器均可以跳转。
实现代码:
1、云函数public编写(参考并改进 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html )
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
switch (event) {
case 'getUrlScheme': {
return getUrlScheme(event)
}
}
return 'action not found'
}
async function getUrlScheme(event) {
if(event.appid) {
var clb = cloud.openapi({ appid: event.appid });
} else{
var clb = cloud.openapi;
}
return clb.urlscheme.generate({
jumpWxa: {
path: event.path,
query: event.query,
},
// 如果想不过期则置为 false,并可以存到数据库
isExpire: false,
// 一分钟有效期
expireTime: parseInt(Date.now() / 1000 + 60),
})
}
2、静态H5页面:jump.html
<html>
<head>
<title>H5打开小程序</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>
<!-- 调试用的移动端 console -->
<!-- <script src="https://cdn.bootcss.com/eruda/1.2.4/eruda.min.js"></script> -->
<!-- <script>eruda.init();</script> -->
<script>
function getQueryParam(key) {
const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
const r = window.location.search.substr(1).match(reg);
if (r != null) {
return decodeURI(r[2]);
}
return null;
}
//设置 资源环境ID以及绑定的appid
var resAppId = '环境宿主Appid';// <!-- replace -->
var resEnv = '资源环境ID'; // <!-- replace -->
//资源方其它小程序组【AppID,原始id,名称,缺省打开路径】
var appIDs = [
['wxe6ddf673521da8f0','gh_e4025e37c422','小程序A','pages/webview'], // <!-- replace -->
['wxb1abf1b1fe25f8c6','gh_a4cbe6b9f17f','小程序B',''], // <!-- replace -->
['wx24911b4d9b6971c9','gh_e544c578a3ef','小程序C',''], // <!-- replace -->
['wx6fecac42503a957b','gh_81a6106a84ce','小程序D',''] // <!-- replace -->
];
//////////////////////////////
var launchIdx = getQueryParam('id') || 0;
var pagepath = launchIdx== 0 ? appIDs[launchIdx][3] : "";
pagepath = pagepath ? pagepath+(getQueryParam('url') ? "?url="+encodeURIComponent(getQueryParam('url')):"") : "";
pagepath = pagepath ? pagepath : (getQueryParam('page') ? getQueryParam('page'):"");
</script>
<!-- weui 样式 -->
<link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.1/weui.min.css" />
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="https://res.wx.qq.com/open/js/cloudbase/1.1.0/cloud.js"></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:25%}.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>正在唤起微信小程序...</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">
<script>
document.write('<p>请点击下方按钮</p>');
document.write('<wx-open-launch-weapp id="launch-btn" username="'+appIDs[launchIdx][1]+'" path="'+pagepath+'">');
document.write(' <template><button style="width: 240px; 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>');
document.write('</wx-open-launch-weapp>');
</script>
</div>
<div id="desktop-web-container" class="hidden"><p class="font-size:26px;">请在手机上打开本链接</p></div>
</div>
<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 = isDesktop = false;
if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {
isMobile = true
} else {
isDesktop = true
}
var isAndroid = ua.indexOf('android') > -1 || ua.indexOf('Adr') > -1;
var isOS = ua.indexOf('iPhone') > -1 || ua.indexOf('iPad') > -1 || ua.indexOf('Mac') > -1;
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: appIDs[launchIdx][0], // <!-- 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,
resourceAppid: resAppId, // 资源方宿主 小程序的AppID
resourceEnv: resEnv, // 资源方环境ID
})
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) {
console.log('error',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',
appid: appIDs[launchIdx][0],
path : pagepath
},
})
if (onBeforeJump) {
onBeforeJump();
}
location.href = res.result.openlink;
}
</script>
</body>
</html>
调用方式:https://xxxx.xxx.xxx/jump.html?id=1&path=my/xwt-apply/xwt-apply (修改成你云环境静态网页的域名)
id=1 表示jump.html页面中小程序B,path 表示小程序B中的具体页面。
你可以尝试修改成自己的,实现传参跳转到不同小程序页面。希望对你有帮助!