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

# Google 搜尋廣告活動

> 在一個請求中建立 Google Ads 搜尋廣告活動，包括預算、關鍵字、廣告文字和地理位置指定

只需一個請求即可建立 Google Ads 搜尋廣告活動。Ayrshare 會一併建立預算、廣告活動、一個廣告群組、您的關鍵字、一則回應式搜尋廣告以及地區定位。若 Google 拒絕其中任何部分，則不會建立任何項目。

此請求使用共用的 [廣告活動](https://www.ayrshare.com/docs/apis/ads/campaigns.md) 格式。本頁說明 Google 特有的部分。

<ul>
  <li>Google 廣告需按帳戶個別開通。請聯絡我們以啟用此功能。</li>
  <li>請先在 Social Accounts（社群帳戶）頁面連結 Google Ads。`accountId` 是 10 位數的 Google Ads 客戶 ID，可包含或不含連字號（`123-456-7890`）。</li>
  <li>您連結的 Google 使用者必須能直接存取該廣告帳戶。僅能透過管理員帳戶存取的帳戶不會列出，目前也無法使用：請將該使用者直接加入廣告帳戶本身。管理員帳戶同樣不會列出：它們無法包含廣告活動。</li>
  <li>新廣告活動預設以 `paused` 狀態開始，除非您傳送 `status: "active"`。</li>
  <li>預算為每日預算，使用廣告帳戶的幣別。請勿發送 `budget.currency`：否則會返回 `code: 101`。</li>
  <li>其他幣別的支出會依 Open Exchange Rates 提供的當日匯率換算為 USD 計費。使用無法換算之幣別的帳戶會在建立任何項目之前返回 `code: 101`。</li>
  <li>廣告只會在 Google 搜尋上顯示，不會出現在搜尋夥伴或多媒體廣告聯播網上。</li>
</ul>

> [!NOTE]
>
> **轉換追蹤。** 只有在您的 Google Ads 帳戶已設定轉換追蹤時，`maximizeConversions` 才會生效。Ayrshare 不會替您進行設定。若未設定，請使用 `maximizeClicks` 或 `manualCpc`。

## 請求頭參數

**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 將廣告活動傳送至 Google 之前就失敗，該金鑰會被釋放，因此您可以修正請求後以相同的金鑰重試。這包括 Ayrshare 拒絕的值（例如不支援的出價策略）、使用無法換算為 USD 之幣別的帳戶，以及 Ayrshare 事先進行的帳戶檢查的任何失敗，包括遭 Google 拒絕。廣告活動已傳送至 Google 後才失敗的建立請求會保留其回應：請以新的金鑰重試。

## 請求體參數

共用欄位的運作方式如 [廣告活動](https://www.ayrshare.com/docs/apis/ads/campaigns.md) 所述。在 Google 上：

**type** `string` *required*

`search`。

**bidding.strategy** `string` *required*

`maximizeClicks`、`manualCpc` 或 `maximizeConversions`。其他任何值都會返回 `code: 101`。

**euPoliticalAdvertising** `boolean` *required*

Google 要求每個廣告活動都提供此聲明。只要帳戶中有任何廣告活動未聲明，Google 就會拒絕對該帳戶廣告活動的所有變更。

**schedule** `object`

Google 以廣告帳戶時區的完整日期進行排程。`start` 從當天 00:00:00 開始，`end` 於當天 23:59:59 結束；您傳送的時間只用於決定日期。`start` 可以是今天，但不能是更早的日期。若要建立為期一天的廣告活動，請為 `start` 和 `end` 傳送相同的日期。若 `end` 的日期早於 `start`，會返回 `code: 101`。

**targeting** `object`

Google 依據您廣告文字的語言將搜尋廣告與使用者配對，因此沒有語言設定。傳送 `targeting.languages` 會返回 `code: 101`。

**子屬性**

**locations** `string[]`

Google 地區 ID，例如 `2840` 代表美國。請在 Google 的 [地理目標清單](https://developers.google.com/google-ads/api/data/geotargets) 中查詢 ID。省略此欄位即可定位所有地區。

**platformOptions.google** `object` *required*

**子屬性**

**finalUrl** `string` *required*

廣告開啟的 `http` 或 `https` 頁面。

**headlines** `string[]` *required*

3 到 15 個廣告標題，每個最多 30 個字元。

**descriptions** `string[]` *required*

2 到 4 個說明，每個最多 90 個字元。

**path1** `string`

顯示路徑的第一部分，顯示在網域之後，最多 15 個字元。

**path2** `string`

顯示路徑的第二部分，最多 15 個字元。需要搭配 `path1`。

**keywords** `object[]` *required*

至少一個關鍵字：`{ "text": string, "matchType": "exact" | "phrase" | "broad" }`。`text` 最多 80 個字元及 10 個字詞。

**maxCpc** `number`

每次點擊願意支付的最高金額，使用帳戶幣別。使用 `manualCpc` 時必填。搭配 `maximizeClicks` 時作為每次出價的上限。搭配 `maximizeConversions` 時不接受。

```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": "Fall sale",
  "type": "search",
  "budget": { "amount": 25, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "targeting": { "locations": ["2840"] },
  "euPoliticalAdvertising": false,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/fall-sale",
      "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "path1": "shoes",
      "keywords": [
        { "text": "running shoes", "matchType": "phrase" },
        { "text": "trail running shoes", "matchType": "exact" }
      ]
    }
  }
}'
```

```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": "Fall sale",
    "type": "search",
    "budget": { "amount": 25, "type": "daily" },
    "bidding": { "strategy": "maximizeClicks" },
    "targeting": { "locations": ["2840"] },
    "euPoliticalAdvertising": false,
    "platformOptions": {
      "google": {
        "finalUrl": "https://example.com/fall-sale",
        "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
        "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
        "path1": "shoes",
        "keywords": [
          { "text": "running shoes", "matchType": "phrase" },
          { "text": "trail running shoes", "matchType": "exact" }
        ]
      }
    }
  })
})
  .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": "Fall sale",
  "type": "search",
  "budget": { "amount": 25, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "targeting": { "locations": ["2840"] },
  "euPoliticalAdvertising": False,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/fall-sale",
      "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "path1": "shoes",
      "keywords": [
        { "text": "running shoes", "matchType": "phrase" },
        { "text": "trail running shoes", "matchType": "exact" }
      ]
    }
  }
}

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": "Fall sale",
  "type": "search",
  "budget": { "amount": 25, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "targeting": { "locations": ["2840"] },
  "euPoliticalAdvertising": false,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/fall-sale",
      "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "path1": "shoes",
      "keywords": [
        { "text": "running shoes", "matchType": "phrase" },
        { "text": "trail running shoes", "matchType": "exact" }
      ]
    }
  }
}
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": "Fall sale",
              "type": "search",
              "budget": { "amount": 25, "type": "daily" },
              "bidding": { "strategy": "maximizeClicks" },
              "targeting": { "locations": ["2840"] },
              "euPoliticalAdvertising": false,
              "platformOptions": {
                "google": {
                  "finalUrl": "https://example.com/fall-sale",
                  "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
                  "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
                  "path1": "shoes",
                  "keywords": [
                    { "text": "running shoes", "matchType": "phrase" },
                    { "text": "trail running shoes", "matchType": "exact" }
                  ]
                }
              }
            }
            """;

        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": "Fall sale",
  "type": "search",
  "budget": { "amount": 25, "type": "daily" },
  "bidding": { "strategy": "maximizeClicks" },
  "targeting": { "locations": ["2840"] },
  "euPoliticalAdvertising": false,
  "platformOptions": {
    "google": {
      "finalUrl": "https://example.com/fall-sale",
      "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
      "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
      "path1": "shoes",
      "keywords": [
        { "text": "running shoes", "matchType": "phrase" },
        { "text": "trail running shoes", "matchType": "exact" }
      ]
    }
  }
}`

    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": "Fall sale",
              "type": "search",
              "budget": { "amount": 25, "type": "daily" },
              "bidding": { "strategy": "maximizeClicks" },
              "targeting": { "locations": ["2840"] },
              "euPoliticalAdvertising": false,
              "platformOptions": {
                "google": {
                  "finalUrl": "https://example.com/fall-sale",
                  "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
                  "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
                  "path1": "shoes",
                  "keywords": [
                    { "text": "running shoes", "matchType": "phrase" },
                    { "text": "trail running shoes", "matchType": "exact" }
                  ]
                }
              }
            }
            """;

        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": "Fall sale",
    "type": "search",
    "budget": { "amount": 25, "type": "daily" },
    "bidding": { "strategy": "maximizeClicks" },
    "targeting": { "locations": ["2840"] },
    "euPoliticalAdvertising": false,
    "platformOptions": {
      "google": {
        "finalUrl": "https://example.com/fall-sale",
        "headlines": ["Fall sale", "Shoes 30% off", "Free returns"],
        "descriptions": ["Every shoe 30% off this week.", "Free returns on every order."],
        "path1": "shoes",
        "keywords": [
          { "text": "running shoes", "matchType": "phrase" },
          { "text": "trail running shoes", "matchType": "exact" }
        ]
      }
    }
  }
JSON

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

puts response.body
```

```json 200: Campaign Created theme={"system"}
{
  "status": "success",
  "platform": "google",
  "campaignId": "21534567890",
  "adGroupId": "16812345678",
  "adId": "71234567890",
  "campaignStatus": "paused"
}
```

```json 400: Too Few Headlines 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": "platformOptions.google.headlines: Supply at least 3 headlines."
}
```

## 錯誤

| 代碼 | 發生時機 |
| - | - |
| `101` | 欄位缺少或無效。`details` 會指出是哪個欄位。 |
| `205` | Google 拒絕了請求：例如帳戶中已有同名的廣告活動，或廣告文字違反 Google 的廣告政策。`details` 會說明需要變更的內容。 |
| `400` | 您連結的 Google 使用者無法存取此廣告帳戶、Google Ads 存取權已被撤銷、廣告活動不屬於您，或變更的對象是已在 Google Ads 中移除的廣告活動。 |
| `370` | Google 無法完成請求，或 Google 尚未核准 Ayrshare 的存取權。若有 Google 的請求 ID，`details` 會包含該 ID。若建立請求因 Google 的回應遺失而返回 `370`，廣告活動仍可能已被建立。Google 不允許同一帳戶中有兩個同名的廣告活動，因此以相同的 `name` 重試會返回 `205`，而不會建立重複項目。 |


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