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,并設(shè)置過期時間為兩小時
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 生成小程序跳轉(zhuǎn)鏈接
*/
@AutoLog(value = "生成小程序跳轉(zhuǎn)鏈接")
@ApiOperation(value = "生成小程序跳轉(zhuǎn)鏈接", notes = "生成小程序跳轉(zhuǎn)鏈接")
@PostMapping(value = "/getAppletUrl")
public Result<?> getAppletUrl(@RequestBody UrlSchemeQueryDTO queryEntity) throws IOException {
//校驗(yàn)參數(shù),參數(shù)都傳遞了才能生成url并跳轉(zhuǎn)
if (StringUtils.isBlank(queryEntity.getDyId()) || StringUtils.isBlank(queryEntity.getJumpPath()) ||
null == queryEntity.getCoinAmt() || BigDecimal.ZERO.compareTo(queryEntity.getCoinRmb()) == 0) {
return Result.error("請求參數(shù)非法!");
}
//微信生成 URL Scheme接口地址
String httpUrl = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";
//需要跳轉(zhuǎn)的小程序路徑
String path = "pages/pay/index";
//獲取AccessToken
String AccessToken = this.getAccessToken();
//token為空,報(bào)錯返回
if (AccessToken == null) {
return Result.error("未獲取到token!");
} else {
/*token非空 拿著token去請求*/
try {
JSONObject jsonParam = new JSONObject();
JSONObject jump_wxa = new JSONObject();
//跳轉(zhuǎn)參數(shù)-跳轉(zhuǎn)的頁面路徑
jump_wxa.put("path", queryEntity.getJumpPath());
jump_wxa.put("query", "dyId=" + queryEntity.getDyId() + "&coinAmt=" + queryEntity.getCoinAmt() + "&coinRmb=" + queryEntity.getCoinRmb().toString());
//小程序環(huán)境 release:正式
jump_wxa.put("env_version", "release");
//跳轉(zhuǎn)到的目標(biāo)小程序信息。
jsonParam.put("jump_wxa", jump_wxa);
//默認(rèn)值0,到期失效的 scheme 碼失效類型,失效時間:0,失效間隔天數(shù):1
jsonParam.put("expire_type", 1);
//到期失效的 scheme 碼的失效間隔天數(shù)。生成的到期失效 scheme 碼在該間隔時間到達(dá)前有效。最長間隔天數(shù)為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 請求參數(shù)
* @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跳轉(zhuǎn)到微信小程序
wxPay() {
// ======================獲取跳轉(zhuǎn)的URL==============================
//跳轉(zhuǎn)的微信小程序的路徑,傳遞給后端進(jìn)行處理
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進(jìn)行跳轉(zhuǎn)
window.location.href=jumpUrl
}
},
fail: function (err) {
uni.showToast({
title: '打開失敗,請稍后再試!',
icon: 'none',
duration: 2000
})
}
});
},
文章來源地址http://www.zghlxwxcb.cn/news/detail-772850.html
文章來源:http://www.zghlxwxcb.cn/news/detail-772850.html
到了這里,關(guān)于H5通過Url Scheme方式傳參跳轉(zhuǎn)微信小程序的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!