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

# 取得 Link Session

> 查詢社群帳號連結 URL 是否已被開啟、是否仍然有效，或是否已被撤銷。

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/docs/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/docs/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/docs/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

<PlansAvailable plans={["business"]} maxPackRequired={false} />

查詢你透過[建立 Link Session](/docs/apis/profiles/create-link-session) 建立的連結 URL 的狀態——你的使用者
是否已開啟它、它是否仍然有效，以及它已被使用了多少次。

當你想在不詢問使用者的情況下得知他們是否已開始連結帳號，或想在建立替代連結之前確認某個連結已失效時，
此端點非常實用。

<Note>
  不存在的 `sessionId`，或屬於其他帳戶的 `sessionId`，都會回傳相同的 `not found` 回應。這是刻意的設計，
  讓此端點無法被用來探測某個識別碼是否真實存在。
</Note>

## 標頭參數

<HeaderAPI profileKeyRequired={true} />

## 路徑參數

<ParamField path="sessionId" type="string" required>
  建立連結時所回傳的 `sessionId`。
</ParamField>

## 連結狀態

`state` 欄位為以下其中之一：

* `pending`：已建立，從未被開啟。
* `active`：至少被開啟過一次，仍在有效期內。
* `expired`：已超過 `expiresAt`。
* `revoked`：已透過[撤銷 Link Session](/docs/apis/profiles/revoke-link-session) 終止。

已撤銷的連結即使超過有效期後仍會回報 `revoked`，因為這是更有用的答案。

## 已連結的帳號

當你的使用者連結帳號時，連結會記錄下來。一旦有帳號連結成功，就會出現三個欄位，在那之前
則不存在：

* `completedAt`：第一個帳號連結完成的時間。
* `lastCompletedAt`：最近一個帳號連結完成的時間。
* `completedNetworks`：在此連結上連結完成的每一個網路。

這些欄位與 `state` 是分開的，且兩者回答的都是真實的問題：一個連結可以是 `active` 卻還沒有連結
任何帳號，也可以是 `expired` 但在到期前已連結了三個帳號。輪詢 `completedNetworks` 正是伺服器端
渲染的應用程式或行動應用程式得知連結完成的方式，也是 Telegram 唯一的訊號——Telegram 的連結在
頻外完成。

<Warning>
  **`completedNetworks` 是此 link session 的歷史紀錄，不是 profile 的目前狀態。**它是只增不減的：
  網路在透過此工作階段連結成功時被加入，且永遠不會被移除，因此在帳號被取消連結、透過其他工作階段
  重新連結，或在網路那一端被中斷連線之後，它仍會列在其中。若要查看**此刻**有哪些網路連結到該
  User Profile，請以 `include=state` 呼叫
  [取得 User Profiles](/docs/apis/profiles/get-profiles)。
</Warning>

<RequestExample>
  ```bash cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Profile-Key: PROFILE_KEY' \
  -X GET https://api.ayrshare.com/api/profiles/link-sessions/SESSION_ID
  ```

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

  fetch(`https://api.ayrshare.com/api/profiles/link-sessions/${SESSION_ID}`, {
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Profile-Key": PROFILE_KEY,
    },
  })
    .then((res) => res.json())
    .then((json) => console.log(json))
    .catch(console.error);
  ```

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

  headers = {'Authorization': 'Bearer API_KEY',
          'Profile-Key': 'PROFILE_KEY'}

  response = requests.get(
      'https://api.ayrshare.com/api/profiles/link-sessions/SESSION_ID',
      headers=headers)
  print(response.json())
  ```

  ```php PHP theme={"system"}
  <?php
  require 'vendor/autoload.php';    // Composer auto-loader using Guzzle. See .../guzzlephp.org/en/stable/overview.html

  $client = new GuzzleHttp\Client();
  $res = $client->request(
      'GET',
      'https://api.ayrshare.com/api/profiles/link-sessions/SESSION_ID',
      [
          'headers' => [
              'Authorization' => 'Bearer API_KEY',
              'Profile-Key'   => 'PROFILE_KEY'
          ]
      ]
  );

  echo json_encode(json_decode($res->getBody()), JSON_PRETTY_PRINT);
  ```

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

  namespace GetLinkSession_csharp
  {
    class GetLinkSession
    {
        static async Task Main(string[] args)
        {
            string API_KEY = "API_KEY";
            string PROFILE_KEY = "PROFILE_KEY";
            string url = "https://api.ayrshare.com/api/profiles/link-sessions/SESSION_ID";

            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);
                    client.DefaultRequestHeaders.Add("Profile-Key", PROFILE_KEY);

                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"HTTP request error: {e.Message}");
            }
        }
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Opened Once, Still Valid theme={"system"}
  {
      "status": "success",
      "sessionId": "c7a2434e72e91bde27579efde0fd6dd0b74ceee29a471fd368407f273708c2e8",
      "state": "active",  // pending | active | expired | revoked - see Link States above.
      "createdAt": "2026-09-01T08:03:26.838Z",  // When the link was created, as an ISO 8601 timestamp.
      "expiresAt": "2026-09-02T08:03:26.838Z",  // When the link stops working.
      "firstUsedAt": "2026-09-01T08:14:02.104Z",  // When the link was first opened. Absent if it never has been.
      "lastUsedAt": "2026-09-01T08:14:02.104Z",  // When the link was most recently opened. Absent if it never has been.
      "useCount": 1,  // How many times the link has been opened. A reload or an OAuth retry increments this.
      "completedAt": "2026-09-01T08:15:44.870Z",  // When the first account was connected. Absent until one is.
      "lastCompletedAt": "2026-09-01T08:16:20.412Z",  // When the most recent was connected. Absent until one is.
      "completedNetworks": ["reddit", "bluesky"]  // Every network connected on this link, append-only. Absent until one is.
  }
  ```

  ```json 200: Created, Never Opened theme={"system"}
  {
      "status": "success",
      "sessionId": "c7a2434e72e91bde27579efde0fd6dd0b74ceee29a471fd368407f273708c2e8",
      "state": "pending",  // Created but never opened, so firstUsedAt and lastUsedAt are absent.
      "createdAt": "2026-09-01T08:03:26.838Z",
      "expiresAt": "2026-09-02T08:03:26.838Z",
      "useCount": 0
  }
  ```

  ```json 404: Not Found theme={"system"}
  {
    "action": "link session",
    "status": "error",
    "code": 502,
    "message": "Social linking session not found. Please request a new linking URL."
  }
  ```
</ResponseExample>
