> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 推廣貼文

> 透過將貼文提交到 Facebook 廣告平台來對其進行推廣

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

<PlansAvailable plans={["premium"]} maxPackRequired={false} />

推廣一條現有的 Facebook 貼文以建立廣告。
此端點允許您使用自定義定位、預算和排期參數，將自然發布的貼文轉換為付費廣告。

<ul className="custom-bullets">
  <li>預算和出價金額必須以美元（USD）指定，最多保留兩位小數。</li>
  <li>為滿足 Facebook 的要求，廣告必須至少投放 30 小時。</li>

  <li>
    您可以使用 [興趣端點](/apis/ads/facebook/get-ad-interests) 來查找用於定位的興趣 ID。
  </li>

  <li>Facebook 審核並批準推廣貼文最多可能需要 24 小時。</li>

  <li>
    如果直接使用 `fbPostId`（而非 Ayrshare 的 `postId`），請確保它是有效的 Facebook 貼文 ID。
  </li>
</ul>

### 廣告目標

每條廣告都必須設定一個目標（goal）。目標決定了廣告將如何針對展示進行最佳化。

<ul className="custom-bullets">
  <li>
    `engagement`（互動）：該目標旨在提升互動，同時確保廣告觸達盡可能多的獨立使用者。
    它在曝光度與互動之間取得平衡，把廣告展示給盡可能多可能與之互動的不同使用者。
  </li>

  <li>
    `interactions`（互動動作）：旨在增加廣告的互動，例如按讚、評論和分享。
    Facebook 會優先將廣告展示給最有可能與之互動的使用者。
  </li>

  <li>
    `awareness_views`（品牌認知—展示）：透過最大化廣告的展示次數來提升品牌認知。
    它會在預算范圍內優先盡可能多次地展示廣告，而不考慮獨立觸達。
  </li>

  <li>
    `awareness_audience`（品牌認知—受眾）：透過最大化看到廣告的獨立使用者數量來增強品牌認知。
    它確保廣告觸達盡可能多的不同使用者，並最大化獨立受眾規模，而不是對同一受眾多次展示。
  </li>
</ul>

