微信登录
这里有QQ、微信、微博登录相关代码。
前期准备
获取
- WX_APP_ID = "*****";
- WX_APP_SECRET = "*****";
调起微信登录
IWXAPI iwxapi = WXAPIFactory.createWXAPI(App.mContext, Constant.WX_APP_ID, true);//微信登录
if (!iwxapi.isWXAppInstalled()) {//判断手机是否安装微信客户端
Toast.makeText(mActivity, "请先安装微信客户端", Toast.LENGTH_SHORT).show();
return;
}
SendAuth.Req req = new SendAuth.Req();
req.scope = WX_SCOPE;//需要的权限范围如 WX_SCOPE = "snsapi_userinfo"
req.state = "test_wx_sdk";//内容随便
iwxapi.sendReq(req);
重点来了
在model的包名下创建wxapi目录,在wxapi目录下创建WXEntryActivity.java,如下
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, WX_APP_ID);//固定配置
api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp resp) {
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK://微信登录成功
// TODO: 继续请求,获取微信账户信息;如果不需要获取微信用户信息,那么以下代码就不需要
if (resp instanceof SendAuth.Resp) {
SendAuth.Resp newResp = (SendAuth.Resp) resp;
//获取微信传回的code
String code = newResp.code;
HashMap<String, String> map = new HashMap<>();
map.put("appid", WX_APP_ID);
map.put("secret",WX_APP_SECRET);
map.put("code", code);
map.put("grant_type", "authorization_code");//这个参数是固定的值,复制就行
//这里是网络请求
OkGo.get(WX_GET_TOKEN)//WX_GET_TOKEN ="https://api.weixin.qq.com/sns/oauth2/access_token";//通过code获取access_token的接口
.params(map)//参数
.execute(new JsonCallback<BWxAccessToken>() {
@Override
public void onSuccess(BWxAccessToken bWxAccessToken, Call call, Response response) {
if (bWxAccessToken != null) {
final String accessToken = bWxAccessToken.getAccess_token();
String refresh_token = bWxAccessToken.getRefresh_token();
final String openID = bWxAccessToken.getOpenid();//拿到openid,然后去获取微信用户信息
HashMap<String, String> getInfoMap = new HashMap<>();
getInfoMap.put("access_token", accessToken);
getInfoMap.put("openid", openID);
//又是网络请求
OkGo.get(WX_GET_USER_INFO)//WX_GET_USER_INFO= "https://api.weixin.qq.com/sns/userinfo";//获取用户个人信息(UnionID机制)
.params(getInfoMap)
.execute(new JsonCallback<BWxUserInfo>() {
@Override
public void onSuccess(BWxUserInfo o, Call call, Response response) {
if (o != null) {
/**//这就是返回的微信的用户json信息
* {
"openid":"OPENID",
"nickname":"NICKNAME",
"sex":1,
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
"privilege":[
"PRIVILEGE1",
"PRIVILEGE2"
],
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
* */
//TODO 根据微信用户信息 去执行你自己的登录逻辑
}
}
});
}
}
});
}
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
L.i("微信登录", "发送取消");
//发送取消
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
L.i("微信登录", "发送取消");
//发送被拒绝
break;
default:
L.i("微信登录", "未知错误");
//发送返回
break;
}
this.finish();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// handleIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
}
QQ登录
前期准备
获取
- QQ_APP_ID = "********";//你自己应用的APP_ID
调起QQ登录
Tencent mTencent = Tencent.createInstance(QQ_APP_ID, App.mContext);//QQ登录
baseUiListener = new BaseUiListener();//
mTencent.login(mActivity,QQ_SCOPE, baseUiListener);//请求的权限范围 QQ_SCOPE = "all";
//QQ登录回调
public class BaseUiListener implements IUiListener {
@Override
public void onComplete(Object o) {//走到这里说明QQ登录成功
//以下代码为获取QQ用户信息,如若业务不需要可不写
if (o != null) {
try {
final JSONObject data = (JSONObject) o;
final String openID = data.getString("openid");
final String accessToken = data.getString("access_token");
String expires_in = data.getString("expires_in");
mTencent.setOpenId(openID);
mTencent.setAccessToken(accessToken, expires_in);
UserInfo userInfo = new UserInfo(mActivity, mTencent.getQQToken());
userInfo.getUserInfo(new IUiListener() {
@Override
public void onComplete(Object o) {
if (o != null) {
JSONObject data = (JSONObject) o;//o中包含了QQ的用户信息
try {
final String nickname = data.getString("nickname");//我这里只需要QQ的用户名
//TODO
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onError(UiError uiError) {
}
@Override
public void onCancel() {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onError(UiError uiError) {
}
@Override
public void onCancel() {
}
}
//在Activity的onActivityResult处理响应码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Constants.ACTIVITY_OK) {
if (requestCode == Constants.REQUEST_LOGIN) {
if (baseUiListener != null)
Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
}
}
}
微博登录
前期准备
获取
String WB_APP_KEY = "**********";
//下面的在官方文档里都可以查到
String WB_SCOPE = "email,direct_messages_read,direct_messages_write," +
"friendships_groups_read,friendships_groups_write,statuses_to_me_read,follow_app_official_microblog,";//微博授权范围
String WB_REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";// 应用的回调页
String WB_GET_USER_INFO = "https://api.weibo.com/2/users/show.json";//获取用户信息api
调起微博登录
AuthInfo authInfo = new AuthInfo(App.mContext,WB_APP_ID,WB_REDIRECT_URL,WB_SCOPE);
mSsoHandler = new SsoHandler(LoginActivity.this, authInfo);
mSsoHandler.authorize(new AuthListener());//SSO授权如果手机安装了微博客户端则使用客户端授权,没有则进行网页授权
private class AuthListener implements WeiboAuthListener {
@Override
public void onComplete(Bundle bundle) {
Oauth2AccessToken mAccessToken = Oauth2AccessToken.parseAccessToken(bundle);
if (mAccessToken.isSessionValid()) {
final String uid = mAccessToken.getUid();
final String token = mAccessToken.getToken();
HashMap<String, String> map = new HashMap<>();
map.put("uid", uid);
map.put("access_token", token);
//下面代码用来获取微博用户信息
OkGo.get(WB_GET_USER_INFO).params(map).execute(new JsonCallback<BWbUserInfo>() {
@Override
public void onSuccess(BWbUserInfo o, Call call, Response response) {
if (o != null) {
o//自己写的微博用户json数据的bean对象
}
}
});
} else {
// 当您注册的应用程序签名不正确时,就会收到错误Code,请确保签名正确
//Toast.makeText(mActivity, "错误码" + bundle.getString("code", "") + "请确保您的应用签名正确", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onWeiboException(WeiboException e) {
//Toast.makeText(mActivity, "微博登录失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
//Toast.makeText(mActivity, "取消微博登录", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mSsoHandler != null) {//处理微博回调
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}