> ## 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>
