package com.gh.common.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.gh.common.constant.Config; import com.lightgame.utils.RuntimeUtils; 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.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; /** * 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; private 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) { mContext = context.getApplicationContext(); mTencent = Tencent.createInstance(Config.TENCENT_APPID, mContext); //初始化QQ分享 mIWXAPI = WXAPIFactory.createWXAPI(mContext, Config.WECHAT_APPID, true); //初始化微信分享 WbSdk.install(context, new AuthInfo(mContext, Config.WEIBO_APPKEY, "http://www.sina.com", SCOPE)); 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) { 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")); JSONObject content = new JSONObject(); content.put("openid", jsonObject.getString("openid")); content.put("access_token_expire", Utils.getTime(mContext) + jsonObject.getLong("expires_in")); content.put("access_token", jsonObject.getString("access_token")); if (mLoginListener != null) { mLoginListener.OnLoginData(content, LoginUtils.LoginTag.qq);// QQ 登录回调 } } catch (JSONException e) { Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQ登录数据回调异常::" + e.toString()); 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(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) { Utils.toast(mContext, "登录失败"); Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQ 登录失败"); } @Override public void onCancel() { Utils.toast(mContext, "登录取消"); Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQ 登录取消"); } }; public void onQQCallback(int requestCode, int resultCode, Intent data) { Tencent.onActivityResultData(requestCode, resultCode, data, QqLoginListener); } // QQ登录 public void QQLogin(OnLoginDataListener listener, Activity activity) { mLoginListener = listener; if (mTencent != null && !mTencent.isSessionValid()) { Utils.log(GetLoginDataUtils.class.getSimpleName(), "QQLogin"); mTencent.login(activity, "all", QqLoginListener); } } public void QQLogout() { if (mTencent != null && mTencent.isSessionValid()) { mTencent.logout(mContext); } } // 微信登录 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); if (!register || !b) { Utils.toast(mContext, "请检查是否安装微信客户端"); } } } public void WCLofinCallBack(JSONObject content) { mLoginListener.OnLoginData(content, LoginUtils.LoginTag.wechat); } public void onWeiboCallback(int requestCode, int resultCode, Intent data) { if (mSsoHandler != null) { mSsoHandler.authorizeCallBack(requestCode, resultCode, data); } } // 微博登录 public void WeiBoLogin(OnLoginDataListener listener, Activity context) { mSsoHandler = new SsoHandler(context); 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) { RuntimeUtils.getInstance().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(); } } }); JSONObject content = new JSONObject(); try { content.put("uid", token.getUid()); content.put("access_token", token.getToken()); content.put("access_token_expire", Utils.getTime(mContext) + token.getExpiresTime()); content.put("refresh_token", token.getRefreshToken()); // content.put("refresh_token_expire", Utils.getTime(mContext) + 86400 * 30); // refresh_token 有效期30天 if (mLoginListener != null) { mLoginListener.OnLoginData(content, LoginUtils.LoginTag.weibo);// 微博 登录回调 } } catch (JSONException e) { e.printStackTrace(); } // AppController.MAIN_EXECUTOR.execute(new Runnable() { // @Override // public void run() { // getWeiBoUserInfo(token.getToken(), token.getUid()); // } // }); } @Override public void cancel() { Utils.toast(mContext, "取消授权"); } @Override public void onFailure(WbConnectErrorMessage errorMessage) { Utils.toast(mContext, "微博登录需要客户端支持,请先安装微博"); } } //微博 获取用户信息 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); } }