微信云开发—H5链接跳转到微信小程序指定页面并传参数

1.官网下载跳转H5页面

<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>
            //微信公众号用户OPENID
            let publicOpenId = '';
            //用户联合ID
            let userUnionId = '';
            //获取路由参数
            function GetQueryString(name) {
                let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
                let r = window.location.search.substr(1).match(reg) // search,查询?后面的参数,并匹配正则
                if (r != null) {
                    return unescape(r[2])
                }
                return null
            }
            //获取用户公众号ID
            publicOpenId = GetQueryString('publicOpenId') //这个地方你连接后传参名是什么就传什么。例:www.baidu.com?id=123,所以我这里是id˝
            //获取用户联合ID
            userUnionId = GetQueryString('userUnionId') //这个地方你连接后传参名是什么就传什么。例:www.baidu.com?id=123,所以我这里是id˝


            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
                }


                //微信内打开--走微信开放标签 wx-open-launch-weapp
                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')
                    //路径动态传参
                    var path = `/pages/me/me?publicOpenId=${publicOpenId}&userUnionId=${userUnionId}`;
                    launchBtn.setAttribute('path', path);

                    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: 'wx_xxxx', // <!-- replace -->
                        timestamp: 0, // 必填,填任意数字即可
                        nonceStr: 'nonceStr', // 必填,填任意非空字符串即可
                        signature: 'signature', // 必填,填任意非空字符串即可
                        jsApiList: ['uploadImage'], // 必填,随意一个接口即可 
                        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 {
                    //手机浏览器打开--走云函数去生成UrlScheme
                    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: 'wx_xxxx', // <!-- replace -->
                        // 资源方环境 ID
                        resourceEnv: 'wx_xxxx', // <!-- 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: {
                        query: `publicOpenId=${publicOpenId}&userUnionId=${userUnionId}`,
                        action: 'getUrlScheme2',
                    },
                })
                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="">正在打开 “xxxx”...</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="">点击以下按钮打开 “xxxx”</p> <!-- replace -->
                <!-- 跳转小程序的开放标签。文档 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html -->
                <wx-open-launch-weapp id="launch-btn" username="gh_xxxx">
                    <!-- 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>

2.创建H5中指定的云函数名 'public'

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    switch (event.action) {
        case 'getUrlScheme': {
            return getUrlScheme(event.query)
        }
        case 'getUrlScheme2': {
            return getUrlScheme2(event.query)
        }
    }
    return 'ACTION传入有误'
}

async function getUrlScheme(query) {
    return cloud.openapi.urlscheme.generate({
        jumpWxa: {
            path: '/pages/login/login', //跳转的页面
            query: query, //页面接受的参数,每个参数使用 options.xxx 接收
            env_version: 'develop' //测试模式 
        },
        // 如果想不过期则置为 false,并可以存到数据库
        isExpire: false,
        // 一分钟有效期
        expireTime: parseInt(Date.now() / 1000 + 60),
    })
}

async function getUrlScheme2(query) {
    return cloud.openapi.urlscheme.generate({
        jumpWxa: {
            path: '/pages/me/me', //跳转的页面
            query: query, //页面接受的参数,每个参数使用 options.xxx 接收
            env_version: 'develop' //测试模式 
        },
        // 如果想不过期则置为 false,并可以存到数据库
        isExpire: false,
        // 一分钟有效期
        expireTime: parseInt(Date.now() / 1000 + 60),
    })
}

注意:
1.云函数创建和操作需自行百度,教程很多
2.想使用开放版测试,需指定evn_version: 'develop',默认正式版

https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html
https://www.qb5200.com/article/597613.html
https://blog.csdn.net/weixin_49045461/article/details/131964528

3.发布生效

静态网站配置:

上传写好的H5页面,访问路径:域名+html页面名+参数,外部链接需要在微信分享到手机上浏览器会带上完整参数。


image.png

image.png
云函数配置:
image.png

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容