萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取 Twitter/X 最新推文:Twitter API v2、OAuth 2.0 Bearer Token 完整實作

⚠️ 重要更新

原文使用 Twitter API v1.1(已停用)且抓取網頁 HTML(脆弱、違反 ToS)。**現代專案必須使用 Twitter API v2 + OAuth 2.0 Bearer Token**。

前置準備

  1. 申請 Twitter Developer 帳號:developer.twitter.com
  2. 建立 Project & App,獲得:API Key、API Secret、Bearer Token
  3. 啟用「Essential」或「Elevated」存取等級以讀取推文

核心 HTTP 客戶端

<?php
class TwitterApiClient
{
    private string $bearerToken;
    private string $baseUrl = 'https://api.twitter.com/2';
    private int $timeout = 10;

    public function __construct(string $bearerToken)
    {
        $this->bearerToken = $bearerToken;
    }

    private function request(string $method, string $endpoint, array $query = [], ?array $body = null): array
    {
        $url = $this->baseUrl . $endpoint;
        if ($query) $url .= '?' . http_build_query($query);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->bearerToken,
                'Content-Type: application/json',
                'User-Agent: MyApp/1.0 (+https://example.com)',
            ],
            CURLOPT_POSTFIELDS => $body ? json_encode($body) : null,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new RuntimeException("cURL error: $error");
        }

        $data = json_decode($response, true);
        
        if ($httpCode >= 400) {
            $msg = $data['detail'] ?? $data['errors'][0]['detail'] ?? "HTTP $httpCode";
            throw new RuntimeException("Twitter API error ($httpCode): $msg");
        }

        return $data;
    }

    // 獲取用戶最近推文
    public function getUserTweets(string $username, int $maxResults = 10, array $expansions = []): array
    {
        // 1. 先解析用戶 ID
        $user = $this->request('GET', "/users/by/username/$username", [
            'user.fields' => 'id,name,username,verified',
        ]);
        $userId = $user['data']['id'] ?? null;
        if (!$userId) throw new RuntimeException("User not found: $username");

        // 2. 獲取推文
        $params = [
            'max_results' => min(100, max(5, $maxResults)),
            'tweet.fields' => 'created_at,public_metrics,conversation_id,lang',
            'exclude' => 'retweets,replies', // 可選:排除轉推/回覆
        ];
        if ($expansions) $params['expansions'] = implode(',', $expansions);

        return $this->request('GET', "/users/$userId/tweets", $params);
    }

    // 獲取單條推文詳情
    public function getTweet(string $tweetId, array $expansions = []): array
    {
        $params = [
            'tweet.fields' => 'created_at,public_metrics,author_id,conversation_id,referenced_tweets',
        ];
        if ($expansions) $params['expansions'] = implode(',', $expansions);
        return $this->request('GET', "/tweets/$tweetId", $params);
    }

    // 搜尋推文(需 Elevated 存取)
    public function searchTweets(string $query, int $maxResults = 10): array
    {
        return $this->request('GET', '/tweets/search/recent', [
            'query' => $query,
            'max_results' => min(100, max(10, $maxResults)),
            'tweet.fields' => 'created_at,author_id,public_metrics,lang',
        ]);
    }
}
?>

使用範例

<?php
require 'TwitterApiClient.php';

$bearerToken = 'YOUR_BEARER_TOKEN_FROM_DEVELOPER_PORTAL';
$client = new TwitterApiClient($bearerToken);

try {
    // 獲取 @elonmusk 最新 5 則推文
    $result = $client->getUserTweets('elonmusk', 5);
    
    foreach ($result['data'] as $tweet) {
        $time = date('Y-m-d H:i:s', strtotime($tweet['created_at']));
        $metrics = $tweet['public_metrics'] ?? [];
        echo "[$time] {$tweet['text']}\n";
        echo "  💬 {$metrics['reply_count']}  🔁 {$metrics['retweet_count']}  ❤️ {$metrics['like_count']}\n\n";
    }
} catch (Throwable $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

速率限制與快取策略

端點限制(15 分鐘窗口)建議快取
GET /2/users/:id/tweets900 請求 / 15min / App5-15 分鐘
GET /2/tweets/search/recent450 請求 / 15min / App10-30 分鐘
GET /2/users/by/username/:username900 請求 / 15min / App永久快取 ID 映射
<?php
// 簡易快取裝飾器
class CachedTwitterClient
{
    private TwitterApiClient $client;
    private $cache; // PSR-16 CacheInterface

    public function __construct(TwitterApiClient $client, $cache)
    {
        $this->client = $client;
        $this->cache = $cache;
    }

    public function getUserTweets(string $username, int $maxResults = 10): array
    {
        $cacheKey = "twitter:tweets:$username:$maxResults";
        $cached = $this->cache->get($cacheKey);
        if ($cached) return $cached;

        $data = $this->client->getUserTweets($username, $maxResults);
        $this->cache->set($cacheKey, $data, 300); // 5 分鐘
        return $data;
    }
}
?>

常見錯誤代碼

代碼含義處理
401UnauthorizedBearer Token 無效/過期/權限不足
403ForbiddenApp 存取等級不足(需 Elevated)
404Not Found用戶/推文不存在
429Too Many Requests速率限制,等待 `x-rate-limit-reset` 秒
503Service UnavailableTwitter 端故障,指數退避重試

前端整合:Web Component 顯示推文

<script type="module">
class TwitterFeed extends HTMLElement {
    async connectedCallback() {
        const username = this.getAttribute('username') || 'twitter';
        const count = parseInt(this.getAttribute('count') || '5');
        
        try {
            const res = await fetch(`/api/twitter/tweets?username=${username}&count=${count}`);
            const data = await res.json();
            
            this.innerHTML = data.data.map(tweet => `
                

${this.escapeHtml(tweet.text)}

💬 ${tweet.public_metrics?.reply_count || 0} 🔁 ${tweet.public_metrics?.retweet_count || 0} ❤️ ${tweet.public_metrics?.like_count || 0}
`).join(''); } catch (e) { this.innerHTML = '

無法載入推文

'; } } escapeHtml(str) { return str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } formatDate(iso) { return new Date(iso).toLocaleString('zh-TW', {dateStyle:'short', timeStyle:'short'}); } } customElements.define('twitter-feed', TwitterFeed); </script> <!-- 使用 --> <twitter-feed username="elonmusk" count="3"></twitter-feed>

Twitter API v2 規範嚴格、速率限制明確,配合快取與錯誤處理,能穩定獲取最新推文資料供前端展示或資料分析使用。

copyright © 萬盛學電腦網 all rights reserved