> ## 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="设置请求头">
    我们设置了请求头的 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)。
