微博開放平台採用 OAuth2.0 授權碼模式。本文基於官方 PHP SDK(saetv2.ex.class.php),詳細拆解:應用創建、SDK 配置、授權跳轉、回調處理換取 Access Token、調用用戶信息接口的完整代碼流程。
<?php
header('Content-Type: text/html; charset=UTF-8');
define('WB_AKEY', '你的App Key');
define('WB_SKEY', '你的App Secret');
define('WB_CALLBACK_URL', 'https://你的域名/callback.php'); // 必須與後台設置一致
// 常量 CANVAS_PAGE 供 SDK 內部使用
define('CANVAS_PAGE', WB_CALLBACK_URL);
?>
<?php
require_once 'config.php';
require_once 'saetv2.ex.class.php';
$oauth = new SaeTOAuth(WB_AKEY, WB_SKEY);
$authUrl = $oauth->getAuthorizeURL(CANVAS_PAGE);
echo '微博授權登錄';
/*
生成的授權地址類似:
https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REDIRECT_URI
*/
?>
<?php
require_once 'config.php';
require_once 'saetv2.ex.class.php';
if (isset($_REQUEST['code'])) {
$oauth = new SaeTOAuth(WB_AKEY, WB_SKEY);
$keys = [
'code' => $_REQUEST['code'],
'redirect_uri' => CANVAS_PAGE,
];
$token = $oauth->getAccessToken('code', $keys);
// $token 結構:['access_token'=>..., 'expires_in'=>..., 'remind_in'=>..., 'uid'=>...]
if (isset($token['access_token']) && $token['access_token']) {
// 存儲到 Session/數據庫/緩存
$_SESSION['wb_token'] = $token;
header('Location: user_info.php'); // 跳轉獲取用戶信息
exit;
} else {
echo "獲取 Access Token 失敗: ";
var_dump($token);
}
} else {
echo "缺少 code 參數,可能用戶拒絕授權";
}
?>
<?php
require_once 'config.php';
require_once 'saetv2.ex.class.php';
session_start();
if (!isset($_SESSION['wb_token'])) {
header('Location: login.php');
exit;
}
$token = $_SESSION['wb_token'];
$client = new SaeTClientV2(WB_AKEY, WB_SKEY, $token['access_token']);
// 根據 UID 獲取用戶資料
$uid = $token['uid'];
$userInfo = $client->show_user($uid); // 對應 API: users/show
/*
返回示例:
[
'id' => 1234567890,
'screen_name' => '用戶昵稱',
'profile_image_url' => '頭像URL',
'gender' => 'm',
'location' => '北京',
'followers_count' => 1000,
'friends_count' => 500,
'statuses_count' => 200,
...
]
*/
echo "歡迎, {$userInfo['screen_name']}!
";
echo '
';
?>
| 類 | 方法 | 用途 |
|---|---|---|
| SaeTOAuth | getAuthorizeURL($redirect_uri) | 生成授權頁 URL |
| SaeTOAuth | getAccessToken('code', $keys) | 用 code 換取 Access Token |
| SaeTClientV2 | show_user($uid_or_name) | 獲取用戶資料 (users/show) |
| SaeTClientV2 | update($status, $pic_path) | 發布微博 (statuses/update) |
| SaeTClientV2 | home_timeline($page, $count) | 獲取首頁微博流 |
state 防 CSRF,回調驗證。OAuthException,友好提示用戶重試。遵循標準 OAuth2 流程 + 官方 SDK,可快速穩健接入微博登錄,為應用引入社交身份體系。