TikTok for Developers

开发者文档

上次更新时间:2026年11月26日

Android

本指南介绍如何使用 Kotlin 将 Login Kit 集成到 Android 中。完成身份验证的用户授权你的应用后,你可以访问他们的基础 TikTok 个人资料数据,包括他们的昵称和头像。访问其他数据可能需要为其他 scope 进行批准。了解更多:scopes.

先决条件

继续操作前,请确保已完成以下指南中的所有步骤:Android Quickstart.

从你的应用页面获取 client_key 和 client_secret;它们位于“凭据”部分。应用页面位于 TikTok for Developers 网站。导航至 您应用页面中的 产品 部分并点击 添加产品。然后添加 Login Kit。

Android 集成

创建一个授权请求

  1. 创建一个 AuthApi 实例。
  2. 创建一个 AuthRequest 实例并设置以下必需参数:
    1. clientKey = your_client_key: 使用你在 TikTok for Developers 网站上获取的 client key。
    2. scope = user.info.basic: 如果你已获批准获得其他 scopes,请使用逗号分隔的列表将它们包含在内。
    3. redirectUri = your_redirectUri: Redirect URI 决定 TikTok 如何将响应返回到你的应用。该值必须与您为 Android Login Kit 提供的已授权重定向 URI 之一匹配,并遵循一个 https 方案。
    4. codeVerifier = your_codeverifier: 使用 PKCEUtils 生成 code verifier。
  3. 调用 authorize() 方法,该方法位于您的 AuthApi 实例上。
// STEP 1: Create an instance of AuthApi
val authApi = AuthApi(
    activity = [your_activity]
)

// STEP 2: Create an AuthRequest and set parameters
val request = AuthRequest(
    clientKey = clientKey,
    scope = "user.info.basic",
    redirectUri = redirectUri, 
    codeVerifier = codeVerifier
)

// STEP 3: Invoke the authorize method
authApi.authorize(
    request = request,
    authMethod = AuthMethod.TikTokApp / AuthMethod.ChromeTab
);

成功授权后,用户将通过与 redirectUri 关联的 activity 返回到你的应用。

接收回调

// the actvity which will receive the authorization response from TikTok
<activity>
    ...
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        // Note that VIEW action, and DEFAULT & BROWSAbLE categories are necessary.
        <data android:scheme="your_redirect_uri_scheme" />
        <data android:host="your_redirect_uri_host"/>
    </intent-filter>
</activity>

使用 authApi.getAuthResponseFromIntent 从 intent 中解析 AuthResponse。请参阅 MainActivity 在 demo-auth 包中的示例。


authApi.getAuthResponseFromIntent(intent, [your_redirect_uri])?.let { 
    val authCode = it.authCode // The auth code will be used to obtain access token
    val grantedPermissions = it.grantedPermissions // Granted scopes
            
    // Please refer to the Handling Errors for more detail.
    val authError = it.authError
    val authErrorDescription = it.authErrorDescription
    ...
}

获取访问令牌

上传回调中返回的 code以及你的 code_verifier 到你的服务器端,并获取用户访问令牌。参见 用户访问令牌管理 以了解更多信息。

处理错误

请参见 错误处理 以了解更多信息。


TikTok for Developers