在今天的移動互聯網時代,授權登陸已經成為了越來越多APP的常用功能之一,尤其是在APP啟動階段,為了減少新註冊用戶的流失率,授權登陸也是一個非常好的方案之一。微信是現在一個使用人數非常多的社交應用,如果我們在我們自己的APP上集成微信的授權登陸功能將會是一個很有必要的事情。接下來,本文將會從如下幾個方面對微信授權登陸在android應用中的實現進行詳細說明。
一、微信開放平台申請AppID
在開始之前,我們需要在微信開放平台去申請我們自己的APPID,這個AppID將會作為我們的安卓應用和微信交互的唯一標識。我們可以在微信開放平台官網上找到申請入口。
// 如下代碼為小程序中獲取wxcode的方法
private void getWXCode() {
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = STATE;
api.sendReq(req);
}
二、使用微信SDK實現微信授權登陸功能
微信提供了一個非常方便易用的SDK去實現微信授權登陸的功能。在開始之前,我們需要在我們的項目中將微信SDK引入。
dependencies {
compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
}
之後,在我們需要使用微信授權登陸的地方加入如下代碼:
// 實現IWXAPIEventHandler接口
private IWXAPI api;
private void initWXApi() {
api = WXAPIFactory.createWXAPI(this, APPID, true);
api.registerApp(APPID);
api.handleIntent(getIntent(), this);
}
// 微信登陸
private void wechatLogin() {
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = STATE;
api.sendReq(req);
}
三、獲取微信授權登陸後的用戶信息
在用戶允許我們的應用後,我們就可以獲得微信給我們回調的code了。我們可以通過這個code去獲取到用戶的access token和openid。
// 獲取用戶信息
private void getUserInfo(String code) {
OkHttpClient client = new OkHttpClient();
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
try {
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
String openid = jsonObject.getString("openid");
String url = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + access_token + "&openid=" + openid;
OkHttpClient client1 = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call1 = client.newCall(request);
call1.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Message message = new Message();
message.what = 0;
Bundle bundle = new Bundle();
bundle.putString("userInfo", result);
message.setData(bundle);
handler.sendMessage(message);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
四、小結
到這裡,我們已經成功地在android應用中將微信授權登陸的功能集成了起來,並且可以正確地獲取到已授權用戶的信息。授權登陸不僅可以讓用戶不必再次進行繁瑣的註冊流程,也是我們APP收集用戶信息的方式之一。期望這篇文章對大家有所幫助!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/288686.html