java 获取用户openid_微信web开发获取用户openid

本文介绍了一个使用微信OAuth2.0进行第三方登录的具体实现过程。详细展示了如何通过获取授权码(code)来进一步请求用户的OpenID,并将该标识符用于后续的身份验证及用户信息获取。文章还涉及了跳转URL的配置、参数传递以及最终如何完成登录重定向。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//需要配置跳转地址

String jumpUrl =request.getContextPath()+"/page/story/storyindex.jsp";

//以下为自动处理,不需要更改

String code = request.getParameter("code");

String rpath = PropertiesUtil.getProperty("yu")+request.getRequestURI();

String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+PropertiesUtil.getProperty("appid")

+"&redirect_uri="+URLEncoder.encode(rpath,"UTF-8")+"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

if(code==null){

response.sendRedirect(oauth2Url);

}else{

String url  =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+PropertiesUtil.getProperty("appid")

+"&secret="+PropertiesUtil.getProperty("secret")+"&code="+code+"&grant_type=authorization_code";

String openidResult = HttpUtil.get(url,true);

JSONObject fromObjectopenid = JSONObject.fromObject(openidResult.toString());

if(fromObjectopenid.toString().indexOf("openid")>-1){

String openid = fromObjectopenid.get("openid").toString();

session.setAttribute("openid",openid);

response.sendRedirect(jumpUrl);

}else{

response.sendRedirect(oauth2Url);

}

}

%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值