前段时间做分享功能接触到新的短链分享URL Scheme
直接拿出来代码
public static Map<String, Object> getAppletUrl(String channelId,String queryName,String query,String path) throws IOException {
Map<String, Object> map = new HashMap<>();
//接口地址
String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";
EnumWxAppId enumWxAppId = EnumWxAppId.getbychannelId(channelId);
String appId = enumWxAppId.getAppID();
String secret = enumWxAppId.getAppSecret();
String httpUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
httpUrl = httpUrl + "&appid=" + appId + "&secret=" + secret;
OkHttpClient okHttpClient = new OkHttpClient();
//获取AccessToken
String AccessTokenJson = okHttpClient.newCall(new Request.Builder().url(httpUrl).get().build()).execute().body().string();
//格式化返回数据
com.alibaba.fastjson.JSONObject resultObject = com.alibaba.fastjson.JSONObject.parseObject(AccessTokenJson);
String AccessToken = resultObject.getString("access_token");
if (AccessToken == null) {
AccessToken = resultObject.getString("errmsg");
map.put("code", -1);//错误码
map.put("msg", AccessToken);//错误信息
} else {
map.put("code", 0);
try {
String content = "";
com.alibaba.fastjson.JSONObject jsonParam = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject jump_wxa = new com.alibaba.fastjson.JSONObject();
//请求参数装填
jump_wxa.put("path", path);
jump_wxa.put("query", queryName+"=" + query);
jump_wxa.put("env_version", "trial");
jsonParam.put("jump_wxa", jump_wxa);
jsonParam.put("expire_type", 1);
jsonParam.put("expire_interval", 2);
String params = jsonParam.toString();
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300 * 1000).setConnectTimeout(300 * 1000).build();
HttpPost post = new HttpPost(url + AccessToken);
post.setConfig(requestConfig);
post.setHeader("Content-Type", "application/json;charset=utf-8");
//URLEncoder.encode(name)
StringEntity postingString = new StringEntity(params, "utf-8");
post.setEntity(postingString);
CloseableHttpResponse response = httpClient.execute(post);
content = EntityUtils.toString(response.getEntity());
com.alibaba.fastjson.JSONObject resultUrl = com.alibaba.fastjson.JSONObject.parseObject(content);
String newUrl = resultUrl.getString("openlink");
map.put("url", newUrl);
System.out.println("WeChatInterfaceUtil.getWeixinUrl--" + newUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
直接get("url"),里面的url就是分享短链
可惜的是不能直接生成二维码->不能触发
我们使用的是让前端写的h5页面去触发短链
稍微封装处理一下就可以用,参数的话目前我用到的确实能够获取到,path是需要跳转的小程序功能页面,原理就像是点击小程序右上角三个点是一样的
短链的使用时间还没清楚,但是肯定不是永久的
我们项目里面有多个微信小程序公用,所以channelId是区分他们渠道的概念,其他代码都是开源的