微信登录想必在很多项目中都会用到,最近的项目中就有需求,之前遇到直接就开干,偶尔会遇到一些小问题,再次记录一下,以免后期需要中在四处寻找。
第一需要在微信开放平台上申请相关信息再次就不累述了
第二需要将微信的sdk集成到项目中也很简单
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
第三就开始撸代码了,首先需要在
Application中初始化微信sdk,再次我直接写了一个方法,在Application的create直接调用就可以了方法如下
private void registerToWX() {
//第二个参数是指你应用在微信开放平台上的AppID
mWxApi = WXAPIFactory.createWXAPI(this, WeiXinConstants.WEIXIN_APP_ID, false);
// 将该app注册到微信
mWxApi.registerApp(WeiXinConstants.WEIXIN_APP_ID);
}
调用如下
public static IWXAPI mWxApi;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
registerToWX();
}
第四需要在本地创建一个包名为wxapi的包
包名里面需要重写WxEntryActivity这个activity,需要去实现
implements IWXAPIEventHandler这个类
接下来我就直接贴代码了
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
private IWXAPI iwxapi;
private static final String TAG = "WXEntryActivity";
private static final int RETURN_MSG_TYPE_LOGIN = 1; //登录
private static final int RETURN_MSG_TYPE_SHARE = 2; //分享
@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, WeiXinConstants.WEIXIN_APP_ID, true);
iwxapi.handleIntent(getIntent(), this);
mContext = this;
sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
ActivityManage.getActivityStackManager().pushPayActivity(WXEntryActivity.this);
}
@Override
public void onReq(BaseReq baseReq) {
}
//请求回调结果处理
@Override
public void onResp(BaseResp baseResp) {
Log.i(TAG, "onResp:------>");
Log.i(TAG, "error_code:---->" + baseResp.errCode);
int type = baseResp.getType(); //类型:分享还是登录
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_AUTH_DENIED:
//用户拒绝授权
ShowToast.showToast(mContext, "拒绝授权微信登录");
case BaseResp.ErrCode.ERR_USER_CANCEL:
//用户取消
String message = "";
if (type == RETURN_MSG_TYPE_LOGIN) {
message = "取消了微信登录";
} else if (type == RETURN_MSG_TYPE_SHARE) {
message = "取消了微信分享";
}
ShowToast.showToast(mContext, message);
break;
case BaseResp.ErrCode.ERR_OK:
//用户同意
if (type == RETURN_MSG_TYPE_LOGIN) {
//用户换取access_token的code,仅在ErrCode为0时有效
String code = ((SendAuth.Resp) baseResp).code;
Log.i(TAG, "code:------>" + code);
//这里拿到了这个code,去做2次网络请求获取access_token和用户个人信息
//getAessToken(WeiXinConstants.WEIXIN_APP_ID, WeiXinConstants.WEIXIN_APP_SECRET, code, "authorization_code");
} else if (type == RETURN_MSG_TYPE_SHARE) {
ShowToast.showToast(mContext, "微信分享成功");
}
break;
}
}
@Override
protected void onPause() {
overridePendingTransition(0, 0);
super.onPause();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e("onNewIntent", "onNewIntent");
setIntent(intent);
if (!iwxapi.handleIntent(intent, this)) {
finish();
}
}
/**
* 获取微信登录,用户授权后的个人信息
*
* @param appid
* @param secret
* @param code
* @param grant_type
*/
private void getAessToken(final String appid, final String secret, final String code, String grant_type) {
// 表单数据
FormBody.Builder builder = new FormBody.Builder();
LoadingUitls.showAuth(mContext);
builder.add("appid", appid);
builder.add("secret", secret);
builder.add("code", code);
builder.add("grant_type", grant_type);
RequestBody formBody = builder.build();
final Request request = new Request.Builder().url()
.post(formBody).build();
okHttpClient.newCall(request).enqueue(callBackAccessToken);
}
// 请求后的回调方法
private Callback callBackAccessToken = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
setResultAccessToken(e.getMessage(), false);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
setResultAccessToken(response.body().string(), true);
}
};
// 显示请求返回的结果
private void setResultAccessToken(final String msg, final boolean success) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LoadingUitls.close();
JSONObject jsonObject = null;
if (success) {
if (msg != null && msg.length() > 0) {
try {
jsonObject = new JSONObject(msg);
access_token = jsonObject.optString("access_token");
unoip = jsonObject.optString("unionid");
openid = jsonObject.optString("openid");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(StringCon.TOKEN, access_token);
editor.putString(StringCon.OPENID, openid);
editor.putString(StringCon.UNIONID, unoip);
editor.commit();
getWXUserInfo(access_token, openid, unoip);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ShowToast.showToast(mContext, "授权失败");
}
} else {
ShowToast.showToast(mContext, "网络问题!");
}
}
});
}
/**
* 获取微信登录,用户授权后的个人信息
*
* @param access_token
* @param openid
* @param unionid
*/
private void getWXUserInfo(final String access_token, final String openid, final String unionid) {
// 表单数据
FormBody.Builder builder = new FormBody.Builder();
LoadingUitls.showLogining(mContext);
builder.add("access_token", access_token);
builder.add("openid", openid);
builder.add("unionid", unionid);
RequestBody formBody = builder.build();
final Request request = new Request.Builder().url(NetCont.get_Userinfo)
.post(formBody).build();
okHttpClient.newCall(request).enqueue(callback);
}
// 请求后的回调方法
private Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
setResult(e.getMessage(), false);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
setResult(response.body().string(), true);
}
};
// 显示请求返回的结果
private void setResult(final String msg, final boolean success) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LoadingUitls.close();
JSONObject jsonObject = null;
if (success) {
if (msg != null && msg.length() > 0) {
try {
jsonObject = new JSONObject(msg);
strNickName = jsonObject.getString("nickname");
strSex = jsonObject.getString("sex");
strHeadimgurl = jsonObject.getString("headimgurl");
unoip = jsonObject.getString("unionid");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(StringCon.USER_NAME, strNickName);
editor.putString(StringCon.SEX, strSex);
editor.putString(StringCon.USER_LOGO, strHeadimgurl);
editor.putString(StringCon.UNIONID, unoip);
editor.putString(StringCon.LOGIN_TYPE, "1"); //
editor.putString(StringCon.BINDWEIXIN, "1"); //
editor.commit();
showViews(true);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ShowToast.showToast(mContext, "微信登录失败");
showViews(false);
}
} else {
ShowToast.showToast(mContext, "网络问题!");
showViews(false);
}
}
});
}
/**
* 微信登录
* DevID
* unionid
* Sex
* headimgurl
* NickName
*/
private void showViews(boolean flag) {
if (flag) {
String deviceId = PhoneParameterUtil.getDeviceID();
wxlogin(deviceId, unoip, strSex, strHeadimgurl, strNickName);
} else {
finish();
}
}
}
我这里网络请求用的是OKhttp,主要有微信授权登录,获取access_token,获取用户信息
最后一点也是容易我忘的,记得权限的配置,还有
android:name=".wxapi.WXEntryActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:theme="@style/AppTheme">