首页 - 微信小程序

H5页面跳转小程序的3种实现方式

前言

实际开发中,小程序和H5往往有很多业务场景需要来回跳转,这里主要介绍三种跳转方式供大家参考。场景:微信小程序登录有时候需要和公众号进行绑定,获取公众号code和appid传给后台进行绑定

一、web-view标签返回小程序

1.小程序启动页面只写web-view标签跳转到授权页面。


<template>
    <web-view src="https://www.xxx.cn/auth.html">web-view>
template>

2.编写auth.html

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script type="text/javascript">
        let url = window.location.href;
        if(url.includes(code)) {
            if (wx.miniProgram) {
                wx.miniProgram.reLaunch({
                    url: `/pages/home/index?code=${url中的code}&appId=${url中的appid}`,
                    success: function() {
                        ......
                    },
                    fall: function() {
                        ......
                    }
                })
            }
        else {
            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=自己的appid&redirect_uri=还是当前页面&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
        }
    </script>

3、把auth.html放到服务器就可以测试访问,打开小程序默认进入启动页面中的webview跳转到H5,授权成功后,通过wx.miniProgram.reLaunch方法携带参数跳回小程序

二、wx-open-launch-weapp

1.编写auth.html


<div id="app">
        <wx-open-launch-weapp id="launch-btn" username="原始ID" path="赋值自己的path页面">
            <template>
                <button class="btn">跳转小程序button>
            template>
        wx-open-launch-weapp>
    div>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js">script>
    <script type="text/javascript">
        let url = window.location.href;
        //如果url中包含code,说明授权成功,开始注册微信config
        if(url.includes(code)) {
            //通过接口拿到appId,nonceStr,signature,timestamp
            wx.config({
                debug: false,
                appId,
                timestamp,
                nonceStr,
                signature,
                jsApiList: ['chooseImage', 'previewImage'], //必写,否则不显示
                openTagList: ['wx-open-launch-weapp']//必写,否则不显示
            });
        } else {
            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=自己的appid&redirect_uri=还是当前页面&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
        }
    script>

2、公众号后台配置好相应的域名和ip白名单,把auth.html放到服务器就可以测试访问,点击按钮,跳转到小程序首页(标签中的path属性),在onLoad函数中获取参数

三、URL Scheme

该接口用于获取小程序 scheme 码,适用于短信、邮件、外部网页、微信内等拉起小程序的业务场景。通过该接口,可以选择生成到期失效和永久有效的小程序码,有数量限制,目前仅针对国内非个人主体的小程序开放。

1.HTTPS 调用


POST https://api.weixin.qq.com/wxa/generatescheme?access_token=ACCESS_TOKEN

2.返回示例


{
  "msg""操作成功",
  "code": 200,
  "data": {
    "openlink""weixin://dl/business/?t=WqDMv7uIy7g"
  }
}

3.调用,微信内打开跳转的是正式版,微信外可以跳转体验版和开发板,具体通过env_version参数设置小程序版本

我这里是写个html文件通过a标签访问


<a href="weixin://dl/business/?t=WqDMv7uIy7g" rel="external nofollow" >跳转小程序a>