在IOS和Android网页内打开小程序指定页面
RT,废话不多说,直接上代码
前端参考链接
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}`;
},