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用户取消
-206SDK未初始化、初始化失败
-207没有安装百度系app
-208百度系app版本号太低