模拟对接登录接口已经登录流程(未完成)
This commit is contained in:
@ -1,252 +1,154 @@
|
||||
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.gh.gamecenter.entity.LoginResponseEntity;
|
||||
import com.gh.gamecenter.retrofit.JSONObjectResponse;
|
||||
import com.gh.gamecenter.retrofit.Response;
|
||||
import com.gh.gamecenter.retrofit.RetrofitManager;
|
||||
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;
|
||||
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.RequestBody;
|
||||
import retrofit2.HttpException;
|
||||
import rx.Observable;
|
||||
import rx.android.schedulers.AndroidSchedulers;
|
||||
import rx.schedulers.Schedulers;
|
||||
|
||||
/**
|
||||
* Created by khy on 14/06/17.
|
||||
* Created by khy on 7/07/17.
|
||||
*/
|
||||
|
||||
public class LoginUtils {
|
||||
|
||||
private static LoginUtils instance;
|
||||
|
||||
private Context mContext;
|
||||
private OnLoginListener 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 LoginUtils(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(LoginUtils.class.getSimpleName(), "initLogin");
|
||||
public enum LoginTag {
|
||||
qq, wechat, weibo, phone
|
||||
}
|
||||
|
||||
public static LoginUtils getInstance(Context context) {
|
||||
if (instance == null) {
|
||||
instance = new LoginUtils(context);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
//QQ登录回调处理
|
||||
public IUiListener QqLoginListener = new IUiListener() {
|
||||
@Override
|
||||
public void onComplete(Object o) {
|
||||
Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQ 登录成功");
|
||||
if (o instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) o;
|
||||
String s = jsonObject.toString();
|
||||
Utils.log(LoginUtils.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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
QQToken qqToken = mTencent.getQQToken();
|
||||
UserInfo userInfo = new UserInfo(mContext, qqToken);
|
||||
userInfo.getUserInfo(new IUiListener() { // 获取QQ用户信息
|
||||
@Override
|
||||
public void onComplete(Object o) {
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQUserInfo::" + o.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(UiError uiError) {
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQUserInfoUiError::" + uiError.errorDetail + "==" + uiError.errorMessage + "==" + uiError.errorCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQUserInfoonCancel");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(UiError uiError) {
|
||||
Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQ 登录失败");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
Toast.makeText(mContext, "登录取消", Toast.LENGTH_SHORT).show();
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQ 登录取消");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// QQ登录
|
||||
public void QQLogin(OnLoginListener listener) {
|
||||
mLoginListener = listener;
|
||||
if (mTencent != null && !mTencent.isSessionValid()) {
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "QQLogin");
|
||||
mTencent.login((Activity) mContext, "all", QqLoginListener);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 微信登录
|
||||
public void WCLogin(OnLoginListener 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(LoginUtils.class.getSimpleName(), "微信注册状态::" + register + "\n 发送状态::" + b);
|
||||
}
|
||||
}
|
||||
|
||||
// 微博登录
|
||||
public void WeiBoLogin(OnLoginListener 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();
|
||||
// 获取验证码
|
||||
public static void getPhoneCaptcha(final Context context, String phoneNum, final onCaptchaCallBackListener listener) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("mobile", phoneNum);
|
||||
RequestBody body = RequestBody.create(MediaType.parse("application/json"),
|
||||
new JSONObject(params).toString());
|
||||
RetrofitManager
|
||||
.getUser()
|
||||
.loginByCaptcha(body)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new JSONObjectResponse() {
|
||||
@Override
|
||||
public void onResponse(JSONObject response) {
|
||||
super.onResponse(response);
|
||||
try {
|
||||
listener.onCaptcha(response.getString("service_id"));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
@Override
|
||||
public void onFailure(HttpException e) {
|
||||
super.onFailure(e);
|
||||
int code = e.code();
|
||||
switch (code) {
|
||||
case 40001:
|
||||
Utils.toast(context, "缺少mobile参数");
|
||||
break;
|
||||
case 40002:
|
||||
Utils.toast(context, "mobile格式错误");
|
||||
break;
|
||||
case 40003:
|
||||
Utils.toast(context, "一分钟内已发送过验证码");
|
||||
break;
|
||||
default:
|
||||
Utils.toast(context, "未知错误");
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//微博 获取用户信息
|
||||
private void getWeiBoUserInfo(String accessToken, String uid) {
|
||||
String path = "https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + uid;
|
||||
Utils.log(LoginUtils.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(LoginUtils.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(LoginUtils.class.getSimpleName(), "getWeiBoUserInfo-Body::" + str);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
// 登录前,做好body判断
|
||||
public static void login(final Context context, RequestBody body, final LoginTag loginTag,
|
||||
final onLoginCallBackListener listener) {
|
||||
|
||||
Observable<LoginResponseEntity> observable;
|
||||
|
||||
if (loginTag == LoginTag.weibo) {
|
||||
observable = RetrofitManager.getUser().loginByWeibo(body);
|
||||
} else if (loginTag == LoginTag.qq){
|
||||
observable = RetrofitManager.getUser().loginByQQ(body);
|
||||
} else if (loginTag == LoginTag.wechat) {
|
||||
observable = RetrofitManager.getUser().loginByWechat(body);
|
||||
} else {
|
||||
observable = RetrofitManager.getUser().loginByMobile(body);
|
||||
}
|
||||
|
||||
observable
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Response<LoginResponseEntity>() {
|
||||
@Override
|
||||
public void onResponse(LoginResponseEntity response) {
|
||||
super.onResponse(response);
|
||||
listener.onLogin(response, loginTag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(HttpException e) {
|
||||
super.onFailure(e);
|
||||
int code = e.code();
|
||||
switch (code) {
|
||||
case 40000:
|
||||
Utils.toast(context,"参数错误或不完整");
|
||||
case 40004:
|
||||
Utils.toast(context,"缺少mobile参数");
|
||||
break;
|
||||
case 40005:
|
||||
Utils.toast(context,"缺少code参数");
|
||||
break;
|
||||
case 40006:
|
||||
Utils.toast(context,"缺少service_id参数");
|
||||
break;
|
||||
case 40007:
|
||||
Utils.toast(context,"服务已超时");
|
||||
break;
|
||||
case 40008:
|
||||
Utils.toast(context,"验证码已超时");
|
||||
break;
|
||||
case 40009:
|
||||
Utils.toast(context,"验证码错误");
|
||||
break;
|
||||
case 40010:
|
||||
Utils.toast(context,"登录授权失败");
|
||||
break;
|
||||
case 40011:
|
||||
Utils.toast(context,"缺少token参数");
|
||||
break;
|
||||
case 40012:
|
||||
Utils.toast(context,"令牌已过期");
|
||||
break;
|
||||
default:
|
||||
Utils.toast(context,"未知错误");
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 微博显示当前 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(LoginUtils.class.getSimpleName(), "::WB_TOKEN::" + token);
|
||||
String message = String.format(format, mAccessToken.getToken(), date);
|
||||
if (hasExisted) {
|
||||
message = "Token 仍在有效期内,无需再次登录。" + "\n" + message;
|
||||
}
|
||||
Utils.log(LoginUtils.class.getSimpleName(), "::WB_MESSAGE::" + message);
|
||||
public interface onCaptchaCallBackListener {
|
||||
void onCaptcha(String serviceId);
|
||||
}
|
||||
|
||||
// 登录成功回调
|
||||
public interface OnLoginListener {
|
||||
void onLogin();
|
||||
public interface onLoginCallBackListener {
|
||||
void onLogin(LoginResponseEntity entity, LoginTag loginTag);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user