在我們的 [Facebook Marketing API 整合指南](https://www.ayrshare.com/blog/facebook-ads-api-boosting-with-the-marketing-api/) 中了解更多有關將 Facebook Marketing API 與 Ayrshare 整合的資訊。

## 請求頭參數

<HeaderAPI />

## 請求體參數

<ParamField body="accountId" type="string" required>
  用於推廣該貼文的 Facebook 廣告帳戶 ID。可以從 [廣告帳戶端點](/apis/ads/facebook/get-ad-accounts) 獲取帳戶 ID。
</ParamField>

<ParamField body="adName" type="string" required>
  您的廣告名稱（顯示在 Facebook 廣告管理器中），格式為 `{adName} - {postId or fbPostId} - {current date}`。
</ParamField>

<ParamField body="bidAmount" type="number" required>
  最高出價金額，以美元計。最低出價金額為 \$1.00。
</ParamField>

<ParamField body="budget" type="number" required>
  每日預算，以美元計。最低預算為 \$1.00。
</ParamField>

<ParamField body="fbPostId" type="string" required>
  要推廣的貼文的 [Facebook 社群貼文 ID](/apis/overview#social-post-id)，可用於以直接在 Facebook 上建立的貼文來建立廣告。
  這是 [Facebook 上貼文](/apis/history/history-platform) 的 ID，而不是 Ayrshare 的 ID。如果未設定 `postId`，則該參數必填。
</ParamField>

<ParamField body="goal" type="string" required default="engagement">
  廣告的目標。可選值：`engagement`、`interactions`、`awareness_views` 和 `awareness_audience`。
  詳見上文 [廣告目標詳細說明](/apis/ads/facebook/boost-post#ad-goals)。
</ParamField>

<ParamField body="locations" type="object" required default={{ countries: ["US"] }}>
  廣告的目標位置，採用包含陣列的物件：`countries`、`regions`、`cities`。

  <Expandable title="子屬性">
    <ParamField body="countries" type="array">
      國家代碼清單。

      ```json theme={"system"}
      {
        "countries": ["US", "CA"]
      }
      ```
    </ParamField>

    <ParamField body="regions" type="array">
      地區需要提供 Facebook 的地區 `key` 值。詳見 [地區端點](/apis/ads/facebook/get-ad-regions)。

      ```json theme={"system"}
      {
        "regions": [{ "key": "3886" }]
      }
      ```
    </ParamField>

    <ParamField body="cities" type="array">
      城市需要提供：`key`（來自 Facebook）、`radius` 和 `distance_unit`。
      `radius` 為圍繞城市的距離：10–50 英裡或 17–80 公裡。
      `distance_unit` 為 `mile`（英裡）或 `kilometer`（公裡）。
      詳見 [城市端點](/apis/ads/facebook/get-ad-cities)。

      ```json theme={"system"}
      {
        "cities": [
          { "key": "2420605", "radius": 25, "distance_unit": "mile" }
        ]
      }
      ```
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="postId" type="string" required>
  要推廣的貼文的 [Ayrshare 貼文 ID](/apis/overview#ayrshare-post-id)。如果未設定 `fbPostId`，則該參數必填。
</ParamField>

<ParamField body="status" type="string" default="active" required>
  廣告的狀態。可選值：`active` 和 `paused`。

  之後可以使用 [更新廣告端點](/apis/ads/facebook/put-ad-update) 修改廣告狀態。
</ParamField>

<ParamField body="adSetBudgetSharingEnabled" type="boolean" default={false}>
  控制 Meta 在活動層級的廣告集預算共享。
  Meta 現在要求在每個未設定活動級預算的活動上都傳遞此參數欄位，因此 Ayrshare 總會發送該欄位——為向後相容預設設為 `false`。

  設定為 `true` 可讓 Meta 在同一活動的其他廣告集之間共享某個廣告集最多約 20% 的預算，以最佳化整體表現。詳見 Meta 的 [廣告活動組參考](https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group/)。
</ParamField>

<ParamField body="tracking" type="object">
  使用 Facebook Pixel 追蹤廣告。

  <Expandable title="子屬性">
    <ParamField body="pixelId" type="number" required>
      用於追蹤廣告的 Facebook Pixel ID。

      ```json theme={"system"}
      {
       "pixelId": 1234567890
      }
      ```
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="urlTags" type="array">
  向廣告 URL 添加 UTM 標簽。

  ```json theme={"system"}
  {
    "urlTags": ["utm_source=ayrshare", "utm_medium=social", "utm_campaign=ayrshare-social"]
  }
  ```

  例如，如果連結 URL 為 `https://www.mysite.com/my-post`，添加的 URL 標簽為：

  `utm_source=ayrshare`、`utm_medium=social` 和 `utm_campaign=ayrshare-social`。

  那麼廣告 URL 將為：
  `https://www.mysite.com/my-post?utm_source=ayrshare&utm_medium=social&utm_campaign=ayrshare-social`。
</ParamField>

<ParamField body="specialAdCategories" type="array">
  Meta 要求屬於 [特殊廣告類別](https://www.facebook.com/business/help/298000447747885?helpref=faq_content) 的廣告主必須自行標識其活動類別。

  如果您的業務屬於其中之一，在推廣貼文時必須選擇相應的類別。

  支援以下取值：

  <ul className="custom-bullets">
    <li>
      `housing`（住房）：推廣或直接連結到住房機會或相關服務的廣告，包括但不限於房屋或公寓的
      出售/出租資訊、房主保險、按揭保險、按揭貸款、房屋維修以及房屋淨值或估價服務。
    </li>

    <li>
      `financial_product_services`（金融產品與服務）：推廣或直接連結到金融產品與服務優惠
      （包括信貸）的廣告。
    </li>

    <li>
      `employment`（就業）：推廣或直接連結到就業機會的廣告，包括但不限於兼職或全職工作、
      實習或專業認證專案。此類別還包括對招聘網站或招聘會、招聘聚合服務，或詳述公司福利的廣告
      （無論是否有具體的職位提供）。
    </li>

    <li>
      `issues_elections_politics`（社會議題、選舉或政治）：由候選人、政治人物、政黨，或代表他們，
      或與其相關的廣告，或倡導選舉結果的廣告。這也包括與任何選舉、公投或投票倡議相關的廣告，
      包括"號召投票"的選舉宣傳。以及在投放地被視為政治廣告或涉及社會議題的廣告。若選擇社會議題、
      選舉或政治，則必須選擇投放這些廣告的國家/地區。您必須已獲得在該指定國家/地區投放社會議題、
      選舉或政治相關廣告的授權。
    </li>
  </ul>

  <Warning>
    Meta 要求廣告主必須自行標識其活動類別。
    Meta 會使用人工審核和機器学習來識別此類廣告。
    如果您向我們發送了錯誤的 `specialAdCategory`，您的廣告可能會被暫停，直到活動被調整為止。
  </Warning>
</ParamField>

<ParamField body="endDate" type="string">
  ISO 8601 格式的結束日期和時間（必須至少在開始時間後 30 小時），例如 `2025-03-01T00:00:00Z`。

  如果未設定，廣告將無限期執行，結束日期為 `ongoing`（進行中）。
</ParamField>

<ParamField body="excludedLocations" type="object">
  使用一個包含 `countries`、`regions` 和 `cities` 陣列的物件來排除位置。

  <Expandable title="子屬性">
    <ParamField body="countries" type="array">
      要排除的國家代碼清單。

      ```json theme={"system"}
      {
        "countries": ["US", "CA"]
      }
      ```
    </ParamField>

    <ParamField body="regions" type="array">
      地區需要提供 Facebook 的地區 `key` 值。詳見 [地區端點](/apis/ads/facebook/get-ad-regions)。

      ```json theme={"system"}
      {
        "regions": [{ "key": "3886" }]
      }
      ```
    </ParamField>

    <ParamField body="cities" type="array">
      城市需要提供：`key`（來自 Facebook）、`radius` 和 `distance_unit`。
      `radius` 為圍繞城市的距離：10–50 英裡或 17–80 公裡。
      `distance_unit` 為 `mile`（英裡）或 `kilometer`（公裡）。
      詳見 [城市端點](/apis/ads/facebook/get-ad-cities)。

      ```json theme={"system"}
      {
        "cities": [
          { "key": "2420605", "radius": 25, "distance_unit": "mile" }
        ]
      }
      ```
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="gender" type="string" default="all">
  受眾性別。可選值：`all`（全部）、`male`（男性）、`female`（女性）。
</ParamField>

<ParamField body="interests" type="array">
  廣告的目標興趣，作為 Facebook [興趣 ID](/apis/ads/facebook/get-ad-interests) 的陣列。
</ParamField>

<ParamField body="maxAge" type="number" default={65}>
  廣告定位的最大年齡（預設：65）。
</ParamField>

<ParamField body="minAge" type="number" default={18}>
  廣告定位的最小年齡（預設：18）。
</ParamField>

<ParamField body="startDate" type="string">
  ISO 8601 格式的開始日期和時間，例如 `2025-03-01T00:00:00Z`。

  如果未設定，廣告將立即開始投放。
</ParamField>

<ParamField body="dsaBeneficiary" type="string">
  面向歐盟國家、用於合規《數字服務法》（DSA）的廣告受益人。若提供 `dsaPayor` 或 `dsaBeneficiary` 中任一個，
  則必須同時設定兩者。有關更多資訊，請參閱我們的 [DSA 指南](/apis/ads/facebook/get-dsa-recommendations)。
</ParamField>

<ParamField body="dsaPayor" type="string">
  面向歐盟國家、用於合規《數字服務法》（DSA）的廣告付款方。若提供 `dsaBeneficiary` 或 `dsaPayor` 中任一個，
  則必須同時設定兩者。
</ParamField>

<RequestExample>
  ```bash cURL theme={"system"}
  curl -X POST https://api.ayrshare.com/api/ads/facebook/boost \
    -H "Authorization: Bearer API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "postId": "1234567890",
      "accountId": "1234567890",
      "adName": "My Ad",
      "status": "active",
      "goal": "engagement",
      "minAge": 18,
      "maxAge": 65,
      "locations": { "countries": ["US"] },
      "budget": 100,
      "bidAmount": 1,
      "startDate": "2025-03-01T00:00:00Z",
      "endDate": "2025-03-07T23:59:59Z",
      "interests": [1234567890, 1234567891]
    }'
  ```

  ```javascript JavaScript theme={"system"}
  const API_KEY = "API_KEY";

  fetch("https://api.ayrshare.com/api/ads/facebook/boost", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      postId: "1234567890",
      accountId: "1234567890",
      adName: "My Ad",
      status: "active",
      goal: "engagement",
      minAge: 18,
      maxAge: 65,
      locations: { countries: ["US"] },
      budget: 100,
      bidAmount: 1,
      startDate: "2025-03-01T00:00:00Z",
      endDate: "2025-03-07T23:59:59Z",
      interests: [1234567890, 1234567891]
    })
  })
    .then((res) => res.json())
    .then((json) => console.log(json))
    .catch(console.error);
  ```

  ```python Python theme={"system"}
  import requests

  API_KEY = "API_KEY"

  url = "https://api.ayrshare.com/api/ads/facebook/boost"
  payload = {
      "postId": "1234567890",
      "accountId": "1234567890",
      "adName": "My Ad",
      "status": "active",
      "goal": "engagement",
      "minAge": 18,
      "maxAge": 65,
      "locations": {"countries": ["US"]},
      "budget": 100,
      "bidAmount": 1,
      "startDate": "2025-03-01T00:00:00Z",
      "endDate": "2025-03-07T23:59:59Z",
      "interests": [1234567890, 1234567891]
  }

  response = requests.post(url, headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json=payload)

  print(response.json())
  ```

  ```php PHP theme={"system"}
  <?php
  $API_KEY = "API_KEY";

  $payload = [
      "postId" => "1234567890",
      "accountId" => "1234567890",
      "adName" => "My Ad",
      "status" => "active",
      "goal" => "engagement",
      "minAge" => 18,
      "maxAge" => 65,
      "locations" => ["countries" => ["US"]],
      "budget" => 100,
      "bidAmount" => 1,
      "startDate" => "2025-03-01T00:00:00Z",
      "endDate" => "2025-03-07T23:59:59Z",
      "interests" => [1234567890, 1234567891]
  ];

  $ch = curl_init("https://api.ayrshare.com/api/ads/facebook/boost");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Content-Type: application/json",
      "Authorization: Bearer " . $API_KEY
  ]);

  $response = curl_exec($ch);
  $result = json_decode($response, true);

  print_r($result);
  curl_close($ch);
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Text;
  using System.Text.Json;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main()
      {
          string API_KEY = "API_KEY";

          var payload = new
          {
              postId = "1234567890",
              accountId = "1234567890",
              adName = "My Ad",
              status = "active",
              goal = "engagement",
              minAge = 18,
              maxAge = 65,
              locations = new { countries = new[] { "US" } },
              budget = 100,
              bidAmount = 1,
              startDate = "2025-03-01T00:00:00Z",
              endDate = "2025-03-07T23:59:59Z",
              interests = new[] { 1234567890, 1234567891 }
          };

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY);

          var content = new StringContent(
              JsonSerializer.Serialize(payload),
              Encoding.UTF8,
              "application/json"
          );

          var response = await client.PostAsync("https://api.ayrshare.com/api/ads/facebook/boost", content);
          var responseBody = await response.Content.ReadAsStringAsync();

          Console.WriteLine(responseBody);
      }
  }
  ```

  ```go Go theme={"system"}
  package main

  import (
  	"bytes"
  	"encoding/json"
  	"fmt"
  	"io/ioutil"
  	"net/http"
  )

  func main() {
  	apiKey := "API_KEY"

  	payload := map[string]interface{}{
  		"postId":    "1234567890",
  		"accountId": "1234567890",
  		"adName":    "My Ad",
  		"status":    "active",
  		"goal":      "engagement",
  		"minAge":    18,
  		"maxAge":    65,
  		"locations":  map[string]interface{}{"countries": []string{"US"}},
  		"budget":    100,
  		"bidAmount": 1,
  		"startDate": "2025-03-01T00:00:00Z",
  		"endDate":   "2025-03-07T23:59:59Z",
  		"interests": []int{1234567890, 1234567891},
  	}

  	jsonData, err := json.Marshal(payload)
  	if err != nil {
  		fmt.Println("Error marshaling JSON:", err)
  		return
  	}

  	req, err := http.NewRequest("POST", "https://api.ayrshare.com/api/ads/facebook/boost", bytes.NewBuffer(jsonData))
  	if err != nil {
  		fmt.Println("Error creating request:", err)
  		return
  	}

  	req.Header.Set("Content-Type", "application/json")
  	req.Header.Set("Authorization", "Bearer "+apiKey)

  	client := &http.Client{}
  	resp, err := client.Do(req)
  	if err != nil {
  		fmt.Println("Error sending request:", err)
  		return
  	}
  	defer resp.Body.Close()

  	body, err := ioutil.ReadAll(resp.Body)
  	if err != nil {
  		fmt.Println("Error reading response:", err)
  		return
  	}

  	fmt.Println(string(body))
  }
  ```

  ```java Java theme={"system"}
  import java.io.IOException;
  import java.net.URI;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.Map;

  import com.fasterxml.jackson.databind.ObjectMapper;

  public class BoostPost {
      public static void main(String[] args) {
          String API_KEY = "API_KEY";
          String url = "https://api.ayrshare.com/api/ads/facebook/boost";

          Map<String, Object> payload = new HashMap<>();
          payload.put("postId", "1234567890");
          payload.put("accountId", "1234567890");
          payload.put("adName", "My Ad");
          payload.put("status", "active");
          payload.put("goal", "engagement");
          payload.put("minAge", 18);
          payload.put("maxAge", 65);
          Map<String, Object> locations = new HashMap<>();
          locations.put("countries", Arrays.asList("US"));
          payload.put("locations", locations);
          payload.put("budget", 100);
          payload.put("bidAmount", 1);
          payload.put("startDate", "2025-03-01T00:00:00Z");
          payload.put("endDate", "2025-03-07T23:59:59Z");
          payload.put("interests", Arrays.asList(1234567890, 1234567891));

          try {
              ObjectMapper objectMapper = new ObjectMapper();
              String requestBody = objectMapper.writeValueAsString(payload);

              HttpClient client = HttpClient.newHttpClient();
              HttpRequest request = HttpRequest.newBuilder()
                      .uri(URI.create(url))
                      .header("Content-Type", "application/json")
                      .header("Authorization", "Bearer " + API_KEY)
                      .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                      .build();

              HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
              System.out.println(response.body());

          } catch (IOException | InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
  ```

  ```ruby Ruby theme={"system"}
  require 'net/http'
  require 'uri'
  require 'json'

  API_KEY = "API_KEY"

  uri = URI.parse("https://api.ayrshare.com/api/ads/facebook/boost")
  payload = {
    postId: "1234567890",
    accountId: "1234567890",
    adName: "My Ad",
    status: "active",
    goal: "engagement",
    minAge: 18,
    maxAge: 65,
    locations: { countries: ["US"] },
    budget: 100,
    bidAmount: 1,
    startDate: "2025-03-01T00:00:00Z",
    endDate: "2025-03-07T23:59:59Z",
    interests: [1234567890, 1234567891]
  }

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.request_uri)
  request["Content-Type"] = "application/json"
  request["Authorization"] = "Bearer #{API_KEY}"
  request.body = payload.to_json

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Post Boosted theme={"system"}
  {
      "status": "success",
      "adId": "120217670757750410",
      "adName": "API Post - DE6gpw8kxlonHy2b7Lo - 2025-03-26T23:42:43",
      "adStatus": "active",
      "bidAmount": 10,
      "budget": 100,
      "endDate": "2026-03-28T22:30:00Z",
      "goal": {
          "title": "Get More Engagement",
          "description": "This goal seeks to increase engagement...",
          "type": "engagement"
      },
      "interests": [
          "6003195554098"
      ],
      "locations": { "countries": ["US"] },
      "maxAge": 65,
      "minAge": 18,
      "postId": "DE6gpw8kxlonHy2b7Lo",
      "startDate": "2026-03-26T22:30:00Z"
  }
  ```

  ```json 400: Invalid Account ID theme={"system"}
  {
    "action": "boost post",
    "status": "error",
    "code": 369,
    "message": "Unable to boost post. Please try again or contact us if the issue persists.",
    "details": "The accountId likely does not exist. Please check the accountId and try again."
  }
  ```

  ```json 400: Missing Required Parameters theme={"system"}
  {
    "action": "request",
    "status": "error",
    "code": 101,
    "message": "Missing or incorrect parameters. Please verify with the docs. https://www.ayrshare.com/docs/apis",
    "details": "Missing required fields: budget"
  }
  ```
</ResponseExample>
