1.获取微信access_token并生成Url Scheme
@Slf4j
@Api(tags = "微信模块")
@RestController
@RequestMapping("/weChat")
public class WeChatController {
@Autowired
private WeChatService weChatService;
@Autowired
private RedisUtil redisUtil;
@Value("${wxConfig.app-id}")
private String AppID;
@Value("${wxConfig.app-secret}")
private String AppSecret;
/**
* @return {@link String}
* @author macro
* @description 获取微信小程序token
*/
@AutoLog(value = "获取微信小程序token")
@ApiOperation(value = "获取微信小程序token", notes = "获取微信小程序token")
@GetMapping(value = "/getAccessToken")
public String getAccessToken() throws IOException {
//1.先判断redis有没有
if (redisUtil.hasKey("access_token")) {
//redis有直接返回
return redisUtil.get("access_token").toString();
} else {
//2.redis没有
/*2.1请求微信 获取token*/
String httpUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
httpUrl = httpUrl + "&appid=" + AppID + "&secret=" + AppSecret;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(httpUrl);
CloseableHttpResponse res = client.execute(httpGet);
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject.containsKey("access_token")) {
String accessToken = jsonObject.getString("access_token");
//放入redis,并设置过期时间为两小时
redisUtil.set("access_token", accessToken);
redisUtil.expire("access_token", 2 * 60 * 60);
return accessToken;
} else {
return null;
}
}
}
/**
* @return {@link Map< String, Object>}
* @author macro
* @description 生成小程序跳转链接
*/
@AutoLog(value = "生成小程序跳转链接")
@ApiOperation(value = "生成小程序跳转链接", notes = "生成小程序跳转链接")
@PostMapping(value = "/getAppletUrl")
public Result<?> getAppletUrl(@RequestBody UrlSchemeQueryDTO queryEntity) throws IOException {
//校验参数,参数都传递了才能生成url并跳转
if (StringUtils.isBlank(queryEntity.getDyId()) || StringUtils.isBlank(queryEntity.getJumpPath()) ||
null == queryEntity.getCoinAmt() || BigDecimal.ZERO.compareTo(queryEntity.getCoinRmb()) == 0) {
return Result.error("请求参数非法!");
}
//微信生成 URL Scheme接口地址
String httpUrl = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";
//需要跳转的小程序路径
String path = "pages/pay/index";
//获取AccessToken
String AccessToken = this.getAccessToken();
//token为空,报错返回
if (AccessToken == null) {
return Result.error("未获取到token!");
} else {
/*token非空 拿着token去请求*/
try {
JSONObject jsonParam = new JSONObject();
JSONObject jump_wxa = new JSONObject();
//跳转参数-跳转的页面路径
jump_wxa.put("path", queryEntity.getJumpPath());
jump_wxa.put("query", "dyId=" + queryEntity.getDyId() + "&coinAmt=" + queryEntity.getCoinAmt() + "&coinRmb=" + queryEntity.getCoinRmb().toString());
//小程序环境 release:正式
jump_wxa.put("env_version", "release");
//跳转到的目标小程序信息。
jsonParam.put("jump_wxa", jump_wxa);
//默认值0,到期失效的 scheme 码失效类型,失效时间:0,失效间隔天数:1
jsonParam.put("expire_type", 1);
//到期失效的 scheme 码的失效间隔天数。生成的到期失效 scheme 码在该间隔时间到达前有效。最长间隔天数为30天。is_expire 为 true 且 expire_type 为 1 时必填
jsonParam.put("expire_interval", 2);
String params = jsonParam.toString();
//请求微信接口,获取url
JSONObject resultUrl = getUrlScheme(httpUrl, AccessToken, params);
//请求微信接口,生成失败,返回错误码及错误信息
if (!resultUrl.getString("errcode").equals("0")) {
return Result.error(resultUrl.getString("errcode"), resultUrl.getString("errmsg"));
}
/*请求成功 返回url*/
String newUrl = resultUrl.getString("openlink");
return Result.ok(newUrl);
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* @param httpUrl 微信接口的url
* @param accessToken token
* @param params 请求参数
* @author: macro
* @description: 请求URL Scheme接口,获取url
* @return: com.alibaba.fastjson.JSONObject URL
**/
private JSONObject getUrlScheme(String httpUrl, String accessToken, String params) throws IOException {
String content;
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(300 * 1000)
.setConnectTimeout(300 * 1000)
.build();
HttpPost post = new HttpPost(httpUrl + 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());
JSONObject resultUrl = JSONObject.parseObject(content);
return resultUrl;
}
}
2.前端获取Url Scheme跳转到微信小程序
wxPay() {
// ======================获取跳转的URL==============================
//跳转的微信小程序的路径,传递给后端进行处理
this.info.jumpPath="pages/pay/index"
/*获取URL*/
let jumpUrl=''
uni.request({
url: configService.apiUrl + this.url.getAppletUrl,
method: 'POST',
data: this.info,
success: (result) => {
if(result.data.success){
jumpUrl=result.data.result
//获取到URL进行跳转
window.location.href=jumpUrl
}
},
fail: function (err) {
uni.showToast({
title: '打开失败,请稍后再试!',
icon: 'none',
duration: 2000
})
}
});
},
文章来源地址https://www.toymoban.com/news/detail-772850.html
文章来源:https://www.toymoban.com/news/detail-772850.html
到了这里,关于H5通过Url Scheme方式传参跳转微信小程序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!