微信登录接入步骤:
事先准备:
以下两个字段在微信开发平台会有,AppSecret在官网上不会储存了,自行保管,但是可以重置
AppID:xxxxxx
AppSecret:yyyyyy
依赖:
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
权限:
<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"/>
WXEntryActivity注册:对于微信登录来说,该类只能放在(包名.wxapi)目录下
<activity
android:name=".wxapi.WXEntryActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
WXEntryActivity类如下:
public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, AppID, false);
//下方注册代码若不行,可以放在BaseApplication中的onCreate();方法中或者是登录页面的Activity中注册
api.registerApp(AppID);
api.handleIntent(getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
//微信发送的请求将回调以下方法
@Override
public void onReq(BaseReq req) {
switch (req.getType()) {
case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
break;
case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
break;
default:
break;
}
}
//发送到微信请求的响应结果将回调以下方法
@Override
public void onResp(BaseResp resp) {
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
//获取回传的code(临时票据参数)
String code = ((SendAuth.Resp) resp).code;
finish();
//保存微信的用户信息(该方法里面是把信息提供给了接口)code加上APPID和AppSecret,通过API 换取access_token
getAccessToken(WXEntryActivity.this, code);
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
//取消
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
//发送被拒绝
break;
default:
break;
}
}
}
步骤一:点击微信登录后,首先调用微信登录授权接入
//点击微信登录的按钮
wxImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginWx();
}
});
/**
* 微信登录授权接入
*/
public static void loginWx() {
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo_test";
api.sendReq(req);
}
步骤二:授权通过后,在WXEntryActivity中的onResp()方法中获取微信回传的临时票据参数code,该参数的作用在于与AppID和AppSecret获取openid 和access_token。
/**
* 获取微信用户的openid和access_token(接口凭证)
*/
public static void getAccessToken(final Activity activity, String code) {
if (!TextUtils.isEmpty(code) && !code.equals("null")) {
final OkHttpClient okHttpClient = new OkHttpClient();
String accessCodeUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
HashMap<String, String> map = new HashMap<>();
map.put("appid", AppID);
map.put("secret", AppSecret);
map.put("code", code);
map.put("grant_type", "authorization_code");
String paramStr = getParams(accessCodeUrl, map);//获取带参数的url
Request request = new Request.Builder().url(paramStr).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {//带上请求之后的回传
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String value = response.body().string();
try {
JSONObject object = new JSONObject(value);
//该回传的值中包含openid和access_token字段
String openid = object.getString("openid");
String access_token = object.getString("access_token");
//获取到以上字段之后就是获取用户的相关信息
getUserInfo(activity, okHttpClient, openid, access_token);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
其中,getUserInfo()为获取用户信息的方法,通过openid 和access_token参数获取用户信息:
/**
* 获取微信用户信息
* @param activity
* @param okHttpClient
* @param openid
* @param access_token
*/
public static void getUserInfo(final Activity activity, OkHttpClient okHttpClient, String openid, String access_token) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("openid", openid);
param.put("access_token", access_token);
String paramsStr = HttpManager.getParams("https://api.weixin.qq.com/sns/userinfo", param);
Request request = new Request.Builder().url(paramsStr).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String value = response.body().string();
try {
JSONObject object = new JSONObject(value);
activity.finish();
JSONObject valueObject = new JSONObject();
//该回传的值中包含用户信息等几个字段
valueObject.put("openId", object.getString("openid"));
valueObject.put("nickname", object.getString("nickname"));
valueObject.put("avatar", object.getString("headimgurl"));
valueObject.put("unionid", object.getString("unionid"));
int sex = object.getInt("sex");
if (sex == 1) {
valueObject.put("gender", "男");
} else {
valueObject.put("gender", "女");
}
//此时valueObject里包含了用户各字段的信息
authLogin(valueObject);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
其中getParams()为获取带有参数的url拼接:
/**
* 获取带有参数的url拼接
* @param url
* @param param
*/
public static String getParams(String url, HashMap<String, String> param) {
String getparams = "";
for (Map.Entry<String, String> entry : param.entrySet()) {
getparams = getparams + entry.getKey() + "=" + entry.getValue() + "&";
}
if (getparams.length() > 1) {
getparams = getparams.substring(0, getparams.length() - 1);
}
url = url + "?" + getparams;
LogUtil.logI("url:" + url);
return url;
}
其中 authLogin()为微信登录请求后台API的方法:
/**
* 微信登录的请求接口
* @param openId
* @param nickname
* @param avatar
* @param userType
* @param unionid
*/
public void authLogin(JSONObject jsonObject) {
String nickname = jsonObject.getString("nickname");
String openId = jsonObject.getString("openId");
String avatar = jsonObject.getString("avatar");
String unionid = jsonObject.getString("unionid");
//请求登录的具体字段应根据后台来定
HashMap<String, String> param = new HashMap<>();
param.put("openId", openId);//openid授权用户唯一标识
param.put("nickname", nickname);//用户名称
param.put("avatar", avatar);//用户头像地址
param.put("userType", “微信登录”);//登录类型
param.put("unionId", unionid);//当且仅当该移动应用已获得该用户的userinfo授权时,才会出现该字段
manager.post(NetworkAPI.Oauth_Login, new HttpCallback() {
@Override
public void onSuccess(int code, String value, String msg, String pageStr) {
if (code == RequestSucceed) {
//登录成功之后存下用户信息类
spUtil.putString("user", value);
//用户信息实体类
UserBean user = GsonUtil.toBean(value, UserBean.class);
//此时登录已成功!!
}
}
@Override
public void onFailure(String value) {
}
}, param);
}
结束。
网友评论