iOS SDK 接入

最后更新:2026-03-29 · SDK 版本 v1.0

本文档介绍如何将 XHSOpenSDK 集成到你的 iOS 应用, 实现小红书账号 OAuth2 授权登录。SDK 默认使用 Secret 模式; 完全公开分发、无法在客户端保护 app_secret 的场景可选用 PKCE 模式

兼容性
要求 iOS 12.0+;用户设备需安装小红书 App v9.3.0+

1. 接入前准备

1.1 申请凭证

管理中心创建应用后,你将获得:

凭证说明使用场景
app_id应用唯一标识所有模式必须
app_secret应用密钥仅 Secret 模式使用

2. 添加 SDK

2.1 CocoaPods

# Podfile
target 'YourApp' do
  pod 'XHSOpenSDK', '~> 1.0'
end
$ pod install

2.2 Swift Package Manager

.package(url: "https://github.com/xiaohongshu/XHSOpenSDK-iOS.git", from: "1.0.0")

3. Info.plist 配置

需要配置 URL Scheme 和白名单:

<!-- 应用自身的 URL Scheme(用于接收小红书回调) -->
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>xhs.YOUR_APP_ID</string>
        </array>
    </dict>
</array>

<!-- 允许拉起小红书 App -->
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>xhsdiscover</string>
    <string>xhsopen</string>
</array>

4. 初始化 SDK

AppDelegateapplication:didFinishLaunchingWithOptions: 中注册:

import XHSOpenSDK

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [...]) -> Bool {

    // 注册 app_id 与代理
    XHSAuthInterface.register(
        appId: "YOUR_APP_ID",
        delegate: self
    )

    // 启用 Secret 模式(默认)
    XHSAuthInterface.registerAppSecret("YOUR_APP_SECRET")

    // 或启用 PKCE 模式(完全公开分发、无法保护 app_secret 时使用)
    // XHSAuthInterface.registerPKCE()

    return true
}

5. 发起授权

// 1. 检查小红书是否安装
guard XHSAuthInterface.isXHSAppInstalled() else {
    // 引导用户下载小红书
    return
}

// 2. 构造授权请求
let req = XHSAuthRequest()
req.scope = "basic_info"
req.state = UUID().uuidString  // 建议使用随机字符串防 CSRF

// 3. 发起授权(会拉起小红书 App)
XHSAuthInterface.startAuth(with: req)

6. 处理回调

AppDelegate 中添加:

func application(_ app: UIApplication,
                 open url: URL,
                 options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    return XHSAuthInterface.handleOpenURL(url, options: options)
}

实现 XHSAuthDelegate 协议以接收结果:

extension AppDelegate: XHSAuthDelegate {

    // 授权结果(拿到 code)
    func onAuthResponse(_ response: XHSAuthResponse) {
        if response.result == .success {
            print("授权成功,code = \(response.code)")
            // SDK 会自动使用 code 换取 token,无需手动处理
        } else {
            print("授权失败:\(response.message)")
        }
    }

    // Token 获取/刷新结果
    func onAccessTokenResponse(_ response: XHSAccessTokenResponse) {
        if response.result == .accessTokenStored {
            print("access_token = \(response.accessToken)")
            print("过期时间 = \(response.expireTime)")
            print("open_id = \(response.openId)")
        }
    }

    // 用户信息
    func onUserInfoResponse(_ response: XHSUserinfoResponse) {
        if response.result == .success {
            print("昵称 = \(response.userNickName)")
            print("头像 = \(response.userImgPath)")
        }
    }

    // Refresh Token 过期,需要重新授权
    func onRefreshTokenExpired(_ appId: String, message: String) {
        // 引导用户重新登录
    }
}

7. 获取用户信息

SDK 内部会用当前 access_token 请求 /oauth2/batch_get_min_user_info

XHSAuthInterface.getUserInfo()
// 结果通过 onUserInfoResponse: 回调返回

8. Token 管理

8.1 获取当前 Access Token(含自动刷新)

let at = XHSAuthInterface.getCurrentAT()
// - AT 未过期 → 返回可用的 access_token
// - AT 已过期 & RT 未过期 → 触发异步刷新,本次返回 nil
// - RT 已过期 → 返回 nil,需引导用户重新授权

8.2 定时刷新

// 每 1 小时自动刷新一次 access_token
XHSAuthInterface.startAutoRefresh(withInterval: 3600)

// 停止定时刷新
XHSAuthInterface.stopAutoRefresh()

8.3 查询剩余时间

let atRemaining = XHSAuthInterface.currentAccessTokenRemainingTime()  // 秒
let rtRemaining = XHSAuthInterface.currentRefreshTokenRemainingTime() // 秒

9. 授权结果码

枚举说明
0XHSAuthResultSuccess授权成功
-1XHSAuthResultCancel用户取消授权
-2XHSAuthResultNetworkErr网络错误
-3XHSAuthResultInvalidParams参数非法
-101XHSAuthResultNotInstalled小红书 App 未安装
-102XHSAuthResultNotSupported小红书版本过低
-200XHSAuthResultAccessTokenStoredToken 获取成功
-300XHSAuthResultRefreshTokenExpiredRefresh Token 已过期

10. 完整 API 速查

API说明
+registerAppId:delegate:注册应用
+registerPKCE启用 PKCE 模式
+registerAppSecret:启用 Secret 模式
+isXHSAppInstalled检查小红书是否已安装
+startAuthWithRequest:发起授权
+handleOpenURL:options:处理授权回调
+getCurrentAT获取当前 access_token
+getUserInfo获取用户信息
+startAutoRefreshWithInterval:开启定时刷新
+cancelAuthorizationWithAppId:取消授权

11. 安全建议

  1. 妥善保护 app_secret:Secret 模式下请使用 Keychain 或加密存储 app_secret,避免明文硬编码到 IPA 中;完全公开分发且无法保护的场景可选用 PKCE 模式
  2. 验证 state 参数:使用随机字符串防止 CSRF 攻击
  3. 安全存储 Token:使用 Keychain 保存 access_token / refresh_token,不要写入 UserDefaults
  4. HTTPS 传输:所有网络请求必须走 HTTPS