一个微信公众号的外链网页,使用angular
做成了单页应用,目前碰到了 微信网页授权 和 调用 js sdk 的问题
据我所目前所知,调用了微信授权后,单页应用的入口 url 会长成这样(假定域名为:example.com
):
①http://example.com?code=aaabbb/#/home
或者(启用了html5 mode
) 长成这样:
②http://example.com/home?code=aaabbb
?code=aaabbb
, 是微信授权后重定向时填充的,有了这个才能进一步去获取用户信息,参见 微信开发文档 > 获取code
至此,还不会出现问题
由于Android微信客户端不支持pushState的H5新特性,url②废弃(亲测,确实不能通过验证),所以入口url是这样:
http://example.com?code=aaabbb/#/home
现在问题来了,如果没有?code=aaabbb
就能通过签名验证, 然后成功调用 js sdk,但实际情况是:如果需要授权?code=aaabbb
必然存在,签名验证必定失败。那么到底如何做到授权和调用sdk均可用???
我目前的想法和做法是:微信授权重定向到
http://example.com?code=aaabbb/#/home
后,拿到code,然后再location.href = http://example.com/#/home
。这样做是能拿到用户信息,并且成功调用sdk,但问题是每次进入应用,会刷新两次,这样用户体验极差,而且有强迫症的我也接受不了。
请教各位给个靠谱的方案
黄舟2017-05-15 17:14:10
Pure front-end cannot be implemented. You can only configure the domain name of the authorization callback page to the backend server, and then redirect it from the backend
PHPz2017-05-15 17:14:10
You can use indexOf() to get the code value
var url = 'http://example.com?code=aaabbb/#/home';
var n = url.indexOf('code=')+5;
var m = url.indexOf('/#');
var code = url.substr(n, m-1);
This way you can get the code value
phpcn_u15822017-05-15 17:14:10
Pure front-end cannot be implemented. It just so happens that I have recently done a similar project, which also used angularjs and implemented a single-page program through angular-route.js.
Call the background interface through ajax in a single page program (index.html),
If successful, return: {status:true,...}
If not logged in and fail, return: {status:falst,next:'login',errmsg :'Error'}
Other errors returned: {status:falst,next:'Next operation',errmsg:'Error'}
If the return status result.status==false, result.next=='login':
case "login":
$http.get($api.callback($api.login)).success(function(val){
//通过后台返回 授权地址
location.href = val.loginUrl;
});
return;
Authorize to jump to wxlogin.php. After verifying that the login is successful, after setting the SESSION, jump to the single-page program (index.html)
The program will continue to call the interface. Because you have already logged in, it returns: {status:true ,...}
PHP中文网2017-05-15 17:14:10
How should this be solved? The author will post the answer to solve it. I am going to use Vue to develop WeChat too