一、问题现象
对接微信公众号,通过https://open.weixin.qq.com/connect/oauth2/authorize获取code,并在成功之后跳转回来,代码如下:
vue前端代码:
/**
* 微信支付
*/
WXPayment(item) {
let redirect_uri="https://www.xxx.cn/homeshopping/#/OrderPayRedirect";
//跳转到微信授权页面,获取code
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="
+微信公众号APPID
+"&redirect_uri="+encodeURIComponent(redirect_uri)
+"&response_type=code&scope=snsapi_base&state=订单ID#wechat_redirect";
},
微信跳转回来时,地址拼接却是下面这样:
https://www.xxx.cn/homeshopping/?code=code值&state=订单ID#/OrderPayRedirect
但其实跳转回来的地址应该是这样:
https://www.xxx.cn/homeshopping/#/OrderPayRedirect?code=code值&state=订单ID
二、解决办法
这真是一个头疼的问题,百度了很多方法,都说不要用hash模式,但不用hash模式部署到IIS服务器又会遇到各种配置问题,尝试良久无果,最终想到用一个html中转页面过渡一下
改造后的方法:
注意关注重点:OrderPayRedirect.html
/**
* 微信支付
*/
WXPayment(item) {
let redirect_uri="https://www.xxx.cn/homeshopping/OrderPayRedirect.html";
//跳转到微信授权页面,获取code
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="
+微信公众号APPID
+"&redirect_uri="+encodeURIComponent(redirect_uri)
+"&response_type=code&scope=snsapi_base&state=订单ID#wechat_redirect";
},
OrderPayRedirect.html页面具体内容如下:
<!DOCTYPE html>
<html lang="">
<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>vue移动端</title>
</head>
<body>
<script src="static/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
//alert(location.search) ;
var vsplit=GetRequest();
debugger;
var code=vsplit["code"];
var orderguid=vsplit["state"];
//alert(code) ;
window.location.href="https://www.xxx.cn/homeshopping/#/orderpay?code="+code+"&orderguid="+orderguid;
});
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
</script>
<div id="app"></div>
</body>
</html>
注意html位置要求: