微信登录和微信支付现在大部分APP都会使用的到。首先需要在微信开放平台注册应用。
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
在Android6.0以上需动态申请
在全局Application类MyApplication中注册微信
/**
* 全局Application
*/
public class MyApplication extends Application {
private static Context context;
public static IWXAPI mWXapi;
public String WX_APP_ID = "你自己的appid";
@Override
public void onCreate() {
super.onCreate();
//向微信注册
registerToWX();
}
private void registerToWX() {
mWXapi = WXAPIFactory.createWXAPI(context, WX_APP_ID, false);
mWXapi.registerApp(WX_APP_ID);
}
public static Context getContext() {
return context;
}
}
在发起登录的onclick方法中
//微信登录页
private void wxLogin() {
if (!MyApplication.mWXapi.isWXAppInstalled()) {
Toast.makeText(this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
return;
}
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "skit_wx_login";//这个字段可以任意更改
MyApplication.mWXapi.sendReq(req);
}
在自己项目的包名下创建一个package,取名叫wxapi,并在该包下创建一个类名为WXEntryActivity的类。(注:包名和类名必须为这两个,自己的包名可以看自己的maninfest文件,比如你的包名是com.test,则这个包的全名则为com.text.wxapi)。
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private static final String WX_APP_ID = "你自己的appid";
private static final String WX_APP_SECRET = "你自己的appsecret";
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final String TAG = "WXEntryActivityLog";
private HttpWxLogin httpWxLogin;
private String openid;
private String accessToken;
private Dialog mDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDialog=WebDialogUtils.createWebDialog(this,"登录中");
//判断是否已经注册到微信
MyApplication.mWXapi.handleIntent(getIntent(), this);
}
// 微信发送请求到第三方应用时,会回调到该方法
@Override
public void onReq(BaseReq baseReq) {
}
// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
//app发送消息给微信,处理返回消息的回调
@Override
public void onResp(BaseResp baseResp) {
Log.d(TAG, "onResp: " + baseResp.errStr);
Log.d(TAG, "onResp: 错误码" + baseResp.errCode);
//ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4(用户拒绝授权) ERR_USER_CANCEL = -2(用户取消)
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_AUTH_DENIED:
Toast.makeText(this, "用户拒绝授权登录", Toast.LENGTH_SHORT).show();
mDialog.dismiss();
finish();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
Toast.makeText(this, "用户取消授权登录", Toast.LENGTH_SHORT).show();
mDialog.dismiss();
finish();
break;
case BaseResp.ErrCode.ERR_OK:
//用户同意授权。
final String code = ((SendAuth.Resp) baseResp).code;
Log.d(TAG, "code: " + code);
new Thread(new Runnable() {
@Override
public void run() {
getAccessToken(code);
}
}).start();
break;
}
}
//获取access_token
private void getAccessToken(String code) {
//这个接口需用get请求
String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APP_ID + "&secret="
+ WX_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url(path)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: 失败");
mDialog.dismiss();
finish();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
Log.d(TAG, "请求微信服务器成功: " + result);
try {
JSONObject jsonObject = new JSONObject(result);
openid = jsonObject.getString("openid");
accessToken = jsonObject.getString("access_token");
UserEntity.setUserWxID(openid);
} catch (JSONException e) {
e.printStackTrace();
}
httpWxLogin = new HttpWxLogin(openid);
httpWxLogin.setReturnHttpResult(new ReturnHttpResult() {
@Override
public void clickReturnHttpResult(String result) {
Log.d(TAG, "clickReturnHttpResult:从服务器获取的数据: " + result);
if (MyApplication.isWxRegister) {
Message message = new Message();
message.obj = result;
WXHandler.sendMessage(message);
} else {
new Thread(new Runnable() {
@Override
public void run() {
bindWX();
}
}).start();
}
}
});
new Thread(new Runnable() {
@Override
public void run() {
httpWxLogin.saveLoginWx();
}
}).start();
getUserInfo();
}
});
}
//检查微信登录
public void checkWXLogin(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
String code = jsonObject.getString("code");
if (code.equals("1")) {
Toast.makeText(this, "该微信号已经注册过", Toast.LENGTH_SHORT).show();
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
UserEntity.setUserID(dataJsonObject.getString("id"));
UserEntity.setUserName(dataJsonObject.getString("name"));
UserEntity.setUserPassword(dataJsonObject.getString("password"));
UserEntity.setUserCity(dataJsonObject.getString("city"));
UserEntity.setUserImg(URL.SERVER_PATH + dataJsonObject.getString("userimg"));
UserEntity.setUserPhone(dataJsonObject.getString("phone"));
UserEntity.setUserWxID(dataJsonObject.getString("wxid"));
UserEntity.setMerchantCaId(dataJsonObject.getString("merchantCaId"));
//该微信号已经注册过
mDialog.dismiss();
startActivity(new Intent(WXEntryActivity.this, HomeActivity.class));
finish();
} else {
//该微信号未被注册过,也可在设置中绑定微信号
UserEntity.setUserWxID(openid);
Toast.makeText(this, "此微信号尚未进行注册,请先注册之后再进行登录", Toast.LENGTH_SHORT).show();
mDialog.dismiss();
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//获取用户信息
private void getUserInfo() {
String path = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(path)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: userinfo" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: userinfo" + response.body().string());
}
});
}
@SuppressLint("HandlerLeak")
Handler WXHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String result = (String) msg.obj;
checkWXLogin(result);
}
};
}
public class HttpWxLogin {
private String openid;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private ReturnHttpResult returnHttpResult;
public HttpWxLogin(String openid) {
this.openid = openid;
}
public void saveLoginWx() {
OkHttpClient client = new OkHttpClient();
Map map = new HashMap<>();
map.put("wxid", openid);
Gson gson = new Gson();
String params = gson.toJson(map);
RequestBody requestBody = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.post(requestBody)
.url("自己项目的登录逻辑地址")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("WXEntryActivityLog", "wxlogin: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
Log.d("WXEntryActivityLog", "wxlogin:得到的返回数据 " + data);
returnHttpResult.clickReturnHttpResult(data);
}
});
}
public void setReturnHttpResult(ReturnHttpResult returnHttpResult) {
this.returnHttpResult = returnHttpResult;
}
}
httpWXlogin这个类就是用来登录自己的服务器的。这里的逻辑根据自己的项目于来的
、关于错误码-6,表示的是你自己的app签名和微信平台注册的签名不一致。可能你自己app还是默认签名,改成正式签名并把平台上的签名一起更改就好了。
微信登录官方文档