H5唤醒微信小程序指定页面

在IOS和Android网页内打开小程序指定页面

RT,废话不多说,直接上代码

前端参考链接

微信开发者文档,以及示列html
微信公众号文档

JAVA控制器

@Controller
@RequestMapping("/html")
public class HtmlController <{>
    @Autowired
    private AdminWeixinService adminWeixinService;

    /**
     * 分享小程序
     * @param path 小程序path
     * @param env_version 默认值"release"。要打开的小程序版本。正式版为"release",体验版为"trial",开发版为"develop",仅在微信外打开时生效。
     * @param model model
     * @return String
     */
    @GetMapping("/share-link")
    public String shareLink(@RequestParam("path") String path, @RequestParam(value = "env_version",required = false) String env_version, Model model) throws UnsupportedEncodingException <{>
        //获取appid和secret
        WxAppConfigVo vo = adminWeixinService.byType(AppTypeEnum.BUYER.getCode());
        //请求微信TOKEN
        JSONObject param = new JSONObject();
        param.put("grant_type","client_credential");
        param.put("appid",vo.getAppid());
        param.put("secret",vo.getSecret());
        String token = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", param, new JSONObject(), JSONObject.class, JSONObject::parseObject).getString("access_token");

        JSONObject param1 = new JSONObject();
        JSONObject jump = new JSONObject();
        if (path.contains("?"))<{>
            String[] pathArray = path.split("\\?");
            jump.put("path",pathArray[0]);
            jump.put("query",pathArray[1]);
        <}>else <{>
            jump.put("path",path);
        <}>
        if (StringUtils.isNotBlank(env_version))<{>
            jump.put("env_version",env_version);
        <}>
        param1.put("jump_wxa",jump);
        param1.put("is_expire",true);
        param1.put("expire_type",0);
        param1.put("expire_interval",100);
        String openLink = HttpUtils.sendPost("https://api.weixin.qq.com/wxa/generatescheme?access_token=" + token,param1,new JSONObject(),JSONObject.class,JSONObject::parseObject).getString("openlink");

        model.addAttribute("openLink", openLink);
        return "shareLink";
    <}>
<}>

shareLink.html,这个是放在服务器上

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<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>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.1/weui.min.css"></link>

    <script th:inline="javascript">
        const openLink = [[${openLink}]];
        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;
            }

            if (isWeixin) {
                //是微信浏览器替换这里
                location.href = openLink;
            } 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')
            }
        })

        function openWeapp() {
            location.href = 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">
        <img style="width: 100vw;height: 380px;display: block;"  src="https://cbte.obs.cn-south-1.myhuaweicloud.com/1/57/2022/07/27/20220727_0a0d3dc50df5e0429b0aa810456bc638fefb.png">
        <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="desktop-web-container" class="hidden">
        <p class="">请在手机打开网页链接</p>
    </div>
</div>
</body>
</html>

    /**
     * 分享小程序
     * @param path 小程序path
     * @param env_version 默认值"release"。要打开的小程序版本。正式版为"release",体验版为"trial",开发版为"develop",仅在微信外打开时生效。
     * @param model model
     * @return String
     */
    @GetMapping("/share-link")
    public String shareLink(@RequestParam("path") String path, @RequestParam(value = "env_version",required = false) String env_version, Model model) throws UnsupportedEncodingException {
        //获取appid和secret
        WxAppConfigVo vo = commonRemoteAdminWeixinService.byType(AppTypeEnum.BUYER.getCode());
        //请求微信TOKEN
        JSONObject param = new JSONObject();
        param.put("grant_type","client_credential");
        param.put("appid",vo.getAppid());
        param.put("secret",vo.getSecret());
        String token = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", param, new JSONObject(), JSONObject.class, JSONObject::parseObject).getString("access_token");

        JSONObject param1 = new JSONObject();
        JSONObject jump = new JSONObject();
        if (path.contains("?")){
            String[] pathArray = path.split("\\?");
            jump.put("path",pathArray[0]);
            jump.put("query",pathArray[1]);
        }else {
            jump.put("path",path);
        }
        if (StringUtils.isNotBlank(env_version)){
            jump.put("env_version",env_version);
        }
        param1.put("jump_wxa",jump);
        param1.put("is_expire",true);
        param1.put("expire_type",0);
        param1.put("expire_interval",100);
        String openLink = HttpUtils.sendPost("https://api.weixin.qq.com/wxa/generatescheme?access_token=" + token,param1,new JSONObject(),JSONObject.class,JSONObject::parseObject).getString("openlink");

        model.addAttribute("openLink", openLink);
        return "shareLink";
    }

分享到朋友圈使用代码

			uni.share({
					provider: 'weixin',
					type: 0,
					scene: 'WXSenceTimeline',
					href: this.getWeAppHttps(),
					title: this.productInfo.productName || '',
					imageUrl: this.productInfo.productIndexImg,
					success: function(res) {
						console.log('success:' + JSON.stringify(res));
					},
					fail: function(err) {
						console.log('fail:' + JSON.stringify(err));
					}
			});
			//生成小程序https链接
		getWeAppHttps() {
			const baseURL = 'https://xxxx.cn';
			const { sellerPrice, productId, skuId, productName } = this.productInfo;
			const appid = getApp().globalData.appId;
			const memberId = uni.getStorageSync('memberId');
			const query = {
				appid,
				path: `subPackages/goodDetails/productDetail?pid=${memberId}&productId=${productId}&skuId=${skuId}&share=true`,
				env_version: 'release' //默认值"release"。正式版为"release",体验版为"trial",开发版为"develop",仅在微信外打开时生效。
			};
			const pathURI = encodeURIComponent(query.path);
			console.log(`${baseURL}/admin/html/share-link?path=${pathURI}&env_version=${query.env_version}`);
			return `${baseURL}/admin/html/share-link?path=${pathURI}`;
		},

完结撒花

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值