1.流程:
App端调用第三方进行登录 |
-> |
第三方返回openid(微博叫uid)与access_token |
-> |
App端发送openid与access_token到后台 |
-> |
后台调用第三方提供的校验API进行校验 |
-> |
校验成功返回本应用的访问令牌token |
2.后台数据库只需要在用户表保存openid即可
3.具体校验过程:
后台采用Java开发 使用Jfinal框架 HttpKit和StrKit都是jfinal框架的内容 StrKit.isBlank方法是字符串的非空验证
微博:
url(post) | https://api.weibo.com/oauth2/get_token_info | |
参数 | access_token | |
返回值 | { "uid": 6021880, "appkey": "9187121", "scope": "follow_app_official_microblog", "create_at": 15231756, "expire_in": 5667 } | |
做法: | 比对返回的uid与open_id是否一致 |
具体代码如下:
public static boolean checkWeibo(String token, String openId) {
String url = "https://api.weibo.com/oauth2/get_token_info";
Map<String, String> paras = new HashMap<String, String>();
paras.put("access_token", token);
String responseString = HttpKit.post(url, paras, null);
if (JFinal.me().getConstants().getDevMode()) {
System.out.println(responseString);
}
if (StrKit.isBlank(responseString)) {
return false;
}
JSONObject object = JSON.parseObject(responseString);
if (object == null) {
return false;
}
String uid = object.getString("uid");
if (StrKit.isBlank(uid) || !uid.equals(openId)) {
return false;
}
return true;
}
微信:
url(get) | https://api.weixin.qq.com/sns/auth | |
参数 | access_token,openid | |
返回值 | {"errcode":0,"errmsg":"ok"} | |
做法 | errcode=0代表成功 |
具体代码如下:
public static boolean checkWechat(String token, String openId) {
String url = "https://api.weixin.qq.com/sns/auth";
Map<String, String> paras = new HashMap<String, String>();
paras.put("access_token", token);
paras.put("openid", openId);
String responseString = HttpKit.get(url, paras);
if (JFinal.me().getConstants().getDevMode()) {
System.out.println(responseString);
}
if (StrKit.isBlank(responseString)) {
return false;
}
JSONObject object = JSON.parseObject(responseString);
if (object == null) {
return false;
}
int errcode = object.getIntValue("errcode");
if (errcode != 0) {
return false;
}
return true;
}
QQ:
url(get) | https://graph.qq.com/user/get_user_info | |
参数 | oauth_consumer_key,access_token,openid | |
返回值 | { "ret": 0, "msg": "", "is_lost":0, "nickname": "123", "gender": "男", "province": "陕西", "city": "西安", "year": "", "is_yellow_vip": "0", "vip": "0", "yellow_vip_level": "0", "level": "0", "is_yellow_year_vip": "0" } | |
做法 | 只需要比对ret是否为0 |
public static boolean checkQQ(String token, String openId) {
String url = "https://graph.qq.com/user/get_user_info";
Map<String, String> paras = new HashMap<String, String>();
paras.put("oauth_consumer_key", "1106812746");//App在腾讯开放平台注册的 appid
paras.put("access_token", token);
paras.put("openid", openId);
String responseString = HttpKit.get(url, paras);
if (JFinal.me().getConstants().getDevMode()) {
System.out.println(responseString);
}
if (StrKit.isBlank(responseString)) {
return false;
}
JSONObject object = JSON.parseObject(responseString);
if (object == null) {
return false;
}
int ret = object.getIntValue("ret");
if (ret != 0) {
return false;
}
return true;
}
第一次做,各路大神轻喷。