1.腾讯QQ登陆
登陆后获取授权后能够得到Access Token(这个不要存到表里面,三个月后重新授权,会发生变化)
把OpenID存到表里面
===
OpenID是此网站上或应用中唯一对应用户身份的标识,网站或应用可将此ID进行存储,便于用户下次登录时辨识其身份,或将其与用户在网站上或应用中的原有账号进行绑定。
代码参考
AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
String accessToken = null,
openId = null;
if (accessTokenObj.getAccessToken().equals(“”)) {
//我们的网站被CSRF攻击了或者用户取消了授权
//做一些数据统计工作
System.out.print(“没有获取到响应参数”);
}
else {
accessToken = accessTokenObj.getAccessToken();
OpenID openIDObj = new OpenID(accessToken);
openId = openIDObj.getUserOpenID();
User res = null;
res = userManager.findUserByOpenId(openId);
if (res == null) {
找不到已有用户信息,跳转到注册
}
else {
自动登陆
}
2.新浪微博登陆
存java实现(只对桌面应用程序起效),弹出登陆窗口,打开的浏览器都是本地的(如果是web程序,它会打开服务器的浏览器,客户端看不到效果)->这是一个坑
web程序最好是js +后台java实现
js的话,只需要 点击按钮访问如下链接就行
window.location.assign(“https://api.weibo.com/oauth2/authorize?client_id=YourKey&response_type=code&redirect_uri=回调地址”);
代码示例:
<a href=”#” onclick=’sinaToLogin()’>
<img src=”<@common.basePath/>/img/sina.png”></a>
function sinaToLogin(){
window.location.assign(“https://api.weibo.com/oauth2/authorize?client_id=1366531189&response_type=code&redirect_uri=http://www.xuehigh.com/sinaregister”);
}
这样就可以
先出现-》新浪登陆-》登陆成功授权->回调页面http://www.xuehigh.com/sinaregister,
新浪官网给的js登陆demo只是登陆,没有调转到回调页面功能
后台
@RequestMapping(value = “/sinalogin”, method = RequestMethod.GET)
public void saveSinaRegister(ModelMap modelMap, HttpServletRequest request,
HttpServletResponse response) {
try {
weibo4j.Oauth oauth = new weibo4j.Oauth();
BareBonesBrowserLaunch.openURL(oauth.authorize(“code”, “”));(这个地方是坑,用js这个函数就不需要用了)
} catch (WeiboException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping(value = “/sinaregister”, method = RequestMethod.GET)
public ModelAndView checkSinaHave(ModelMap modelMap, HttpServletRequest request,
HttpServletResponse response) {
User user = new User();
modelMap.addAttribute(user);
ModelAndView mav = new ModelAndView(“user/register”, modelMap);
try {
weibo4j.Oauth oauth = new weibo4j.Oauth();
String codeString = request.getParameter(“code”);
weibo4j.http.AccessToken accesstoken = oauth.getAccessTokenByCode(codeString);
String accString = accesstoken.getAccessToken();
Account am = new Account(accString);
JSONObject uid = am.getUid();
Users um = new Users(accString);
weibo4j.model.User webuser = um.showUserById(uid.getString(“uid”));
User res = null;
res = userManager.findUserByOpenId(accString);
if (res == null)
{
//根据新浪微博账号判断是否以前绑定过登陆,绑定过,更新,未绑定过,注册新用户
//accString这个会变,有授权期限
User filterUser = new User();
filterUser.setThirdContent(webuser.getId());
PaginationSupport<User> findUser = userManager.getUserListPage(filterUser, 0, 10, null, false);
if (findUser != null && findUser.getItems().size() > 0) {
User oldUser = findUser.getItems().get(0);
oldUser.setOpenId(accString);
try {
userManager.updateUser(oldUser);
} catch (EmptyPropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getSession();
SiteUtil.loginToSite(roleHierarchy, authenticationManager, request, oldUser, sessionRegistry);
mav.setViewName(“redirect:/index”);
}
else {
user.setOpenId(accString);
user.setShowName(webuser.getScreenName());
user.setThirdContent(webuser.getId());
user.setThirdType(“sina”);
if (webuser.getGender().compareToIgnoreCase(“n”) == 0) {
user.setGender(1);
}
modelMap.addAttribute(“figureurl”, webuser.getProfileImageUrl());
modelMap.addAttribute(“infoData”, “您的注册信息会和新浪微博账号绑定,注册后你可以直接通过新浪微博账号登录本网站”);
}
}
else {
request.getSession();
SiteUtil.loginToSite(roleHierarchy, authenticationManager, request, res, sessionRegistry);
mav.setViewName(“redirect:/index”);
}
} catch (WeiboException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mav;
}
3.支付宝登陆
代码示例
@RequestMapping(value = “/zfblogin”, method = RequestMethod.GET)
public void saveZfbRegister(ModelMap modelMap, HttpServletRequest request,
HttpServletResponse response) {
//目标服务地址
String target_service = “user.auth.quick.login”;
//必填
//必填,页面跳转同步通知页面路径
String return_url = “http://www.xuehigh.com/zfbregister”;
//需http://格式的完整路径,不允许加?id=123这类自定义参数
//防钓鱼时间戳
String anti_phishing_key = “”;
//若要使用请调用类文件submit中的query_timestamp函数
//客户端的IP地址
String exter_invoke_ip = “”;
//非局域网的外网IP地址,如:221.0.0.1
//////////////////////////////////////////////////////////////////////////////////
//把请求参数打包成数组
Map<String, String> sParaTemp = new HashMap<String, String>();
sParaTemp.put(“service”, “alipay.auth.authorize”);
sParaTemp.put(“partner”, AlipayConfig.partner);
sParaTemp.put(“_input_charset”, AlipayConfig.input_charset);
sParaTemp.put(“target_service”, target_service);
sParaTemp.put(“return_url”, return_url);
sParaTemp.put(“anti_phishing_key”, anti_phishing_key);
sParaTemp.put(“exter_invoke_ip”, exter_invoke_ip);
//建立请求
String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,”get”,”确认”);
try {
response.setContentType(“text/html”);
response.getWriter().println(sHtmlText);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping(value = “zfbregister”, method = RequestMethod.GET)
public ModelAndView returnZfbRegister(ModelMap modelMap, HttpServletRequest request,
HttpServletResponse response) {
User user = new User();
modelMap.addAttribute(user);
ModelAndView mav = new ModelAndView(“user/register”, modelMap);
//获取支付宝GET过来反馈信息
Map<String,String> params = new HashMap<String,String>();
@SuppressWarnings(“rawtypes”)
Map requestParams = request.getParameterMap();
for (@SuppressWarnings(“rawtypes”)
Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = “”;
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length – 1) ? valueStr + values[i]
: valueStr + values[i] + “,”;
}
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
/*try {
System.out.println(“1:” + valueStr);
valueStr = new String(valueStr.getBytes(“ISO-8859-1”), “utf-8”);
System.out.println(“2:” + valueStr);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
params.put(name, valueStr);
}
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
//支付宝用户号
String user_id=request.getParameter(“user_id”);
/*try {
user_id = new String(request.getParameter(“user_id”).getBytes(“ISO-8859-1″),”utf-8”);
System.out.println(“test1:” + user_id);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//授权令牌
//String token = new String(request.getParameter(“token”));
/*try {
token = new String(request.getParameter(“token”).getBytes(“ISO-8859-1″),”utf-8”);
System.out.println(“test2:” + token);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
//计算得出通知验证结果
boolean verify_result = AlipayNotify.verify(params);
if(verify_result){//验证成功
//////////////////////////////////////////////////////////////////////////////////////////
//请在这里加上商户的业务逻辑程序代码
//——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
//判断是否在商户网站中已经做过了这次通知返回的处理
//如果没有做过处理,那么执行商户的业务程序
//如果有做过处理,那么不执行商户的业务程序
//该页面可做页面美工编辑
//System.out.println(“验证成功”);
//——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
//////////////////////////////////////////////////////////////////////////////////////////
//判读用户是否注册
User res = null;
res = userManager.findUserByOpenId(user_id);
if (res == null)
{
user.setOpenId(user_id);
modelMap.addAttribute(“infoData”, “您的注册信息会和支付宝账号绑定,注册后你可以直接通过支付宝账号登录本网站”);
}
else {
request.getSession();
SiteUtil.loginToSite(roleHierarchy, authenticationManager, request, res, sessionRegistry);
mav.setViewName(“redirect:/index”);
}
}else{
//该页面可做页面美工编辑
modelMap.addAttribute(“infoData”, “支付宝账号验证失败!”);
}
return mav;
}
转载请注明:学时网 » 网站第三方登陆(腾讯、新浪微博、支付宝)开发遇到的坑