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

# Chiến dịch Quảng cáo

> Tạo, đọc và cập nhật các chiến dịch quảng cáo không dựa trên bài đăng nào, chẳng hạn như chiến dịch tìm kiếm.

Chiến dịch là một quảng cáo không bắt đầu từ một bài đăng của bạn. Hãy dùng nó cho các định dạng như quảng cáo tìm kiếm, trong đó bạn đặt ngân sách, chiến lược đặt giá thầu và nhắm mục tiêu, còn mạng quảng cáo sẽ tự tạo các quảng cáo.

Để quảng bá một bài đăng bạn đã xuất bản, hãy dùng [Boost Bài đăng](https://www.ayrshare.com/docs/apis/ads/facebook/boost-post.md) thay thế.

> [!NOTE]
>
> Google chấp nhận chiến dịch. Xem [Chiến dịch Google Search](https://www.ayrshare.com/docs/apis/ads/google/search-campaigns.md) và [Chiến dịch Google Performance Max](https://www.ayrshare.com/docs/apis/ads/google/performance-max-campaigns.md) để biết những điểm riêng của Google. Các mạng khác từ chối yêu cầu chiến dịch với `code: 101`, và `details` cho biết lý do. Ví dụ, trên Facebook, thông báo là `campaignCreation is not supported on facebook.`

## Endpoint

| Phương thức | Đường dẫn | Chức năng |
| - | - | - |
| `POST` | `/ads/{platform}/campaigns` | Tạo một chiến dịch |
| `GET` | `/ads/{platform}/campaigns/{id}` | Lấy một chiến dịch |
| `PUT` | `/ads/{platform}/campaigns/{id}` | Thay đổi một chiến dịch |

`{platform}` là mạng quảng cáo. `{id}` là id chiến dịch được trả về khi bạn tạo nó. Bạn chỉ có thể đọc và thay đổi các chiến dịch được tạo qua Ayrshare bởi cùng một user profile.

## Tham số Header

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

Bắt buộc khi tạo chiến dịch. Gửi một giá trị duy nhất mới, chẳng hạn một UUID, cho mỗi chiến dịch mới. Nếu bạn lặp lại một yêu cầu với cùng khóa, Ayrshare sẽ trả về phản hồi đầu tiên, được đánh dấu `idempotentReplayed: true`, và không tạo thêm gì mới. Bạn cũng có thể gửi khóa trong body dưới dạng `idempotencyKey`. Nếu bạn gửi cả hai, chúng phải khớp nhau.

## Tạo một Chiến dịch

`POST /ads/{platform}/campaigns`

Chiến dịch mới bắt đầu ở trạng thái `paused` trừ khi bạn gửi `status: "active"`, vì vậy sẽ không có khoản chi nào cho đến khi bạn chọn bắt đầu.

**accountId** `string` *required*

Tài khoản quảng cáo để tạo chiến dịch.

**name** `string` *required*

Tên chiến dịch, từ 1 đến 255 ký tự.

**type** `string` *required*

Loại chiến dịch: `search` hoặc `performanceMax`. Mỗi mạng chỉ hỗ trợ một số loại. Một loại mà mạng không hỗ trợ sẽ trả về `code: 101` và liệt kê các loại được hỗ trợ.

**budget** `object` *required*

**thuộc tính**

**amount** `number` *required*

Số tiền chi tiêu mỗi ngày, với tối đa hai chữ số thập phân.

**type** `string` *required*

`daily`.

**currency** `string`

Mã ISO 4217, chẳng hạn `USD`. Mặc định là đơn vị tiền tệ của tài khoản quảng cáo. Chỉ một số mạng chấp nhận trường này.

**bidding** `object` *required*

**thuộc tính**

**strategy** `string` *required*

`maximizeConversions`, `maximizeConversionValue`, `targetCpa`, `targetRoas`, `maximizeClicks`, hoặc `manualCpc`. Mỗi mạng chỉ hỗ trợ một số chiến lược.

**targetCpa** `number`

Chi phí mục tiêu cho mỗi hành động. Bắt buộc với `targetCpa`, và không được chấp nhận với bất kỳ chiến lược nào khác.

**targetRoas** `number`

Lợi tức mục tiêu trên chi tiêu quảng cáo, ví dụ `3.5` cho 350%. Bắt buộc với `targetRoas`, và không được chấp nhận với bất kỳ chiến lược nào khác.

**euPoliticalAdvertising** `boolean` *required*

Chiến dịch có phải là quảng cáo chính trị tại EU hay không. Bạn phải luôn gửi trường này. Ayrshare không bao giờ tự điền nó cho bạn.

**schedule** `object`

**thuộc tính**

**start** `string`

Thời điểm bắt đầu: một ngày ISO (`2026-11-01`) hoặc một ngày-giờ ISO với `Z` hoặc độ lệch múi giờ (`2026-11-01T09:00:00Z`). Mặc định là thời điểm hiện tại.

**end** `string`

Thời điểm dừng, cùng định dạng với `start`. Phải sau `start`, hoặc sau thời điểm hiện tại nếu bạn bỏ qua `start`. Bỏ qua trường này để chạy không có ngày kết thúc. Mạng lên lịch theo trọn ngày, như Google, cũng chấp nhận `end` cùng ngày với `start`, cho chiến dịch kéo dài một ngày.

**targeting** `object`

Mỗi mạng chỉ hỗ trợ một số tiêu chí nhắm mục tiêu. Một trường mà mạng không hỗ trợ sẽ trả về `code: 101`.

**thuộc tính**

**locations** `string[]`

Các id vị trí riêng của mạng.

**languages** `string[]`

Các id ngôn ngữ riêng của mạng.

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

`active` hoặc `paused`.

**platformOptions** `object`

Các tùy chọn chỉ dành cho một mạng, đặt dưới tên của mạng đó, ví dụ `{ "facebook": { ... } }`. Tùy chọn cho bất kỳ mạng nào khác sẽ trả về `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
```

Một lần tạo thành công sẽ trả về `status: "success"`, `campaignId`, và trạng thái riêng của chiến dịch dưới dạng `campaignStatus` (`active` hoặc `paused`). Lấy và cập nhật cũng trả về theo cùng cách.

## Lấy một Chiến dịch

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

Trả về chiến dịch theo những gì mạng báo cáo. Một chiến dịch không thuộc về bạn, hoặc không tồn tại, sẽ trả về `code: 400`.

## Cập nhật một Chiến dịch

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

Gửi ít nhất một trong các trường sau. Bạn không thể thay đổi `type`, `accountId`, hoặc `euPoliticalAdvertising` sau khi đã tạo chiến dịch.

**name** `string`

Tên chiến dịch mới.

**status** `string`

`active` hoặc `paused`. Một yêu cầu chỉ gửi `status: "paused"` sẽ không bị chặn khi Ayrshare đã tạm dừng quảng cáo trên mạng đó. Yêu cầu này vẫn cần một mạng đã được liên kết, và vẫn có thể thất bại nếu bản thân mạng đó gặp sự cố.

**budget** `object`

`{ "amount": number }`: số tiền mới chi tiêu mỗi ngày.

**schedule** `object`

`{ "end": string }`: ngày kết thúc mới, cùng định dạng với `schedule.start`. Phải sau thời điểm bắt đầu của chiến dịch. Mạng lên lịch theo trọn ngày, như Google, cũng chấp nhận cùng ngày với ngày bắt đầu.

## Lỗi

Các lỗi sau mang một `code` của Ayrshare:

| Mã | Khi nào |
| - | - |
| `101` | Yêu cầu không hợp lệ, mạng không hỗ trợ chiến dịch hoặc loại chiến dịch này, hoặc thiếu khóa idempotency. `details` cho biết trường hợp nào. Ayrshare kiểm tra khóa sau khi xác nhận mạng đã được liên kết, vì vậy một profile chưa liên kết sẽ nhận lỗi "not linked" (chưa liên kết) trước. |
| `400` | Chiến dịch không thuộc về bạn hoặc không tồn tại. |
| `424` | Quảng cáo trên mạng này tạm thời không khả dụng. |

Một yêu cầu tạo cũng có thể trả về một trong các trạng thái HTTP sau. Body của nó không có `code`, chỉ có `{ "action": "createAdCampaign", "status": "error", "message": "..." }`:

| Trạng thái HTTP | Khi nào |
| - | - |
| `409` | Khóa idempotency đã được dùng với một yêu cầu khác, hoặc yêu cầu với khóa này vẫn đang được xử lý. Đừng thử lại với khóa mới. Hãy kiểm tra tài khoản quảng cáo trước. |
| `503` | Ayrshare không thể đặt trước khóa idempotency một cách an toàn, vì vậy không có gì được tạo. Hãy thử lại sau với cùng khóa. |


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