> ## 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>除非您发送 `status: "active"`，否则新活动以 `paused` 状态开始。</li>
  <li>预算按天计算，使用广告账户的币种。请勿发送 `budget.currency`：否则会返回 `code: 101`。</li>
  <li>其他币种的支出会按 Open Exchange Rates 提供的当日汇率换算为美元进行结算。使用无法换算的币种的账户会在创建任何内容之前返回 `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 拒绝的值（例如不支持的出价策略）、使用无法换算为美元的币种的账户，以及 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.