萬盛學電腦網

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

網頁整合 Facebook 分享功能:Open Graph 標籤、分享對話框、SDK 完整實作指南

Facebook 分享的兩種主要方式

方式特點適用場景
Share Dialog (Web)彈出 Facebook 官方分享視窗,無需登入授權,自帶預覽簡單分享按鈕、部落格文章、產品頁
JavaScript SDK (FB.ui)嵌入式體驗、可程式化控制、需載入 SDK單頁應用、需回調處理、自訂 UI
手動構建 sharer.php URL最簡單、無 SDK 依賴、功能受限靜態頁面、郵件模板、極簡需求

核心前置作業:Open Graph Meta 標籤(必須)

Facebook 爬蟲抓取分享預覽資訊完全依賴頁面上的 og: 標籤,而非 URL 參數。必須在 <head> 區塊完整部署:

<head>
  <meta property="og:url" content="https://example.com/article/123" />
  <meta property="og:type" content="article" />
  <meta property="og:title" content="文章標題 | 網站名稱" />
  <meta property="og:description" content="文章摘要描述,建議 2-4 句,約 150-200 字元" />
  <meta property="og:image" content="https://cdn.example.com/images/article-123-cover.jpg" />
  <meta property="og:image:width" content="1200" />
  <meta property="og:image:height" content="630" />
  <meta property="og:image:alt" content="圖片替代文字" />
  <meta property="og:site_name" content="網站名稱" />
  <meta property="og:locale" content="zh_TW" />
  <meta property="article:published_time" content="2024-01-15T10:30:00+08:00" />
  <meta property="article:author" content="https://example.com/author/john" />
  <meta property="article:tag" content="PHP" />
  <meta property="article:tag" content="Web開發" />
</head>

圖片規格嚴格要求(避免預覽無圖/裁切錯誤)

  • 最小尺寸:200×200 px
  • 推薦尺寸:1200×630 px(1.91:1 比例),適用 Feed/動態/連結預覽
  • 最大檔案:8 MB
  • 格式:JPEG、PNG、WebP、GIF(首幀)
  • HTTPS 必須:HTTP 圖片會被忽略
  • 多圖支援:可放多個 og:image,用戶分享時可選擇

方式一:手動構建 sharer.php URL(零依賴)

<a 
  href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fexample.com%2Farticle%2F123"
  target="_blank"
  rel="noopener noreferrer"
  onclick="window.open(this.href, 'fb-share', 'width=640,height=480'); return false;"
>
  分享到 Facebook
</a>

參數說明:

  • u:必填,目標 URL(需 URL encode),Facebook 會抓取此 URL 的 og: 標籤
  • quote:可選,預填引用文字(用戶可編輯)
  • hashtag:可選,預填標籤(如 #PHP)

方式二:JavaScript SDK 完整整合(推薦 SPA/動態頁)

<!-- 1. 載入 SDK(建議放在 <body> 開頭後) -->
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" 
  src="https://connect.facebook.net/zh_TW/sdk.js#xfbml=1&version=v19.0&appId=YOUR_APP_ID&autoLogAppEvents=1">
</script>

<!-- 2. 分享按鈕觸發 -->
<button id="fb-share-btn" class="btn">分享到 Facebook</button>

<script>
document.getElementById('fb-share-btn').addEventListener('click', function() {
  FB.ui({
    method: 'share_open_graph',
    action_type: 'og.shares',
    action_properties: JSON.stringify({
      object: {
        'og:url': 'https://example.com/article/123',
        'og:title': '動態生成的標題',
        'og:description': '動態生成的描述',
        'og:image': 'https://cdn.example.com/dynamic-image.jpg',
      }
    })
  }, function(response) {
    if (response && !response.error_message) {
      console.log('分享成功', response);
      // 可觸發 GA/GTM 事件追蹤
      gtag('event', 'share', { method: 'facebook', content_id: '123' });
    } else {
      console.log('用戶取消或錯誤', response);
    }
  });
});
</script>

方式三:Share Button Plugin(最簡單嵌入)

<!-- 在需顯示按鈕處放入 -->
<div 
  class="fb-share-button" 
  data-href="https://example.com/article/123" 
  data-layout="button_count"
  data-size="large"
  data-mobile_iframe="true"
></div>

屬性說明:data-layout (button_count/button/icon_link)、data-size (small/large)、data-mobile_iframe (行動裝置用 iframe 而非彈窗)。

Facebook 爬蟲快取與除錯工具

Facebook 會快取 og: 標籤內容(通常 24-48 小時)。內容更新後必須主動刷新:

  1. 分享除錯工具:developers.facebook.com/tools/debug/ 輸入 URL → 「再次抓取」
  2. Graph API 刷新:POST https://graph.facebook.com/?id={URL}&scrape=true&access_token={APP_ACCESS_TOKEN}
  3. 批次刷新:開發者儀表板 → 分享除錯 → 批次失效

常見問題排查

問題原因解決
分享預覽無圖片og:image 缺失/HTTP/尺寸過小/robots.txt 封鎖檢查除錯工具「Open Graph 資料」區塊
標題/描述未更新Facebook 快取未失效使用除錯工具「再次抓取」
行動裝置彈窗被攔截瀏覽器攔截 popup使用 data-mobile_iframe="true" 或 SDK
開發環境 localhost 無法抓取Facebook 爬蟲無法訪問內網使用 ngrok/Cloudflare Tunnel 映射公開域名
AMP 頁面分享異常AMP 版面 og:url 指向 canonical確保 AMP 頁面 og:url = canonical URL

進階:動態生成 OG 標籤(SSR/模板引擎)

<?php
// PHP 模板範例
function renderOgTags(array $article): string
{
    $tags = [
        'og:url' => $article['canonical_url'],
        'og:type' => 'article',
        'og:title' => $article['title'],
        'og:description' => mb_substr(strip_tags($article['content']), 0, 200),
        'og:image' => $article['cover_image'],
        'og:image:width' => '1200',
        'og:image:height' => '630',
        'og:site_name' => config('app.name'),
        'og:locale' => 'zh_TW',
        'article:published_time' => $article['published_at']->format(DateTime::ATOM),
        'article:modified_time' => $article['updated_at']->format(DateTime::ATOM),
        'article:author' => $article['author_url'],
    ];
    
    $html = '';
    foreach ($tags as $property => $content) {
        $html .= '' . "\n";
    }
    // 多標籤
    foreach ($article['tags'] as $tag) {
        $html .= '' . "\n";
    }
    return $html;
}
?>
<head>
  
</head>

隱私與合規提醒

  • 載入 Facebook SDK 會發送請求至 Facebook 伺服器,可能涉及用戶追蹤,需在隱私權政策說明
  • 歐盟 GDPR/台灣個資法:考慮延遲載入 SDK(用戶點擊分享按鈕時才動態注入 script)
  • rel="noopener noreferrer" 防止反向標籤頁攻擊

總結

Facebook 分享的關鍵在於 正確部署 Open Graph 標籤,這是所有分享方式的共同基礎。選擇方式:靜態頁/簡單需求用 sharer.php URL,動態頁/需回調用 JS SDK,最省事用 Share Button Plugin。務必善用分享除錯工具驗證預覽效果,並處理快取更新機制。

copyright © 萬盛學電腦網 all rights reserved