目前微信/微博作为第三方登录也比较流行,也有整合第三方登录的方式比如sharesdk,友盟之类的。但是项目中独立整合第三方登录对熟悉相关的SDK也是有意义的。
微信登录/分享的文档路径为https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319167&token=ba3e4911036eb232f54ab39efc023930d7cfc60e&lang=zh_CN
APP添加微信登录需要如下步骤:
1.申请APP ID
2.下载上面路径中的android开发包,并将wxapi文件夹加入工程中
3.在manifest中添加如下代码
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true"
android:label="@string/app_name"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="AppID"/>
</intent-filter>
</activity>
4.在需要添加微信登录的页面中添加如下代码
private IWXAPI api;
onCreate() -> initWX(); ->
private void initWX() {
api = WXAPIFactory.createWXAPI(LoginActivity.this, null);
api.registerApp(WXAppContants.APP_ID);
}
5.点击微信登录按钮
icon_wechat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "*****";//可以为package name
api.sendReq(req);
}
});
6.通过上面代码就可以弹出微信第三方授权页面了,点击确认即可。然后进入WXEntryActivity页面onResp函数
@Override
public void onResp(BaseResp baseResp) {
int result = 0;
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
result = R.string.errcode_success;
try {
SendAuth.Resp sendResp = (SendAuth.Resp) baseResp;
// 参考文档 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317853&token=&lang=zh_CN 内容
<span style="background-color: rgb(51, 51, 255);">**通过 https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code 获取内容</span>
} catch (Exception e) {
e.printStackTrace();
}
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
result = R.string.errcode_cancel;
finish();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result = R.string.errcode_deny;
finish();
break;
default:
result = R.string.errcode_unknown;
finish();
break;
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
7.在上面**中返回如下内容:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
8.有了上面内容后即可获取个人信息,参考https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
private void doGetUserInfo(JSONObject response) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("openid", response.optString("openid"));
paramMap.put("access_token", response.optString("access_token"));
paramMap.put("lang", "zh_CN");
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%1$s&openid=%2$s&lang=zh_CN";
new WXUserInfoTask().execute(String.format(url,
response.optString("access_token"),
response.optString("openid")));
}
class WXUserInfoTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
StringBuffer strBuffer = new StringBuffer();
while ((len = is.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
return new String(outputStream.toByteArray());
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(String strInfo) {
if (strInfo == null) {
CommonUtil.showToast(WXEntryActivity.this,
R.string.str_error_wxinfo);
finish();
} else {
// 这里即可对用户信息做相关处理
}
}
}
其中上面的**也可参考上面的方式处理
注意点:
1.如果无法显示授权页面的话,应该是注册信息不对导致。故可以确认相关信息。
包括需要输入正确的编译参数SHA值,区分是debug版本还是release版本