完成 OAuth 認證並獲取 Access Token 後,即可調用微博開放平台 API 發布微博。本文基於前文儲存的 oauth_token 與 oauth_token_secret,示範如何使用封裝好的 WeiboClient 類發布文字微博,並處理常見錯誤碼與回應解析。
oauth_token、oauth_token_secretWeiboClient 類(或同等 OAuth 1.0a 簽名 HTTP 客戶端)<?php
require_once 'config.php';
require_once 'weiboclient.php'; // 需支援 OAuth 1.0a 簽名的客戶端類
session_start();
// 1. 從 Session/資料庫獲取 Token
if (empty($_SESSION['user']['oauth_token']) || empty($_SESSION['user']['oauth_token_secret'])) {
die('用戶未授權或 Token 遺失,請重新登入授權');
}
$accessToken = $_SESSION['user']['oauth_token'];
$accessTokenSecret = $_SESSION['user']['oauth_token_secret'];
// 2. 實例化客戶端
$client = new WeiboClient(WB_AKEY, WB_SKEY, $accessToken, $accessTokenSecret);
// 3. 準備發布內容
$statusText = "測試發表微博 " . date('Y-m-d H:i:s'); // 避免重複內容被過濾
$statusText = mb_substr($statusText, 0, 140, 'UTF-8'); // 微博 140 字限制
// 4. 呼叫 statuses/update 介面
$response = $client->update($statusText);
// 5. 處理回應
if ($response === false || $response === null) {
error_log("微博發布失敗:網路錯誤或客戶端異常");
echo "發布失敗:網路異常";
exit;
}
// 微博 API 錯誤回應格式:{"error":"...", "error_code":..., "request":"/statuses/update"}
if (isset($response['error_code']) && isset($response['error'])) {
$errorCode = $response['error_code'];
$errorMsg = $response['error'];
// 常見錯誤碼處理
$errorMessages = [
400 => '請求參數錯誤',
401 => 'Token 無效或過期,需重新授權',
403 => '權限不足(未審核通過/超出頻率限制)',
404 => '介面不存在',
10001 => '參數缺失',
10002 => '參數值非法',
20001 => '用戶未登入',
20003 => '用戶不存在',
20012 => '內容為空',
20013 => '內容過長',
20014 => '重複內容',
20018 => '包含敏感詞',
20019 => '包含惡意連結',
20101 => '未授權該介面',
20111 => '應用未授權',
];
$friendlyMsg = $errorMessages[$errorCode] ?? "未知錯誤 (Code: {$errorCode})";
error_log("微博發布失敗:[{$errorCode}] {$errorMsg}");
echo "發布失敗:{$friendlyMsg}";
exit;
}
// 6. 成功回應解析
// 成功格式:{"created_at":"...", "id":1234567890, "text":"...", "user":{...}, ...}
$weiboId = $response['id'] ?? $response['mid'] ?? 'unknown';
$createdAt = $response['created_at'] ?? 'unknown';
$text = $response['text'] ?? $statusText;
echo "發布成功!\n";
echo "微博 ID: {$weiboId}\n";
echo "發布時間: {$createdAt}\n";
echo "內容: {$text}\n";
// 可選:同步儲存至本地資料庫
// $pdo->prepare("INSERT INTO user_weibos (user_id, weibo_id, content, created_at) VALUES (?, ?, ?, ?)")
// ->execute([$_SESSION['user']['id'], $weiboId, $text, $createdAt]);
?>
<?php
class WeiboClient
{
private $consumerKey;
private $consumerSecret;
private $accessToken;
private $accessTokenSecret;
private $apiBase = 'https://api.weibo.com';
public function __construct(string $ck, string $cs, string $at, string $ats)
{
$this->consumerKey = $ck;
$this->consumerSecret = $cs;
$this->accessToken = $at;
$this->accessTokenSecret = $ats;
}
public function update(string $status, array $extraParams = []): mixed
{
$url = "{$this->apiBase}/2/statuses/update.json";
$params = array_merge(['status' => $status], $extraParams);
return $this->oauthRequest($url, 'POST', $params);
}
// 同 weibooauth.php 的 oauthRequest 方法
private function oauthRequest(string $url, string $method, array $params): mixed
{
// ... 簽名邏輯同前文 ...
// 返回 json_decode($response, true)
}
}
?>
<?php
// 1. 先上傳圖片獲取 pic_id
$picResponse = $client->uploadPic('path/to/image.jpg');
if (isset($picResponse['pic_id'])) {
$picId = $picResponse['pic_id'];
// 2. 發布微博時帶上 pic_id
$response = $client->update('分享一張圖片', ['pic_id' => $picId]);
}
// upload_pic 介面:POST https://api.weibo.com/2/statuses/upload.json
?>
| 介面 | 限制 | 建議策略 |
|---|---|---|
| statuses/update | 單用戶 100 次/小時,全應用 1000 次/小時 | 佇列異步處理、錯誤重試指數退避、用戶級頻率提示 |
| statuses/upload | 單用戶 50 次/小時 | 圖片預處理壓縮、CDN 加速 |
| statuses/destroy | 單用戶 100 次/小時 | 謹慎提供刪除功能 |
發布請求
│
├─ 網路層失敗 (timeout/connection refused) → 重試 3 次 (指數退避) → 仍失敗 → 寫入失敗佇列,人工/定時重試
│
├─ HTTP 非 200 → 記錄日誌 → 返回系統錯誤
│
└─ HTTP 200 但含 error_code
│
├─ 401/20101/20111 (Token 無效/未授權) → 清除本地 Token → 導向重新授權
│
├─ 20014 (重複內容) → 提示用戶修改內容
│
├─ 20018/20019 (敏感/惡意) → 提示內容違規,不重試
│
├─ 403/10002 (頻率限制/參數錯誤) → 等待恢復/修正參數後重試
│
└─ 其他 → 記錄詳情 → 返回友好錯誤提示
微博發布核心流程:獲取 Token → 實例化簽名客戶端 → 呼叫 statuses/update → 解析回應 → 分類處理錯誤碼。關鍵在於:
/2/statuses/update.json 仍相容,但建議使用新版端點)本文代碼可直接整合至擁有微博登入功能的系統,實現「一鍵同步發布」等社交功能。