模拟对接登录接口已经登录流程(未完成)

This commit is contained in:
kehaoyuan
2017-07-07 19:31:58 +08:00
parent 475221a011
commit b239407c25
11 changed files with 564 additions and 385 deletions

View File

@ -0,0 +1,267 @@
package com.gh.common.util;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.lightgame.utils.Utils;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
/**
* Created by khy on 14/06/17.
*
* 获取第三方登录数据
*/
public class GetLoginDataUtils {
private static GetLoginDataUtils instance;
private Context mContext;
private OnLoginDataListener mLoginListener; //登录成功回调
private Tencent mTencent;
private IWXAPI mIWXAPI;
public SsoHandler mSsoHandler;
private Oauth2AccessToken mAccessToken; // weibo
public static final String SCOPE =
"email,direct_messages_read,direct_messages_write,"
+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
+ "follow_app_official_microblog," + "invitation_write"; // weiboCode
private GetLoginDataUtils(Context context) {
mTencent = Tencent.createInstance(Config.TENCENT_APPID, context); //初始化QQ分享
mIWXAPI = WXAPIFactory.createWXAPI(context, Config.WECHAT_APPID, true); //初始化微信分享
WbSdk.install(context, new AuthInfo(context, Config.WEIBO_APPKEY, "http://www.sina.com", SCOPE));
mSsoHandler = new SsoHandler((Activity) context);
mContext = context;
Utils.log(GetLoginDataUtils.class.getSimpleName(), "initLogin");
}
public static GetLoginDataUtils getInstance(Context context) {
if (instance == null) {
instance = new GetLoginDataUtils(context);
}
return instance;
}
//QQ登录回调处理
public IUiListener QqLoginListener = new IUiListener() {
@Override
public void onComplete(Object o) {
Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQ 登录成功");
if (o instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) o;
String s = jsonObject.toString();
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQLoginComplete::" + s);
try {
mTencent.setOpenId(jsonObject.getString("openid"));
mTencent.setAccessToken(jsonObject.getString("access_token"), jsonObject.getString("expires_in"));
} catch (JSONException e) {
e.printStackTrace();
}
// TODO 数据不对
mLoginListener.OnLoginData(jsonObject, LoginUtils.LoginTag.qq);// QQ 登录回调
}
QQToken qqToken = mTencent.getQQToken();
UserInfo userInfo = new UserInfo(mContext, qqToken);
userInfo.getUserInfo(new IUiListener() { // 获取QQ用户信息
@Override
public void onComplete(Object o) {
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQUserInfo::" + o.toString());
}
@Override
public void onError(UiError uiError) {
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQUserInfoUiError::" + uiError.errorDetail + "==" + uiError.errorMessage + "==" + uiError.errorCode);
}
@Override
public void onCancel() {
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQUserInfoonCancel");
}
});
}
@Override
public void onError(UiError uiError) {
Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQ 登录失败");
}
@Override
public void onCancel() {
Toast.makeText(mContext, "登录取消", Toast.LENGTH_SHORT).show();
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQ 登录取消");
}
};
// QQ登录
public void QQLogin(OnLoginDataListener listener) {
mLoginListener = listener;
if (mTencent != null && !mTencent.isSessionValid()) {
Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQLogin");
mTencent.login((Activity) mContext, "all", QqLoginListener);
}
}
// 微信登录
public void WCLogin(OnLoginDataListener listener) {
mLoginListener = listener;
if (mIWXAPI != null) {
boolean register = mIWXAPI.registerApp(Config.WECHAT_APPID);
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "光环助手";
boolean b = mIWXAPI.sendReq(req);
Utils.log(GetLoginDataUtils.class.getSimpleName(), "微信注册状态::" + register + "\n 发送状态::" + b);
}
}
// 微博登录
public void WeiBoLogin(OnLoginDataListener listener) {
mLoginListener = listener;
mSsoHandler.authorizeClientSso(new SelfWbAuthListener());
// 第一次启动本应用AccessToken 不可用
mAccessToken = AccessTokenKeeper.readAccessToken(mContext);
if (mAccessToken.isSessionValid()) {
updateTokenView(true);
}
}
// 微博登录回调处理
private class SelfWbAuthListener implements WbAuthListener {
@Override
public void onSuccess(final Oauth2AccessToken token) {
((Activity) mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
mAccessToken = token;
if (mAccessToken.isSessionValid()) {
// 显示 Token
updateTokenView(false);
// 保存 Token 到 SharedPreferences
AccessTokenKeeper.writeAccessToken(mContext, mAccessToken);
Toast.makeText(mContext, "授权成功", Toast.LENGTH_SHORT).show();
}
}
});
Map<String, String> map = new HashMap<>();
map.put("uid", token.getUid());
map.put("access_token", token.getToken());
map.put("access_token_expire", String.valueOf(token.getExpiresTime()));
map.put("refresh_token", token.getRefreshToken());
map.put("refresh_token_expire", ""); // TODO 数据不对
mLoginListener.OnLoginData(new JSONObject(map), LoginUtils.LoginTag.qq);// QQ 登录回调
AppController.MAIN_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
getWeiBoUserInfo(token.getToken(), token.getUid());
}
});
}
@Override
public void cancel() {
Toast.makeText(mContext, "取消授权", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(WbConnectErrorMessage errorMessage) {
Toast.makeText(mContext, errorMessage.getErrorMessage(), Toast.LENGTH_LONG).show();
}
}
//微博 获取用户信息
private void getWeiBoUserInfo(String accessToken, String uid) {
String path = "https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + uid;
Utils.log(GetLoginDataUtils.class.getSimpleName(), "getWeiBoUserInfo-url::" + path);
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
int code = conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
Utils.log(GetLoginDataUtils.class.getSimpleName(), "getWeiBoUserInfo-RequestCode::" + code);
if (code == 200) {
InputStream is = conn.getInputStream();
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
String str = new String(baos.toByteArray());
Utils.log(GetLoginDataUtils.class.getSimpleName(), "getWeiBoUserInfo-Body::" + str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 微博显示当前 Token 信息。
*
* @param hasExisted 配置文件中是否已存在 token 信息并且合法
*/
private void updateTokenView(boolean hasExisted) {
String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
new java.util.Date(mAccessToken.getExpiresTime()));
String format = "Token%1$s \\n有效期%2$s";
String token = String.format(format, mAccessToken.getToken(), date);
Utils.log(GetLoginDataUtils.class.getSimpleName(), "::WB_TOKEN::" + token);
String message = String.format(format, mAccessToken.getToken(), date);
if (hasExisted) {
message = "Token 仍在有效期内,无需再次登录。" + "\n" + message;
}
Utils.log(GetLoginDataUtils.class.getSimpleName(), "::WB_MESSAGE::" + message);
}
// 登录成功回调
public interface OnLoginDataListener {
void OnLoginData(JSONObject content, LoginUtils.LoginTag loginTag);
}
}