后端生成
/// <summary>
/// 获取微信小程序的URL Scheme
public async Task<(bool isSuccess, string msg)> GetUrlScheme(string path, string query, bool isExpirable,long expireTime,string env = "release")
{
var options = new WechatApiClientOptions()
{
AppId = "",//小程序appid
AppSecret = "",//小程序appsecret
MidasAppKey = "",//米大师相关服务 AppKey,不用则不填
ImmeDeliveryAppKey = "",//即时配送相关服务 AppKey,不用则不填
ImmeDeliveryAppSecret = ""//即时配送相关服务 AppSecret,不用则不填
};
var client = new WechatApiClient(options);
var request = new CgibinTokenRequest();
var tokenResponse = await client.ExecuteCgibinTokenAsync(request);
var token = tokenResponse.AccessToken;
var request = new WxaGenerateSchemeRequest();
request.AccessToken = token;
request.MiniProgram = new WxaGenerateSchemeRequest.Types.MiniProgram();
request.MiniProgram.Path = path;
request.MiniProgram.Query = query;
request.MiniProgram.EnvironmentVersion = env;
if (isExpirable)
{
request.IsExpirable = isExpirable;
request.ExpireTimestamp = expireTime;
}
var result = await client.ExecuteWxaGenerateSchemeAsync(request);
if (result.IsSuccessful())
{
return (true, result.UrlScheme);
}
return (false, result.ErrorMessage);
}
前端跳转
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小程序跳转</title>
</head>
<body>
<div class="h1">
欢迎访问xxx小程序
</div>
<div>
<button class="login">跳转小程序</button>
</div>
</body>
</html>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function getParam(queryString, query) {
if (!queryString) {
return ""
}
var vars = queryString.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0].toLocaleLowerCase() === query.toLowerCase()) {
return pair[1];
}
}
return "";
}
var queryString = window.location.search;
if(queryString.indexOf("?")==0){
queryString= queryString.slice(1);
}
//参数需要encodeURIComponent编码
var wechatUrl = getParam(queryString,"scheme");
wechatUrl = decodeURIComponent(wechatUrl);
if(wechatUrl){
location.href = wechatUrl;
}
$(function () {
$(".login").click(function () {
if (wechatUrl) {
location.href = wechatUrl;
} else {
alert("登录失败,请微信搜索\"xxxx小程序\"查看");
}
})
})
</script>
使用
encodeURIComponent("url scheme")
//url scheme
链接写做index.html?scheme=url scheme
即可