> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devin.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 通过 Webhook 自动修复工单

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="通过 Webhook 自动修复工单" description="通过 webhook 到会话的桥接，将本地部署或不受支持的工单系统连接到 Devin。" prompt="帮我为我的工单系统设置一条 webhook 到 Devin 的流水线。请按照 https://docs.devin.ai/use-cases/gallery/api-webhook-custom-ticketing 上的指南，引导我完成每一步：创建服务用户账号、构建 webhook 处理程序，以及配置我的工单系统将事件发送到该处理程序。" category="自动化" features="API, Playbooks" />

<div className="uc-detail-wrapper">
  <Tip>不想手动设置？将此页面的链接粘贴到 Devin 会话中，让它帮你完成所有设置。</Tip>

  <Steps>
    <Step title="创建服务用户">
      Devin 使用[服务用户令牌](/zh/api-reference/v3/overview)对 API 调用进行身份验证。这是在生产环境中实现自动化的推荐方式。

      1. 访问 [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) > **Settings** > **Service Users**，创建一个具有 `ManageOrgSessions` 权限的新服务用户
      2. 复制创建后显示的 API 令牌并安全保存—它只会显示一次，你会在 webhook 处理程序中将其用作 `DEVIN_API_KEY`

      要找到你的组织 ID，使用你的令牌调用 `GET https://api.devin.ai/v3/enterprise/organizations` — 该 URL 只会返回组织 slug，而不是 ID。

      使用一个简单的 curl 命令进行测试：

      ```bash theme={null}
      curl -X POST https://api.devin.ai/v3/organizations/YOUR_ORG_ID/sessions \
        -H "Authorization: Bearer YOUR_API_TOKEN" \
        -H "Content-Type: application/json" \
        -d '{"prompt": "Say hello — this is a test session."}'
      ```

      你应该会收到一个 `session_id` 和 `url`。在 Devin Web 应用中删除该测试会话，然后继续。
    </Step>

    <Step title="构建 Webhook 处理器">
      这种模式非常适合用于**本地部署的工单系统** (例如自托管的 Jira、Redmine 或 Bugzilla) ，或者**没有原生 Devin 集成的工单工具** (不同于 [Linear](/zh/integrations/linear) 和 [Jira Cloud](/zh/integrations/jira)，它们具有内置支持) 。如果你的工单系统支持 Webhook，你可以通过一个小型服务将其与 Devin 对接。

      在提示中包含你的工单系统 API 文档的链接，以便 Devin 能够了解如何向工单回发评论。将工单系统的 API token 作为[会话密钥](/zh/api-reference/common-flows)传入，这样 Devin 就可以直接进行身份验证。

      让 Devin 来生成脚手架代码：

      <PromptBlock>
        ```txt Webhook handler for custom ticketing theme={null}
        Build an Express.js service that:
        1. Accepts POST /webhooks/tickets with a JSON body containing id, title,
           description, and labels
        2. Verifies the webhook signature using HMAC-SHA256
        3. Skips tickets without a "devin-autofix" or "devin-feature" label
        4. Calls POST https://api.devin.ai/v3/organizations/{org_id}/sessions
           with a prompt built from the ticket fields, a playbook_id based on
           the label, and the ticketing API token as a session secret

        Read DEVIN_API_KEY, DEVIN_ORG_ID, TICKET_API_TOKEN, and WEBHOOK_SECRET
        from environment variables.
        ```
      </PromptBlock>

      核心处理程序大致如下所示：

      ```javascript theme={null}
      const PLAYBOOKS = {
        'devin-autofix': 'playbook-a1b2c3d4e5f6',
        'devin-feature': 'playbook-f6e5d4c3b2a1',
      };

      app.post('/webhooks/tickets', async (req, res) => {
        if (!verifySignature(req)) return res.status(401).send('Bad signature');

        const { id, title, description, labels } = req.body;
        const label = labels.find(l => PLAYBOOKS[l]);
        if (!label) return res.status(200).send('No Devin label — skipped');

        const orgId = process.env.DEVIN_ORG_ID;
        const { session_id } = await fetch(
          `https://api.devin.ai/v3/organizations/${orgId}/sessions`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            prompt: [
              `Ticket ${id}: ${title}`,
              description,
              `Reference ticket ${id} in your commit message.`,
              `When done, post a comment on ticket ${id} with a summary of your`,
              `changes and a link to the PR. Use the ticketing API at`,
              `https://your-ticketing-system.com/api/docs to post the comment.`,
              `Authenticate with the $TICKET_API_TOKEN environment variable.`,
            ].join('\n\n'),
            playbook_id: PLAYBOOKS[label],
            session_secrets: [
              { key: 'TICKET_API_TOKEN', value: process.env.TICKET_API_TOKEN },
            ],
          }),
        }).then(r => r.json());

        res.json({ session_id });
      });
      ```

      `PLAYBOOKS` 映射会将工单标签路由到你在 **Settings > Playbooks** 中创建的[运行手册](/zh/product-guides/creating-playbooks)。一个修复 bug 的运行手册可能会写着 *“始终添加回归测试”*；一个功能类运行手册可能会写着 *“创建一个草稿 PR 并请求评审。”*

      提示词中包含指向你工单系统 API 文档的链接，以便 Devin 知道如何回写评论。`TICKET_API_TOKEN` 作为[会话密钥](/zh/api-reference/common-flows)传入 —— 它只会在该会话中以环境变量的形式注入，不会被持久存储。请将示例中的 API 文档 URL 替换为你实际工单系统的文档地址。

      将 handler 部署到任意可以接收 HTTPS POST 请求的地方——云函数 (AWS Lambda、Google Cloud Functions) 、容器或 VPS。然后在工单系统的通知或集成设置中，将其 URL 注册为一个 webhook，并仅筛选 **ticket created** 事件。

      创建一个带有 `devin-autofix` 标签的测试工单来验证完整闭环：工单创建 → webhook 触发 → Devin 会话启动 → PR 创建 → Devin 在工单上发布评论。
    </Step>
  </Steps>
</div>
