快速开始

Youyun 基于 OAuth 2.0 授权码模式,本文档帮助你快速接入。

前置条件

  • 一个 Youyun 管理员账号
  • 在管理后台创建的应用凭证(Client ID 和 Client Secret)
  • 一个可接收回调的后端服务

API 基础地址

所有 API 请求的基础地址为:https://api.yun52.cn

例如授权地址为 https://api.yun52.cn/api/oauth.php,文档中的接口路径均相对于此地址。

1. 创建应用

登录管理后台(youyou.php),在「应用管理」中创建新应用,获得 Client ID 和 Client Secret。

2. 引导用户授权

$clientId = "你的Client ID"; $redirectUri = "https://your-app.com/callback"; $state = bin2hex(random_bytes(16)); $authUrl = "https://api.yun52.cn/api/oauth.php" . "?action=authorize" . "&client_id=" . urlencode($clientId) . "&redirect_uri=" . urlencode($redirectUri) . "&state=" . urlencode($state); header("Location: " . $authUrl);

3. 处理回调

$code = $_GET['code']; $state = $_GET['state']; if ($state !== $_SESSION['oauth_state']) { die('Invalid state'); }

4. 换取 Access Token

必须使用 POST 方法:

$postData = http_build_query([ 'code' => $code, 'client_id' => $clientId, 'client_secret' => $clientSecret, 'redirect_uri' => $redirectUri, ]); $ctx = stream_context_create(['http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => $postData, ]]); $response = json_decode(file_get_contents( "https://api.yun52.cn/api/oauth.php?action=token", false, $ctx ), true); $accessToken = $response['access_token'];

5. 获取用户信息

支持 GET 和 POST:

$userInfo = json_decode(file_get_contents( "https://api.yun52.cn/api/oauth.php?action=verify" . "&access_token=" . urlencode($accessToken) ), true); if ($userInfo['valid']) { $userId = $userInfo['user']['id']; $username = $userInfo['user']['username']; $avatar = $userInfo['user']['avatar']; // base64 Data URI,空字符串表示未设置 }