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

# 廣告活動

> 建立、讀取及更新背後沒有貼文的廣告活動，例如搜尋廣告活動。

廣告活動是一種不從您的貼文開始的廣告。可用於搜尋廣告等格式：由您設定預算、出價策略和定位，再由網路建立廣告。

若要推廣您已發布的貼文，請改用 [推廣貼文](https://www.ayrshare.com/docs/apis/ads/facebook/boost-post.md)。

> [!NOTE]
>
> Google 接受廣告活動。有關 Google 的特定內容，請參閱 [Google 搜尋廣告活動](https://www.ayrshare.com/docs/apis/ads/google/search-campaigns.md) 和 [Google Performance Max 廣告活動](https://www.ayrshare.com/docs/apis/ads/google/performance-max-campaigns.md)。其他網路會以 `code: 101` 拒絕廣告活動請求，`details` 會說明原因。例如在 Facebook 上，它會顯示 `campaignCreation is not supported on facebook.`

## 端點

| 方法 | 路徑 | 功能 |
| - | - | - |
| `POST` | `/ads/{platform}/campaigns` | 建立廣告活動 |
| `GET` | `/ads/{platform}/campaigns/{id}` | 取得單一廣告活動 |
| `PUT` | `/ads/{platform}/campaigns/{id}` | 變更單一廣告活動 |

`{platform}` 是廣告網路。`{id}` 是建立廣告活動時返回的廣告活動 ID。您只能讀取和變更由同一個使用者個人檔案透過 Ayrshare 建立的廣告活動。

## 請求頭參數

**Authorization** `string` *required*

[API Key](https://www.ayrshare.com/docs/apis/overview.md#authorization) of the Primary Profile.

Format: `Authorization: Bearer API_KEY`
**Profile-Key** `string`

[Profile Key](https://www.ayrshare.com/docs/apis/overview.md#profile-key-format) of a User Profile.

Format: `Profile-Key: PROFILE_KEY`

**Idempotency-Key** `string` *required*

建立廣告活動時必填。每個新的廣告活動都請傳送一個新的唯一值，例如 UUID。若您以相同的金鑰重複發送請求，Ayrshare 會返回第一次的回應並標記 `idempotentReplayed: true`，且不會建立任何新項目。您也可以改在請求體中以 `idempotencyKey` 傳送此金鑰。若兩者都傳送，其值必須相同。

## 建立廣告活動

`POST /ads/{platform}/campaigns`

除非您傳送 `status: "active"`，否則新的廣告活動會以 `paused` 狀態開始，因此在您決定啟動之前不會產生任何花費。

**accountId** `string` *required*

要在其中建立廣告活動的廣告帳戶。

**name** `string` *required*

廣告活動名稱，長度為 1 到 255 個字元。

**type** `string` *required*

廣告活動類型：`search` 或 `performanceMax`。每個網路僅支援部分類型。若網路不支援該類型，會以 `code: 101` 回應並列出支援的類型。

**budget** `object` *required*

**子屬性**

**amount** `number` *required*

每日花費金額，最多保留兩位小數。

**type** `string` *required*

`daily`。

**currency** `string`

ISO 4217 代碼，例如 `USD`。預設為廣告帳戶的貨幣。僅部分網路接受此參數。

**bidding** `object` *required*

**子屬性**

**strategy** `string` *required*

`maximizeConversions`、`maximizeConversionValue`、`targetCpa`、`targetRoas`、`maximizeClicks` 或 `manualCpc`。每個網路只支援部分策略。

**targetCpa** `number`

目標單次行動成本。使用 `targetCpa` 時為必填，使用其他策略時不接受此參數。

**targetRoas** `number`

目標廣告投資報酬率，例如 `3.5` 代表 350%。使用 `targetRoas` 時為必填，使用其他策略時不接受此參數。

**euPoliticalAdvertising** `boolean` *required*

該廣告活動是否為歐盟境內的政治廣告。您必須每次都傳送此參數。Ayrshare 絕不會替您填入。

**schedule** `object`

**子屬性**

**start** `string`

開始時間：ISO 日期（`2026-11-01`），或帶有 `Z` 或時區偏移的 ISO 日期時間（`2026-11-01T09:00:00Z`）。預設為現在。

**end** `string`

結束時間，格式與 `start` 相同。必須晚於 `start`；若省略 `start`，則必須晚於現在。省略此參數則不設結束日期持續投放。以完整日期排程的網路（例如 Google）也接受與 `start` 同一天的 `end`，用於為期一天的廣告活動。

**targeting** `object`

每個網路僅支援部分定位。若網路不支援某個欄位，會以 `code: 101` 回應。

**子屬性**

**locations** `string[]`

網路自身的地點 ID。

**languages** `string[]`

網路自身的語言 ID。

**status** `string` (default: paused)

`active` 或 `paused`。

**platformOptions** `object`

僅適用於單一網路的選項，放在該網路的名稱之下，例如 `{ "facebook": { ... } }`。針對其他任何網路的選項會以 `code: 101` 回應。

```bash cURL theme={"system"}
curl \
-H "Authorization: Bearer API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10" \
-X POST https://api.ayrshare.com/api/ads/google/campaigns \
-d '{
  "accountId": "123-456-7890",
  "name": "Spring search",
  "type": "search",
  "budget": { "amount": 20, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "euPoliticalAdvertising": false,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/spring",
      "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
    }
  }
}'
```

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

fetch("https://api.ayrshare.com/api/ads/google/campaigns", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10"
  },
  body: JSON.stringify({
    "accountId": "123-456-7890",
    "name": "Spring search",
    "type": "search",
    "budget": { "amount": 20, "type": "daily" },
    "bidding": { "strategy": "maximizeClicks" },
    "euPoliticalAdvertising": false,
    "platformOptions": {
      "google": {
        "finalUrl": "https://example.com/spring",
        "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
        "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
        "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
      }
    }
  })
})
  .then((res) => res.json())
  .then((json) => console.log(json))
  .catch(console.error);
```

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

headers = {
    "Authorization": "Bearer API_KEY",
    "Idempotency-Key": "6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10",
}

payload = {
  "accountId": "123-456-7890",
  "name": "Spring search",
  "type": "search",
  "budget": { "amount": 20, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "euPoliticalAdvertising": False,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/spring",
      "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
    }
  }
}

r = requests.post("https://api.ayrshare.com/api/ads/google/campaigns", headers=headers, json=payload)

print(r.json())
```

```php PHP theme={"system"}
<?php
$payload = <<<'JSON'
{
  "accountId": "123-456-7890",
  "name": "Spring search",
  "type": "search",
  "budget": { "amount": 20, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "euPoliticalAdvertising": false,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/spring",
      "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
    }
  }
}
JSON;

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.ayrshare.com/api/ads/google/campaigns",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer API_KEY",
        "Content-Type: application/json",
        "Idempotency-Key: 6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10"
    ],
    CURLOPT_POSTFIELDS => $payload
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error: " . $err;
} else {
    echo $response;
}
?>
```

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

class Program
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer API_KEY");
        client.DefaultRequestHeaders.Add("Idempotency-Key", "6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10");

        var payload = """
            {
              "accountId": "123-456-7890",
              "name": "Spring search",
              "type": "search",
              "budget": { "amount": 20, "type": "daily" },
              "bidding": { "strategy": "maximizeClicks" },
              "euPoliticalAdvertising": false,
              "platformOptions": {
                "google": {
                  "finalUrl": "https://example.com/spring",
                  "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
                  "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
                  "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
                }
              }
            }
            """;

        var response = await client.PostAsync(
            "https://api.ayrshare.com/api/ads/google/campaigns",
            new StringContent(payload, Encoding.UTF8, "application/json"));
        var content = await response.Content.ReadAsStringAsync();

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

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

import (
    "fmt"
    "io"
    "net/http"
    "strings"
)

func main() {
    payload := `{
  "accountId": "123-456-7890",
  "name": "Spring search",
  "type": "search",
  "budget": { "amount": 20, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "euPoliticalAdvertising": false,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/spring",
      "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
    }
  }
}`

    req, _ := http.NewRequest("POST", "https://api.ayrshare.com/api/ads/google/campaigns", strings.NewReader(payload))
    req.Header.Add("Authorization", "Bearer API_KEY")
    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Idempotency-Key", "6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10")

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

    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}
```

```java Java theme={"system"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class CreateCampaign {
    public static void main(String[] args) throws Exception {
        String payload = """
            {
              "accountId": "123-456-7890",
              "name": "Spring search",
              "type": "search",
              "budget": { "amount": 20, "type": "daily" },
              "bidding": { "strategy": "maximizeClicks" },
              "euPoliticalAdvertising": false,
              "platformOptions": {
                "google": {
                  "finalUrl": "https://example.com/spring",
                  "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
                  "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
                  "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
                }
              }
            }
            """;

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.ayrshare.com/api/ads/google/campaigns"))
            .header("Authorization", "Bearer API_KEY")
            .header("Content-Type", "application/json")
            .header("Idempotency-Key", "6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10")
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
```

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

uri = URI.parse('https://api.ayrshare.com/api/ads/google/campaigns')

request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer API_KEY'
request['Content-Type'] = 'application/json'
request['Idempotency-Key'] = '6f1c2d4e-0b7a-4c55-9a3e-2f8d1b7c9e10'
request.body = <<~JSON
  {
    "accountId": "123-456-7890",
    "name": "Spring search",
    "type": "search",
    "budget": { "amount": 20, "type": "daily" },
    "bidding": { "strategy": "maximizeClicks" },
    "euPoliticalAdvertising": false,
    "platformOptions": {
      "google": {
        "finalUrl": "https://example.com/spring",
        "headlines": ["Spring sale", "Shoes 30% off", "Free returns"],
        "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
        "keywords": [{ "text": "running shoes", "matchType": "phrase" }]
      }
    }
  }
JSON

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(request)
end

puts response.body
```

建立成功時會回應 `status: "success"`、`campaignId`，以及以 `campaignStatus` 表示的廣告活動本身狀態（`active` 或 `paused`）。取得與更新的回應方式相同。

## 取得廣告活動

`GET /ads/{platform}/campaigns/{id}`

返回網路所報告的廣告活動。若廣告活動不屬於您或不存在，會以 `code: 400` 回應。

## 更新廣告活動

`PUT /ads/{platform}/campaigns/{id}`

請至少傳送下列其中一個欄位。建立廣告活動後，您無法變更 `type`、`accountId` 或 `euPoliticalAdvertising`。

**name** `string`

新的廣告活動名稱。

**status** `string`

`active` 或 `paused`。當 Ayrshare 已暫停該網路上的廣告時，僅傳送 `status: "paused"` 的請求不會被阻擋。但它仍需要已連結的網路，且若網路本身停止服務，仍可能失敗。

**budget** `object`

`{ "amount": number }`：新的每日花費金額。

**schedule** `object`

`{ "end": string }`：新的結束日期，格式與 `schedule.start` 相同。必須晚於廣告活動的開始時間。以完整日期排程的網路（例如 Google）也接受與開始日期相同的日期。

## 錯誤

這些錯誤帶有 Ayrshare `code`：

| 代碼 | 發生時機 |
| - | - |
| `101` | 請求無效、網路不支援廣告活動或此廣告活動類型，或缺少冪等金鑰。`details` 會說明是哪一種情況。Ayrshare 會在確認網路已連結後才檢查金鑰，因此未連結的個人檔案會先收到 "not linked"（未連結）錯誤。 |
| `400` | 廣告活動不屬於您或不存在。 |
| `424` | 此網路上的廣告暫時無法使用。 |

建立請求也可能以下列其中一種 HTTP 狀態回應。其回應主體不含 `code`，只有 `{ "action": "createAdCampaign", "status": "error", "message": "..." }`：

| HTTP 狀態 | 發生時機 |
| - | - |
| `409` | 該冪等金鑰已用於不同的請求，或使用此金鑰的請求仍在處理中。請勿以新的金鑰重試。請先檢查廣告帳戶。 |
| `503` | Ayrshare 無法安全地保留該冪等金鑰，因此未建立任何項目。請稍後以相同的金鑰重試。 |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.