微信oauth2网页授权code过期

来源:互联网 发布:淘宝指纹支付设置方法 编辑:程序博客网 时间:2024/04/29 06:38

最近开发微信客户端项目时遇到code返回码请求两次,导致获取openid失败的情况,

特此一记帮助看到的同学节约一点点的时间,引用微信文档的一段说明(详细参考点击):

用户同意授权,获取code

在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认带有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
参考链接(请在微信客户端中打开此链接体验)Scope为snsapi_basehttps://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=http%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirectScope为snsapi_userinfohttps://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
关键点请注意红色的地方,个人猜测可能微信内部有针对appid、redirecturi以及state做缓存机制优化处理,导致同一账号修改OAuth2.0网页授权地址后出现重复请求2次的情况,修改定义state参数即可达到目的如(state随机生成,当然有特殊目的验证的同学自己设定也可以):

public String convertOAuthHref(String href) {//return href;StringBuffer str = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize");str.append("?appid=").append(appId);str.append("&redirect_uri=").append(href);/*try {str.append("&redirect_uri=").append(URLEncoder.encode(href, "UTF-8"));} catch (Exception e) {// }*/str.append("&response_type=code");str.append("&scope=snsapi_base");str.append("&state=" + new Random().nextInt(10000));str.append("#wechat_redirect");return str.toString();}


0 0