微信oauth验证 java 版本_微信OAuth验证 java 版本

/**

* @author JackZhang

*

*/

public class OAuthAPI {

public static final String APP_ID = "ABC";

public static final String APP_SECRET = "CDE";

public static final String DOMAIN = "WWW.ABC.COM";

public static void OAuthIfNesscary(HttpServletRequest request,

HttpServletResponse response) throws IOException {

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

HttpSession session = request.getSession();

boolean isValidCode = true;

String serviceUrl = URLEncoder.encode(

"http://" + DOMAIN + request.getRequestURI(), "utf-8");

//检查是否已验证或者验证是否通过

if (code == null || code.equals("authdeny")) {

isValidCode = false;

}

//如果session未空或者取消授权,重定向到授权页面

if ((!isValidCode) && session.getAttribute("user") == null) {

StringBuilder oauth_url = new StringBuilder();

oauth_url.append("https://open.weixin.qq.com/connect/oauth2/authorize?");

oauth_url.append("appid=").append(APP_ID);

oauth_url.append("&redirect_uri=").append(serviceUrl);

oauth_url.append("&response_type=code");

oauth_url.append("&scope=snsapi_userinfo");

oauth_url.append("&state=1#wechat_redirect");

response.sendRedirect(oauth_url.toString());

return;

}

//如果用户同意授权并且,用户session不存在,通过OAUTH接口调用获取用户信息

if (isValidCode && session.getAttribute("user") == null) {

Member member = null;

JSONObject obj = OAuthAPI.getAccessToken(OAuthAPI.APP_ID,OAuthAPI.APP_SECRET, code);

String token = obj.getString("access_token");

String openid = obj.getString("openid");

JSONObject user = OAuthAPI.getUserInfo(token, openid);

MemberService memberService = (MemberService) WebAppContext.getObject("memberService");

member = memberService.saveOrUpdateIfNesscary(user);

session.setAttribute("user", member);

}

}

/**

* 获取授权令牌

* */

public static JSONObject getAccessToken(String appid, String secret,

String code) {

StringBuilder url = new StringBuilder();

url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");

url.append("appid=" + appid);

url.append("&secret=").append(secret);

url.append("&code=").append(code);

url.append("&grant_type=authorization_code");

return HttpClientUtils.getJson(url.toString());

}

//获取用户信息

public static JSONObject getUserInfo(String token, String openid) {

StringBuilder url = new StringBuilder();

url.append("https://api.weixin.qq.com/sns/userinfo?");

url.append("access_token=" + token);

url.append("&openid=").append(openid);

url.append("&lang=zh_CN");

return HttpClientUtils.getJson(url.toString());

}

}

$(document).ready(function(){

if("${param.code}"=="authdeny")

{

$("body").css("display","none");

document.addEventListener(‘WeixinJSBridgeReady‘, function onBridgeReady() {

WeixinJSBridge.call(‘closeWindow‘);

});

}

原文:http://blog.csdn.net/myxx520/article/details/21461455

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值