1.在微信开放平台注册并创建应用
2.集成微信SDK
3.调用微信API开始登录授权
IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID, true);
api.registerApp(APP_ID);
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo"; // 授权作用域,获取用户信息
req.state = "wechat_login"; // 自定义参数,用于回调处理
api.sendReq(req);
4.在回调处取出微信返回的code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
// 处理微信登录授权回调结果
if (resultCode == ConstantsAPI.COMMAND_SENDAUTH) {
// 授权成功,获取授权码
String code = data.getStringExtra(ConstantsAPI.WX_RESULT_KEY_CODE);
// 将授权码传递给服务端,换取access_token和用户信息
// TODO: 发送网络请求,根据code获取access_token
} else if (resultCode == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
// 授权失败或取消
// TODO: 处理授权失败或取消的情况
}
}
}
5.拿到code去获取access_token和openId
// 发送网络请求,根据code获取access_token
String url = " + APP_ID
+ "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
// 使用HttpClient或OkHttp等库发送网络请求,获取access_token和openid
// TODO: 发送网络请求,获取access_token和openid
OkHttpUtils.get().url(wxTokenUrl(code)).build().readTimeOut(5000).execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
if (socialCallback != null) {
socialCallback.fail(ErrCode.ERR_SDK_INTERNAL, e.toString());
}
}
@Override
public void onResponse(String response, int id) {
try {
JSONObject jsonObject = new JSONObject(response);
String accessToken = jsonObject.getString("access_token");
String openid = jsonObject.getString("unionid");//原来使用openid,现使用unionid
AuthResult authResult = new AuthResult(openid, accessToken);
if (socialCallback instanceof SocialAuthCallback) {
((SocialAuthCallback) socialCallback).success(authResult);
} else if (socialCallback instanceof SocialLoginCallback) {
fetchUserInfo(authResult, ((SocialLoginCallback) socialCallback));
}
} catch (Exception e) {
}
}
});
- 发送网络请求,根据access_token和openid获取用户信息
String userInfoUrl = " + accessToken
+ "&openid=" + openid;
// 使用HttpClient或OkHttp等库发送网络请求,获取用户信息
// TODO: 发送网络请求,获取用户信息
BASE_URL = "https://api.weixin.qq.com/sns/"
WXUser user = WXUser.parse(response);
user.setAuthResult(authResult);
if(callback != null){
callback.success(user);
}
7.拿到用户信息去确认登录页面确认登录
8.拿到第五步的openID去登录
JSONObject json = GenerateJsonUtils.getInstance().getJsonObject();
try {
json.put("loginType",2);
json.put("vLogin",user.getAuthResult().getOpenId());
json.put("vPwd","");
json.put("vIp","");
json.put("vCity","");
if(!TextUtils.isEmpty(ndid)) {
json.put("ndid",ndid);
}
} catch(JSONException e) {
e.printStackTrace();
}
mRequestCall = OkHttpUtils.postJsonString(json.toString()).url(UrlConstant.WXCHAT_LOGIN_URL).build();
网友评论