導讀:部落格、CMS 系統常需發文時同步推送至微博。本文系統梳理新浪微博開放平台接入流程:開發者認證、應用審核、OAuth 2.0 授權碼模式、Access Token 管理、發文介面調用、內容截取與清洗,提供可直接落地的代碼架構。
App Key (WB_AKEY) 與 App Secret (WB_SKEY)。call.php)<?php
include_once 'sina_config.php'; // 定義 WB_AKEY, WB_SKEY, WB_CALLBACK_URL
include_once 'saetv2.ex.class.php'; // 官方 SDK 核心類
$oauth = new SaeTOAuthV2(WB_AKEY, WB_SKEY);
$authUrl = $oauth->getAuthorizeURL(WB_CALLBACK_URL);
// 重定向至新浪授權頁
header("Location: " . $authUrl);
exit;
callback.php)<?php
include_once 'sina_config.php';
include_once 'saetv2.ex.class.php';
$oauth = new SaeTOAuthV2(WB_AKEY, WB_SKEY);
if (isset($_REQUEST['code'])) {
$keys = [
'code' => $_REQUEST['code'],
'redirect_uri' => WB_CALLBACK_URL
];
try {
$token = $oauth->getAccessToken('code', $keys);
} catch (OAuthException $e) {
logError("Weibo OAuth Error: " . $e->getMessage());
exit('授權失敗');
}
}
if (!empty($token)) {
// 儲存 Token (Session/Redis/DB),有效期內複用
$_SESSION['weibo_token'] = $token;
// 實例化 API 客戶端
$client = new SaeTClientV2(WB_AKEY, WB_SKEY, $token['access_token']);
// 發送微博
$weiboContent = buildWeiboContent($article); // 見下文構建邏輯
$ret = $client->update($weiboContent);
if (isset($ret['error_code']) && $ret['error_code'] > 0) {
logError("Weibo Send Failed: {$ret['error_code']} - {$ret['error']}");
} else {
logInfo("Weibo Sync Success: {$ret['id']}");
}
}
微博限制 140 個字符 (中文算 1 字),需精確計算並預留短連結空間 (t.cn 短連結固定佔 20 字符)。
class WeiboPublisher {
private $title;
private $summary;
private $id;
public function __construct($title, $summary, $id) {
$this->title = $title;
$this->summary = $summary;
$this->id = $id;
}
public function getWeiboText() {
$titleLen = mb_strlen($this->title, 'UTF-8');
$summaryLen = 115 - $titleLen; // 140 - 20(短鏈) - 5(【】...) = 115
$cleanSummary = $this->stripHtmlTags($this->summary);
if (mb_strlen($cleanSummary, 'UTF-8') >= $summaryLen) {
$cleanSummary = mb_substr($cleanSummary, 0, $summaryLen, 'UTF-8');
}
$shortUrl = $this->generateShortUrl($this->id); // 對接短網址服務
return sprintf('【%s】%s... %s', $this->title, $cleanSummary, $shortUrl);
}
// 徹底移除 HTML 標籤、空白實體
private function stripHtmlTags($string) {
$string = strip_tags($string);
$string = preg_replace('/\s+/u', '', $string); // 含換行、空格、
return $string;
}
}
mb_strlen() / mb_substr():正確處理多字節字符 (UTF-8 中文算 1 字),避免 strlen() 按字節計算導致截斷錯誤。strip_tags():移除所有 HTML/PHP 標籤。| 項目 | 建議 |
|---|---|
| Token 儲存 | Redis/資料庫持久化,含 expires_in 時間戳,自動刷新機制 |
| 錯誤重試 | 網路抖動時指數退避重試 (最多 3 次),記錄失敗隊列人工介入 |
| 頻率控制 | 遵守接口限制 (如 100 次/小時/用戶),佇列化發送 |
| 內容合規 | 敏感詞過濾、圖片尺寸壓縮 (upload 介面單張 ≤ 5MB) |
| 日誌審計 | 記錄請求/響應全鏈路,便於排查 error_code (如 21322 重複內容) |
完整 SDK 下載:新浪微博開放平台 SDK | 介面文檔:statuses/update