Android 接入指南
优质
小牛编辑
130浏览
2023-12-01
1. 集成SDK
将下载的baidu-oauth-sdk-android-release-XXX.zip文件解压后的baidu-oauth-sdk-XXX.aar添加到工程
2. 初始化SDK
AuthInfo authInfo = new AuthInfo({context}, {appKey}, {redirectUrl}, {scope});
BdOauthSdk.init(authInfo);
3. 申请授权
bdSsoHandler = new BdSsoHandler(MainActivity.this);
BdOauthDTO bdOauthDTO = new BdOauthDTO();
// BdOauthDTO.OAUTH_TYPE_BOTH 若安装了百度系APP调起SSO授权,否则调起web授权
// BdOauthDTO.OAUTH_TYPE_SSO 若安装了百度系APP调起SSO授权,否则返回异常
// BdOauthDTO.OAUTH_TYPE_WEB 调起web授权
bdOauthDTO.oauthType = BdOauthDTO.OAUTH_TYPE_BOTH;
// 重定向后会携带state参数,建议开发者利用state参数来防止CSRF攻击
bdOauthDTO.state = UUID.randomUUID().toString();
bdSsoHandler.authorize(bdOauthDTO, new BdOauthCallback() {
@Override
public void onSuccess(BdOauthResult result) {
ViewUtility.showToast("code = " + result.getCode() + " state = " + result.getState());
}
@Override
public void onFailure(BdOauthResult result) {
ViewUtility.showToast("result code = " + result.getResultCode() + " msg = " + result.getResultMsg());
}
});
code 换取 access_token 参考 code获取授权access_token
4. 处理回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 因为sdk通过startActivityForResult启动授权页面,所以需要产品线在调用activity接收返回
if (bdSsoHandler != null) {
bdSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
5. 错误码列表
错误码 | 含义 |
---|---|
0 | 成功 |
-201 | 其他错误 |
-202 | 参数错误 |
-203 | 网络异常 |
-204 | 服务返回的异常 |
-205 | 用户取消 |
-206 | SDK未初始化、初始化失败 |
-207 | 没有安装百度系app |
-208 | 百度系app版本号太低 |