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

# 產生 JWT

> 產生用於單一登入（SSO）的 JSON Web Token（JWT）。

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="/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="/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="/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} />

產生用於單一登入（SSO）的 JSON Web Token（JWT）。

詳情請參閱 [Generate JWT 概觀](/apis/profiles/generate-jwt-overview)。

<Note>
  JWT URL 的有效期為 **5 分鐘**。5 分鐘後你必須產生新的 JWT URL。
  其他選項請參閱 Max Pack 的 `expiresIn` [設定](/apis/profiles/generate-jwt-overview#jwt-expires-in)。
</Note>

## 標頭參數

<HeaderAPI noProfileKey />

<ParamField header="X-Twitter-OAuth1-Api-Key" type="string">
  你從 X Developer Portal 取得的 X API Key（Consumer Key）。是 `twitterApiKey` body 參數的替代方式。當提供時，產生的 JWT URL 將使用你自己的 X Developer App 進行 OAuth 連結。
</ParamField>

<ParamField header="X-Twitter-OAuth1-Api-Secret" type="string">
  你從 X Developer Portal 取得的 X API Secret（Consumer Secret）。是 `twitterApiSecret` body 參數的替代方式。當提供了 `X-Twitter-OAuth1-Api-Key` 時為必填。
</ParamField>

<Info>
  \*\*建議：\*\*透過標頭（`X-Twitter-OAuth1-Api-Key` 與 `X-Twitter-OAuth1-Api-Secret`）傳遞你的 X 認證資料，以便與所有其他 Ayrshare API 端點的做法保持一致。為了向下相容，仍然支援 `twitterApiKey` 與 `twitterApiSecret` body 參數。
</Info>

## Body 參數

<ParamField body="domain" type="string" required>
  App 的網域。請使用你在導入期間所取得的確切網域。
</ParamField>

<ParamField body="privateKey" type="string" required>
  用於加密的 Private Key。
</ParamField>

<ParamField body="profileKey" type="string" required>
  User Profile Key。此欄位不能使用 API Key。
</ParamField>

<ParamField body="logout" type="boolean" default={false}>
  自動登出目前的工作階段。建議不要在正式環境中使用，因為會影響效能。

  更多資訊請參閱[自動登出 Profile 工作階段](/multiple-users/api-integration-business#automatic-logout-of-a-profile-session)。
</ParamField>

<ParamField body="redirect" type="string">
  指定當使用者點擊「Done」按鈕或 Logo 圖片時要轉向的 URL。該 URL 會在回傳的 JWT URL 中自動被縮短。若要[轉向原始](/multiple-users/api-integration-business#opening-and-closing-the-social-linking-url)開啟者視窗，請在 redirect URL 中加入 `origin=true` 查詢參數。
</ParamField>

<ParamField body="allowedSocial" type="array">
  指定要在連結頁面上顯示的社群網路。此設定會覆寫 [Social Networks](/multiple-users/manage-user-profiles#set-social-networks-access) 頁面所設定的社群網路。

  ```json Only display Facebook, X/Twitter, LinkedIn, and TikTok theme={"system"}
  {
    "allowedSocial": ["facebook", "twitter", "linkedin", "tiktok"]
  }
  ```
</ParamField>

<ParamField body="instagramLinkMethod" type="string">
  針對此 URL，覆寫使用者在社群連結頁面點擊 Instagram 按鈕時所使用的 Instagram 連結流程。有效值：

  * `instagram`：直接的 Instagram Login，不需 Facebook 粉絲專頁。
  * `facebook`：透過已連結的 Facebook 粉絲專頁連結 Instagram。

  ```json Force direct Instagram Login for this linking session theme={"system"}
  {
    "instagramLinkMethod": "instagram"
  }
  ```

  若省略此欄位，連結頁面將沿用你的帳號層級 [Instagram Login](/multiple-users/manage-user-profiles#instagram-login) 設定。

  更多資訊請參閱 [Instagram 連結方式](/apis/profiles/generate-jwt-overview#instagram-link-method)。
</ParamField>

<ParamField body="verify" type="boolean" default={false}>
  驗證產生的 Token 是否有效。建議僅在非正式環境使用。

  更多資訊請參閱[開啟與關閉社群連結 URL](/multiple-users/api-integration-business#opening-and-closing-the-social-linking-url)。
</ParamField>

<ParamField body="base64" type="boolean" default={false}>
  若 Private Key 為 base64 編碼，請設為 `true`。

  將 private.key 檔案以 base64 編碼，並將產生的單行字串以 `privateKey` 欄位傳入。

  例如在 Linux 中：`cat private.key | base64`
</ParamField>

<ParamField body="expiresIn" type="number" default={5}>
  設定 Token 的有效期，單位為分鐘。範圍：1 分鐘至 2880 分鐘。

  更多資訊請參閱 [JWT Expires In](/apis/profiles/generate-jwt-overview#jwt-expires-in)。
</ParamField>

<ParamField body="email" type="object" default={5}>
  寄送 Connect Accounts 電子郵件，內含可讓使用者直接前往社群連結頁面的連結。

  更多資訊請參閱 [Connect Accounts 電子郵件](/apis/profiles/generate-jwt-overview#connect-accounts-email)。
</ParamField>

<Info>
  當你附上 X API 認證資料時，產生的 JWT URL 將以你自己的 X Developer App 啟動 OAuth 連結流程。你的終端使用者會在 X 的授權同意畫面上看到你的 App 名稱。
</Info>

<Warning>
  \*\*必要條件：\*\*在使用此功能之前，你必須在 X Developer App 設定中（Authentication settings > Callback URI / Redirect URL）加入以下回呼 URL：

  * `https://profile.ayrshare.com/social-accounts`
  * `https://app.ayrshare.com/social-accounts`

  若未設定，OAuth 流程將失敗並回傳 `403 Callback URL not approved` 錯誤。
</Warning>

<RequestExample>
  ```javascript cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Content-Type: application/json' \
  -H "X-Twitter-OAuth1-Api-Key: YOUR_CONSUMER_KEY" \
  -H "X-Twitter-OAuth1-Api-Secret: YOUR_CONSUMER_SECRET" \
  -d '{"domain": "ACME", "privateKey": "-----BEGIN RSA PRIVATE KEY...", "profileKey": "PROFILE_KEY"}' \
  -X POST https://api.ayrshare.com/api/profiles/generateJWT
  ```

  ```javascript JavaScript theme={"system"}
  const fs = require('fs');
  const API_KEY = "API_KEY";
  const PROFILE_KEY = "PROFILE_KEY";

  // Read in local private.key files - also can read from a DB
  const privateKey = fs.readFileSync('private.key', 'utf8');

  fetch("https://api.ayrshare.com/api/profiles/generateJWT", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${API_KEY}`,
          "X-Twitter-OAuth1-Api-Key": "YOUR_CONSUMER_KEY",
          "X-Twitter-OAuth1-Api-Secret": "YOUR_CONSUMER_SECRET"
        },
        body: JSON.stringify({
          domain: "ACME",          // required
          privateKey,              // required
          profileKey: PROFILE_KEY, // required
        }),
      })
        .then((res) => res.json())
        .then((json) => console.log(json))
        .catch(console.error);
  ```

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

  # Read in local private.key files - also can read from a DB
  with open('.private.key') as f:
      profileKey = f.read()

  payload = {'domain': 'ACME',
          'privateKey': profileKey,
          'profileKey': 'PROFILE_KEY' }
  headers = {'Content-Type': 'application/json',
          'Authorization': 'Bearer API_KEY',
          'X-Twitter-OAuth1-Api-Key': 'YOUR_CONSUMER_KEY',
          'X-Twitter-OAuth1-Api-Secret': 'YOUR_CONSUMER_SECRET'}

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

  print(r.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(
      'POST',
      'https://api.ayrshare.com/api/post',
      [
          'headers' => [
              'Content-Type'  => 'application/json',
              'Authorization' => 'Bearer API_KEY'
          ],
          'json' => [
              'domain' => 'ACME',
              'privateKey' => '-----BEGIN RSA PRIVATE KEY...', // required
              'profileKey' => 'PROFILE_KEY', // requires
          ]
      ]
  );

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

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

  namespace GenerateJWTRequest_csharp
  {
    class GenerateJWT
    {
        static async Task Main(string[] args)
        {
            string API_KEY = "API_KEY";
            string url = "https://api.ayrshare.com/api/profiles/generateJWT";

            try
            {
                string privateKey = await File.ReadAllTextAsync("./private.key");

                var sendData = new
                {
                    domain = "domain",
                    privateKey = privateKey,
                    profileKey = "PROFILE_KEY"
                };

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);

                    string jsonData = JsonConvert.SerializeObject(sendData);
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();

                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"Private key file not found: {e.Message}");
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"HTTP request error: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unexpected error: {e.Message}");
            }
        }
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Success theme={"system"}
  {
      "status": "success",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LY-E",
      "emailSent": true,    
      "expiresIn": "30m"    
  }
  ```

  ```json 400: Private Key Formatted Incorrectly theme={"system"}
  {
    "action": "JWT",
    "status": "error",
    "code": 189,
    "message": "Error generating JWT. Check the sent parameters, such as the privateKey has no extra tabs, spaces, or newlines. Error: error:0909006C:PEM routines:get_name:no start line"
  }
  ```

  ```json 400: Partial Twitter API Keys theme={"system"}
  {
    "action": "JWT",
    "status": "error",
    "code": 188,
    "message": "Both twitterApiKey and twitterApiSecret are required. You provided only one."
  }
  ```

  ```json 400: Duplicate X/Twitter Credentials theme={"system"}
  {
      "action": "JWT",
      "status": "error",
      "code": 434,
      "message": "X/Twitter API credentials were provided in both the request headers and the request body. Please use the headers only. See https://www.ayrshare.com/docs/apis/profiles/generate-jwt"
  }
  ```
</ResponseExample>
