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

# 快速入門指南

> 在幾分鐘內連結你的社群帳戶並送出第一則貼文。

本指南適用於設定單一公司帳戶的情境。若你訂閱的是面向多位使用者的 Business 或 Enterprise 方案，我們會為你提供專屬客製的整合指南。

<div class="video-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/HaWh_QOib_Y" title="Ayrshare's Social API Quick Start Guide" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscsope; picture-in-picture" />
</div>

## 連結你的社群媒體帳戶

登入或註冊一個 [Ayrshare 帳戶](https://app.ayrshare.com/)。
在 Social Account 頁面上，點選你想連結的社群網路。
請務必授予所有權限。

<p align="center">
  <img width="240" src="https://mintcdn.com/ayrshare-docs/dKBti0xVDJrOZ19f/images/fb-connect.webp?fit=max&auto=format&n=dKBti0xVDJrOZ19f&q=85&s=d256f4862cb21b388d388cc62aa94659" alt="Facebook Linking Example" data-path="images/fb-connect.webp" />
</p>

## 取得你的 API 金鑰

存取 API 端點需要使用 API 金鑰進行授權。
此金鑰用於請求的標頭中，並需以 `Bearer` 關鍵字作為前綴。

你的 API 金鑰位於 [Ayrshare 儀表板](https://app.ayrshare.com/) 的 **API Key** 頁面。如有必要，請先在 **User Profiles** 頁面切換到「Primary Profile」（主要設定檔）。
接著你可以在左側面板中找到 **API Key** 頁面。

<img src="https://mintcdn.com/ayrshare-docs/Nmrhj2Gh7WSf62Bh/images/api-key.webp?fit=max&auto=format&n=Nmrhj2Gh7WSf62Bh&q=85&s=29ebd3dd2f23c9f9f1c52a974ebd6240" alt="API Key" width="4000" height="1126" data-path="images/api-key.webp" />

每一次 API 呼叫都必須在標頭中透過 `Bearer` 權杖帶上 API 金鑰。同時也要包含 `Content-Type: application/json`。

```json Header theme={"system"}
"Authorization": "Bearer API_KEY",
"Content-Type": "application/json"
```

更多資訊請參見 [Authorization](/apis/overview#authorization)。

## 送出你的第一次 API 貼文

### 發布貼文

以下是使用我們的 API 在不同程式語言中發文的程式碼範例。
若想更輕鬆地整合，你也可以使用我們預先建置的 [SDK 套件](/packages-guides/overview)。

要發文，你需要：

<ul className="custom-bullets">
  <li>用於身分驗證的 [API 金鑰](/apis/overview#authorization)。</li>
  <li>貼文的文字內容。</li>
  <li>你想要發布的社群媒體平台（僅列入你已連結的平台）。</li>
  <li>選用：你想附加的圖片或影片 URL。</li>
</ul>

所有範例都使用 [/post](/apis/post/post) 端點。我們來看幾段範例程式碼：

<Info>
  **要發布到 X/Twitter？** X 需要你自己的 API 憑證。請在請求中加上兩個 BYO 標頭（`X-Twitter-OAuth1-Api-Key` 與 `X-Twitter-OAuth1-Api-Secret`）。這是 **每個 Ayrshare 帳戶的一次性設定**，同一組金鑰適用於每一個子設定檔／終端使用者。詳細步驟請參見 [設定指南](/dashboard/connect-social-accounts/x-twitter-byo-keys)。
</Info>

<CodeGroup>
  ```bash cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "post": "Today is a great day!",
    "platforms": ["facebook", "instagram", "linkedin"],
    "mediaUrls": ["https://img.ayrshare.com/012/gb.jpg"]
  }' \
  -X POST https://api.ayrshare.com/api/post
  ```

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

  fetch("https://api.ayrshare.com/api/post", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
          post: "Today is a great day!", // required
          platforms: ["bluesky", "facebook", "instagram", "linkedin"], // required
          mediaUrls: ["https://img.ayrshare.com/012/gb.jpg"] //optional
        }),
      })
        .then((res) => res.json())
        .then((json) => console.log(json))
        .catch(console.error);
  ```

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

  payload = {'post': 'Today is a great day!',
          'platforms': ['bluesky', 'facebook', 'instagram', 'linkedin'],
          'mediaUrls': ['https://img.ayrshare.com/012/gb.jpg']}
  headers = {'Content-Type': 'application/json',
          'Authorization': 'Bearer API_KEY'}

  r = requests.post('https://api.ayrshare.com/api/post',
      json=payload,
      headers=headers)

  print(r.json())
  ```

  ```php PHP theme={"system"}
  <?php

  $curl = curl_init();
  $data = [
      "post" => "Today is a great day!",
      "platforms" => ["bluesky", "facebook", "instagram", "linkedin", "pinterest"],
      "mediaUrls" => ["https://img.ayrshare.com/012/gb.jpg"]
  ];

  curl_setopt_array($curl, [
      CURLOPT_URL => 'https://api.ayrshare.com/api/post',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => json_encode($data),
      CURLOPT_HTTPHEADER => [
          'Authorization: Bearer API_KEY', // Replace 'API_KEY' with your actual API key
          'Content-Type: application/json'
      ],
  ]);

  $response = curl_exec($curl);
  curl_close($curl);
  echo $response;
  ```

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

  import (
  	"bytes"
  	"encoding/json"
  	"log"
  	"net/http"
  )

  func main() {
  	message := map[string]interface{}{
  		"post":      "Today is a great day!",
  		"platforms": []string{"bluesky", "facebook", "instagram", "linkedin"},
  		"mediaUrls": []string{"https://img.ayrshare.com/012/gb.jpg"}
  	}

  	bytesRepresentation, err := json.Marshal(message)
  	if err != nil {
  		log.Fatalln(err)
  	}

  	req, _ := http.NewRequest("POST", "https://api.ayrshare.com/api/post",
  		bytes.NewBuffer(bytesRepresentation))

  	req.Header.Add("Content-Type", "application/json; charset=UTF-8")
  	req.Header.Add("Authorization", "Bearer API_KEY")

  	res, err := http.DefaultClient.Do(req)
  	if err != nil {
  		log.Fatal("Error:", err)
  	}

  	res.Body.Close()
  }
  ```

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

  namespace PostPOSTRequest_csharp
  {
    class Post
    {
      private static readonly HttpClient client = new HttpClient();

          static async Task Main(string[] args)
          {
              string API_KEY = "API_KEY";
              string url = "https://api.ayrshare.com/api/post";

              // Set up request headers
              client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);

              // Prepare JSON content
              string json = "{\"post\" : \"Today is a great day!\","
                  + "\"platforms\" : [ \"bluesky\", \"facebook\", \"instagram\", \"linkedin\" ],"
                  + "\"mediaUrls\" : [ \"https://img.ayrshare.com/012/gb.jpg\" ]}";
              var content = new StringContent(json, Encoding.UTF8, "application/json");

              try
              {
                  // Send POST request
                  HttpResponseMessage response = await client.PostAsync(url, content);
                  response.EnsureSuccessStatusCode();

                  // Read response
                  string responseBody = await response.Content.ReadAsStringAsync();
                  Console.WriteLine(responseBody);
              }
              catch (HttpRequestException e)
              {
                  Console.WriteLine($"Error: {e.Message}");
              }
          }
      }
  }
  ```

  ```ruby Ruby theme={"system"}
  require 'httparty'    # gem install httparty

  res = HTTParty.post("https://api.ayrshare.com/api/post",
      headers: {Authorization: "Bearer API_KEY"},
      body: {
          post: "Today is a great day!",
          platforms: ['bluesky', 'facebook', 'instagram', 'linkedin'],
          mediaUrls: ["https://img.ayrshare.com/012/gb.jpg"]
      }).body

  puts res
  ```
</CodeGroup>

恭喜！你已成功送出第一則貼文。

### 發文回應

當我們的 API 成功處理你的貼文時，你會收到 `status` 為 "success" 的回應。回應中包含：

<ul className="custom-bullets">
  <li>`status`：API 呼叫的整體狀態（"success" 或 "error"）</li>
  <li>`errors`：所遇錯誤的陣列（成功時為空）</li>
  <li>`postIds`：包含各平台具體資訊的物件陣列：</li>

  <ul className="custom-bullets">
    <li>平台名稱</li>
    <li>該平台上的貼文 ID</li>
    <li>檢視該貼文的 URL</li>
    <li>其他平台特有的資訊</li>
  </ul>
</ul>

`postIds` 陣列中的每個平台都會有各自的狀態，讓你能確認哪些平台成功接收了你的貼文。

請檢查你的社群媒體頁面，確認貼文已成功處理並上線。請留意，某些平台在貼文公開顯示前可能會有些微延遲。

以下是一個範例回應：

```json Post Response theme={"system"}
{
  "status": "success",
  "errors": [],
  "postIds": [
    {
      "status": "success",
      "id": "738681876342836_1530521371228093",
      "postUrl": "https://www.facebook.com/738681876342836/posts/1530521371228093",
      "platform": "facebook"
    },
    {
      "status": "success",
      "id": "18008340650526653",
      "postUrl": "https://www.instagram.com/p/DGf4hgZObR0/",
      "usedQuota": 1,
      "platform": "instagram"
    },
    {
      "status": "success",
      "id": "urn:li:share:7300150903578275840",
      "postUrl": "https://www.linkedin.com/feed/update/urn:li:share:7300150903578275840",
      "owner": "urn:li:organization:66755239",
      "platform": "linkedin"
    }
  ],
  "id": "K0DmYRgugS5P694it",
  "refId": "d93ca2784c9bf7bf83e0bf081d16c91598",
  "post": "Today is a great day!"
}
```

檢視更多以 Node.js、Python、PHP、Go、C# 與 Ruby 呼叫社群媒體 API 的程式碼範例，以及其他強大功能：

<Card title="Post" icon="code" href="/apis/post/post" horizontal />

### 稍微深入了解

我們來拆解剛才這次 API 呼叫時到底發生了什麼事。

<Steps>
  <Step title="設定標頭">
    我們設定了 Header Authorization Bearer 權杖（API 金鑰），以及 Content-Type 為 json。
  </Step>

  <Step title="建立 Body 物件">
    接著，我們建立了 body 物件：

    <ul className="custom-bullets">
      <li>包含文字 "Today is a great day!" 的 post。</li>

      <li>
        社群網路平台為 Facebook、Instagram 與 LinkedIn。
        你只應該列入你在 Social Linkage 頁面上已連結的平台。
      </li>

      <li>在 mediaUrls 中加入了一張圖片。</li>
    </ul>
  </Step>

  <Step title="呼叫 /post 端點">
    將以上內容作為 HTTP POST 請求送至 /post 端點。
  </Step>
</Steps>

## 在你繼續之前，一些最佳實務

### 閱讀文件

我們維護著詳盡且持續更新的文件。既然你已經到這裡了，就花點時間瀏覽左側導覽中的各個章節吧。

### 錯誤碼很重要

你必須處理它們，才能讓你的使用者獲得良好的體驗。

<Card title="錯誤" icon="link" href="/errors/overview" horizontal />

### 妥善保管你的 API 金鑰

我們非常重視資訊安全，你也應該如此。你完全掌握 Ayrshare 與你社群媒體帳戶之間的連線。一旦帳戶完成連結，Ayrshare API 金鑰就是你進行身分驗證的憑證。請務必將此金鑰保密並妥善保存。

### 發布測試貼文

你可以在 [/post 端點](/apis/post/post) 中使用 `randomPost`、`randomMediaUrl`，以及 `isLandscapeVideo` 或 `isPortraitVideo` 參數，發布帶有隨機引言、圖片或影片的測試貼文。若使用了 `randomPost`，就不再需要 `post` 參數。

<div class="video-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/hMI0eK-5qBk?si=y5dkygosZ1B2DtlV" title="Post Random Content" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" />
</div>

<Warning>
  這些貼文會實際發布到你的社群媒體頁面上，測試完成後如有需要請及時刪除。
</Warning>

#### 隨機引言

加上 `randomPost: true` 即可送出一則隨機引言，用於測試發文。

搭配 [/post](/apis/post/post) 端點使用。

```json theme={"system"}
"randomPost": true
```

#### 隨機圖片

加上 `randomMediaUrl: true` 即可送出一張隨機圖片。

搭配 [/post](/apis/post/post) 端點使用。

```json theme={"system"}
"randomMediaUrl": true
```

#### 隨機影片

加上 `isVideo: true` 與 `isLandscapeVideo: true` 即可送出一段隨機的橫向影片。
影片將採標準橫向尺寸。

搭配 [/post](/apis/post/post) 端點使用。

```json theme={"system"}
"randomMediaUrl": true,
"isLandscapeVideo": true
```

加上 `isVideo: true` 與 `isPortraitVideo: true` 即可送出一段隨機的直向影片，適用於 TikTok 或 Facebook/Instagram Reels。

搭配 [/post](/apis/post/post) 端點使用。

```json theme={"system"}
"randomMediaUrl": true,
"isPortraitVideo": true
```

#### 隨機留言

加上 `randomComment: true` 即可送出一則隨機留言，用於測試發布留言。

搭配 [/comment](/apis/comments/post-comment) 端點使用。

```json theme={"system"}
"randomComment": true
```

#### cURL 呼叫範例

送出一則隨機引言與直向影片。

```bash theme={"system"}
curl \
-H "Authorization: Bearer API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
    "randomPost": true,
    "platforms": ["facebook", "instagram", "linkedin"],
    "randomMediaUrl": true,
    "isPortraitVideo": true
}' \
https://api.ayrshare.com/api/post
```

### **使用 Postman 測試你的 API 呼叫**

[Postman](https://www.postman.com/) 是測試 API 呼叫的絕佳工具。你甚至可以用它產生十幾種語言的程式碼。

### 示範程式碼

如果你想找以 React 與 Node.js 建置的示範專案，請參考這個 GitHub 儲存庫：

<Card title="Github 社群發文示範應用" icon="github" href="https://github.com/ayrshare/social-api-demo" horizontal />

### **常見疑難排解**

有時事情不會一帆風順，以下是我們幫助中心提供的一些協助。

<Card title="疑難排解" icon="link" href="/help-center/overview" horizontal />

### **需要協助時聯絡我們**

我們隨時願意提供協助，請使用右下角的聊天功能，或[寄電子郵件給我們](mailto:support@ayrshare.com)。
