Android笔记:集成原生微信授权获取用户信息登录
【摘要】
其实两年前做过这个功能,项目最近需要加上获取微信用户信息的需求,索性我就写成一篇文章,当做笔记 我在项目中用到的是点击一个按钮发起微信授权请求的需求,首先判断是否安装微信,如果安装微信则进行用户授权,授权...
其实两年前做过这个功能,项目最近需要加上获取微信用户信息的需求,索性我就写成一篇文章,当做笔记
我在项目中用到的是点击一个按钮发起微信授权请求的需求,首先判断是否安装微信,如果安装微信则进行用户授权,授权成功之后通过微信提供的接口获取openID等用户信息,然后做自己的业务:
1、 Android端要使用微信登录,必须在微信开发平台创建APP并且审核通过,得到appid和secret
2、 依赖微信SDK
dependencies {
compile ‘com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+’
}
- 1
- 2
- 3
3、添加权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- 1
- 2
- 3
- 4
- 5
4、注册到微信
iwxapi = WXAPIFactory.createWXAPI(this, Constant.APP_ID, true);
iwxapi.registerApp(Constant.APP_ID);
- 1
- 2
5、 判断是否安装微信,已安装则发起授权请求
if (!iwxapi.isWXAppInstalled()) {
Intent intent = new Intent(this, MyDialogActivity.class);
startActivity(intent);
} else {
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo_test";
iwxapi.sendReq(req);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
6、在包名下创建wxapi包和WXEntryActivity类(继承Activity并实现IWXAPIEventHandler接口)WXEntryActivity是微信回调的一个类,通常给个透明的主题或者处理完业务逻辑就直接finish。需要在回调中拿到code,然后再根据code去获取AccessToken,然后再根据AccessToken和OpenId去获取UserInfo。
代码如下:
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
private IWXAPI iwxapi;
private String unionid;
private String openid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
// // 隐藏状态栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//接收到分享以及登录的intent传递handleIntent方法,处理结果
iwxapi = WXAPIFactory.createWXAPI(this, Constant.APP_ID, false);
iwxapi.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
//请求回调结果处理
@Override
public void onResp(BaseResp baseResp) {
//登录回调
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
String code = ((SendAuth.Resp) baseResp).code;
//获取用户信息
getAccessToken(code);
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
finish();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
finish();
break;
default:
finish();
break;
}
}
private void getAccessToken(String code) {
//获取授权
StringBuffer loginUrl = new StringBuffer();
loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
.append("?appid=")
.append(Constant.APP_ID)
.append("&secret=")
.append(Constant.SECRET)
.append("&code=")
.append(code)
.append("&grant_type=authorization_code");
OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
@Override
public void onSuccess(String response) {
String access = null;
String openId = null;
try {
JSONObject jsonObject = new JSONObject(response);
access = jsonObject.getString("access_token");
openId = jsonObject.getString("openid");
} catch (JSONException e) {
e.printStackTrace();
}
//获取个人信息
String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
OkHttpUtils.ResultCallback<String> reCallback = new OkHttpUtils.ResultCallback<String>() {
@Override
public void onSuccess(String responses) {
String nickName = null;
String sex = null;
String city = null;
String province = null;
String country = null;
String headimgurl = null;
try {
JSONObject jsonObject = new JSONObject(responses);
openid = jsonObject.getString("openid");
nickName = jsonObject.getString("nickname");
sex = jsonObject.getString("sex");
city = jsonObject.getString("city");
province = jsonObject.getString("province");
country = jsonObject.getString("country");
headimgurl = jsonObject.getString("headimgurl");
unionid = jsonObject.getString("unionid");
loadNetData(1, openid, nickName, sex, province,
city, country, headimgurl, unionid);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Exception e) {
Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
finish();
}
};
OkHttpUtils.get(getUserInfo, reCallback);
}
@Override
public void onFailure(Exception e) {
Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
finish();
}
};
OkHttpUtils.get(loginUrl.toString(), resultCallback);
}
@Override
protected void onPause() {
overridePendingTransition(0, 0);
super.onPause();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
这里贴上OkHttpUtils的代码便于大家使用:
public class OkHttpUtils {
private static OkHttpUtils mInstance;
private OkHttpClient mOkHttpClient;
private Handler mDelivery;
private Gson mGson;
private OkHttpUtils() {
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
mGson = new Gson();
mDelivery = new Handler(Looper.getMainLooper());
}
private synchronized static OkHttpUtils getmInstance() {
if (mInstance == null) {
mInstance = new OkHttpUtils();
}
return mInstance;
}
private void getRequest(String url, final ResultCallback callback) {
final Request request = new Request.Builder().url(url).build();
deliveryResult(callback, request);
}
private void postRequest(String url, final ResultCallback callback, List<Param> params) {
Request request = buildPostRequest(url, params);
deliveryResult(callback, request);
}
/**
* 处理结果
* @param callback
* @param request
*/
private void deliveryResult(final ResultCallback callback, Request request) {
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailCallback(callback, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String str = response.body().string();
if (callback.mType == String.class) {
/**
* 返回字符串
*/
sendSuccessCallBack(callback, str);
} else {
/**
* 这里处理解析返回对象
*/
Object object = mGson.fromJson(str, callback.mType);
sendSuccessCallBack(callback, object);
}
} catch (final Exception e) {
// LogUtils.e(TAG, "convert json failure", e);
sendFailCallback(callback, e);
}
}
});
}
private void sendFailCallback(final ResultCallback callback, final Exception e) {
mDelivery.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onFailure(e);
}
}
});
}
private void sendSuccessCallBack(final ResultCallback callback, final Object obj) {
mDelivery.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onSuccess(obj);
}
}
});
}
private Request buildPostRequest(String url, List<Param> params) {
FormBody.Builder builder= new FormBody.Builder();
for (Param param : params) {
builder.add(param.key, param.value);
}
RequestBody requestBody = builder.build();
return new Request.Builder().url(url).post(requestBody).build();
}
/**********************对外接口************************/
/**
* get请求
* @param url 请求url
* @param callback 请求回调
*/
public static void get(String url, ResultCallback callback) {
getmInstance().getRequest(url, callback);
}
/**
* post请求
* @param url 请求url
* @param callback 请求回调
* @param params 请求参数
*/
public static void post(String url, final ResultCallback callback, List<Param> params) {
getmInstance().postRequest(url, callback, params);
}
/**
* http请求回调类,回调方法在UI线程中执行
* @param <T>
*/
public static abstract class ResultCallback<T> {
Type mType;
public ResultCallback(){
mType = getSuperclassTypeParameter(getClass());
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
/**
* 请求成功回调
* @param response
*/
public abstract void onSuccess(T response);
/**
* 请求失败回调
* @param e
*/
public abstract void onFailure(Exception e);
}
/**
* post请求参数类 这里可以根据项目抽取成泛型
*/
public static class Param {
String key;
String value;
public Param() {
}
public Param(String key, String value) {
this.key = key;
this.value = value;
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
到此登录授权就结束了,大家有什么不懂的,或者遇到什么问题可在下方留言。
文章来源: chengsy.blog.csdn.net,作者:程思扬,版权归原作者所有,如需转载,请联系作者。
原文链接:chengsy.blog.csdn.net/article/details/89298112
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)