Tips & Tricks (अपडेट: 3/6/2026)

Claude Code से SaaS Integration: API Key, OAuth, Webhook और Audit Log

Claude Code से SaaS integration की व्यावहारिक guide: API keys, OAuth, webhooks, retries, secrets और audit logs.

Claude Code से SaaS Integration: API Key, OAuth, Webhook और Audit Log

Claude Code से SaaS integration बनाते समय पहला सवाल यह नहीं होना चाहिए कि “कौन सा endpoint call करें?” पहला सवाल है: authorization सुरक्षित कैसे होगा, retry करने पर duplicate काम कैसे नहीं बनेगा, और बाद में यह कैसे साबित होगा कि किसने क्या किया। यह layer छोड़ दी जाए तो Slack notification जैसा छोटा automation भी security, billing या operations की समस्या बन सकता है।

यह guide API keys, OAuth, webhooks, rate limits, retries, idempotency, audit logs, secrets और test environments को Claude Code के साथ इस्तेमाल करने लायक practical workflow में बदलती है। Webhook का मतलब है SaaS service से आपके server पर आने वाला event. Idempotency का मतलब है कि वही operation दोबारा चले तो duplicate result न बने. Audit log वह record है जिससे automation को बाद में समझाया जा सके।

Examples Node.js 20 या उससे नए version पर चलते हैं और इन्हें scripts/ folder में copy किया जा सकता है।

Integration Architecture

Claude Code को integration state रखने की अकेली जगह न बनाएं। Claude Code planning, code generation और command execution के लिए अच्छा है; tokens, retry state और audit history connector code में रहनी चाहिए।

flowchart LR
  A[Claude Code] --> B[CLI or MCP connector]
  B --> C[Auth and secret store]
  B --> D[Retry and rate-limit wrapper]
  D --> E[SaaS API]
  E --> F[Webhook receiver]
  F --> G[Queue]
  G --> H[Worker]
  H --> I[Audit log]

सबसे छोटा उपयोगी रूप CLI wrapper है, जैसे node scripts/slack-notify.mjs, जिसे Claude Code चला सकता है। अगर workflow बार-बार उपयोग होता है, तो उसे MCP server में बदलें ताकि input schema, permissions और error handling reuse हो सकें। Webhook receiver ज्यादा मेहनत मांगता है, लेकिन जब Stripe, GitHub, Slack या कोई और SaaS workflow शुरू करता है, तब यह जरूरी होता है।

चार ठोस Use Cases

पहला use case release operations है। Claude Code GitHub के unreleased commits पढ़ता है, release notes बनाता है और Slack में छोटा summary भेजता है। Slack Incoming Webhooks जल्दी setup हो जाते हैं, लेकिन message delete करने या complex chat flow के लिए Slack Web API बेहतर है।

दूसरा use case billing automation है। Stripe webhook checkout.session.completed receive करता है, customer को internal tool में record करता है और failed काम को retry queue में डालता है। यहां signature verification, idempotency keys और test mode तथा live mode की साफ separation अनिवार्य है।

तीसरा use case support triage है। Google Workspace OAuth backend को support CSV पढ़ने देता है, Claude Code rows classify करता है, और engineering follow-up के लिए GitHub issues बनते हैं। चूंकि यह user data को छूता है, shared API key के बजाय narrow read-only OAuth scopes safer हैं।

चौथा use case audit dashboard है। Claude Code से trigger हुई हर SaaS action को NDJSON में लिखा जाता है ताकि team actor, provider, action, target और idempotency key देख सके। Full audit platform से पहले भी यह बहुत काम आता है।

API Key, OAuth, Webhook या Connector कैसे चुनें

तरीकाआसान भाषा में अर्थकब उपयोग करेंध्यान रखें
API keyServer-side shared credentialStripe server calls, internal Slack alertsSource code में नहीं, environment variable या secret manager में रखें
OAuthUser या workspace access grant करता हैGoogle Drive, GitHub Apps, user-specific actionsRefresh tokens और scopes की साफ design चाहिए
WebhookSaaS आपके endpoint पर event भेजता हैStripe payments, GitHub issues, Slack eventsSignature verify करें, duplicate delivery handle करें, order assume न करें
CLI/MCP connectorClaude Code द्वारा call की जाने वाली stable tool layerRunbooks, internal ops, multi-SaaS workflowsValidation और logging connector में रखें

Google OAuth 2.0 documentation access token और refresh token flow समझाती है। GitHub और Slack में भी actor-aware logs जरूरी हैं, क्योंकि permission debug करते समय “bot ने किया” पर्याप्त जवाब नहीं होता।

Environment Variable Checklist

पहले .env.example बनाएं और केवल नाम share करें। Real values Git में नहीं जाएंगी।

# .env.example
INTEGRATION_ENV=sandbox
SAAS_API_TOKEN=
SLACK_WEBHOOK_URL=
GITHUB_WEBHOOK_SECRET=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
AUDIT_LOG_PATH=logs/saas-audit.ndjson
# .gitignore
.env
.env.*
!.env.example
logs/

Claude Code से integration चलाने से पहले यह check करें:

  • Live keys और test keys अलग environments में हैं।
  • Secrets कभी Claude Code prompt में paste नहीं किए गए।
  • Error में Authorization header या webhook secret print नहीं होता।
  • OAuth scopes read-only से शुरू होते हैं और जरूरत पर ही बढ़ते हैं।
  • CI values secrets के रूप में register हैं, public repository variables के रूप में नहीं।
  • Key rotation की date और owner record है।

Retry और Rate Limit Wrapper

Rate limit provider द्वारा allowed request speed की सीमा है। GitHub REST APIs में primary और secondary limits हैं, और limit fail होने पर response headers मानने चाहिए। Slack 429 Too Many Requests और Retry-After देता है। यह behavior prompt में नहीं, code में होना चाहिए।

// scripts/saas-request.mjs
import crypto from "node:crypto";
import { pathToFileURL } from "node:url";

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function saasRequest(url, options = {}) {
  const {
    method = "GET",
    token = process.env.SAAS_API_TOKEN,
    body,
    idempotencyKey = method === "POST" ? crypto.randomUUID() : undefined,
    maxRetries = 4,
    headers = {},
  } = options;

  for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
    const res = await fetch(url, {
      method,
      headers: {
        Accept: "application/json",
        ...(body ? { "Content-Type": "application/json" } : {}),
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
        ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
        ...headers,
      },
      body: body ? JSON.stringify(body) : undefined,
    });

    if (res.ok) return res;

    const retryAfter = Number(res.headers.get("retry-after"));
    const shouldRetry = [408, 409, 425, 429, 500, 502, 503, 504].includes(res.status);

    if (!shouldRetry || attempt === maxRetries) {
      const text = await res.text();
      throw new Error(`SaaS request failed: ${res.status} ${text.slice(0, 200)}`);
    }

    const backoffMs = Number.isFinite(retryAfter)
      ? retryAfter * 1000
      : Math.min(30000, 500 * 2 ** attempt);

    await sleep(backoffMs);
  }

  throw new Error("unreachable");
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const url = process.argv[2];
  if (!url) throw new Error("Usage: node scripts/saas-request.mjs <url>");
  const res = await saasRequest(url);
  console.log(await res.text());
}

Stripe जैसी APIs idempotency keys support करती हैं, इसलिए वही POST safely retry किया जा सकता है। अपने workers में provider + event_id + action जैसी key रखें और अगर वह पहले से processed है तो काम skip करें।

Webhook Verification Flow

Webhooks public HTTP entry points होते हैं। Signature verification न हो तो कोई भी fake event भेज सकता है। GitHub X-Hub-Signature-256 use करता है; Stripe Stripe-Signature use करता है। मुख्य नियम है कि JSON parse करने से पहले raw body verify करें।

1. Raw body पढ़ें.
2. Signature header पढ़ें.
3. Shared secret से HMAC calculate करें.
4. Timing-safe comparison करें.
5. Delivery id को idempotency key के रूप में save करें.
6. तुरंत 202 return करें और heavy work queue में process करें.
// scripts/verify-github-webhook.mjs
import crypto from "node:crypto";
import http from "node:http";

const secret = process.env.GITHUB_WEBHOOK_SECRET;
if (!secret) throw new Error("Set GITHUB_WEBHOOK_SECRET");

function verifyGitHubSignature(rawBody, signatureHeader) {
  const received = Array.isArray(signatureHeader)
    ? signatureHeader[0]
    : signatureHeader ?? "";
  const expected =
    "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  const receivedBytes = Buffer.from(received);
  const expectedBytes = Buffer.from(expected);

  return (
    receivedBytes.length === expectedBytes.length &&
    crypto.timingSafeEqual(receivedBytes, expectedBytes)
  );
}

http
  .createServer(async (req, res) => {
    const chunks = [];
    for await (const chunk of req) chunks.push(chunk);
    const rawBody = Buffer.concat(chunks);

    if (!verifyGitHubSignature(rawBody, req.headers["x-hub-signature-256"])) {
      res.writeHead(401);
      res.end("invalid signature");
      return;
    }

    const event = req.headers["x-github-event"];
    const delivery = req.headers["x-github-delivery"];
    console.log(JSON.stringify({ event, delivery, receivedAt: new Date().toISOString() }));

    res.writeHead(202, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ ok: true }));
  })
  .listen(3000, () => console.log("Listening on http://localhost:3000"));

Stripe के लिए production में official SDK का constructEvent() इस्तेमाल करना बेहतर है। Test और live webhook secrets अलग होते हैं, इसलिए STRIPE_WEBHOOK_SECRET environment-specific रखें।

Audit Logs

Audit log वह record है जिससे automated action को बाद में explain किया जा सके। Claude Code chat history काफी नहीं है; timestamp, actor, provider, action, target, idempotency key और status चाहिए।

{
  "ts": "2026-06-03T09:15:00.000Z",
  "actor": "claude-code",
  "provider": "github",
  "action": "create_issue",
  "target": "owner/repo#123",
  "idempotencyKey": "github:issue:customer-42:2026-06-03",
  "status": "succeeded"
}
// scripts/audit-log.mjs
import { appendFile, mkdir } from "node:fs/promises";
import { dirname } from "node:path";

export async function writeAudit(event) {
  const record = {
    ts: new Date().toISOString(),
    actor: event.actor ?? "claude-code",
    provider: event.provider,
    action: event.action,
    target: event.target,
    idempotencyKey: event.idempotencyKey,
    status: event.status ?? "started",
  };
  const file = process.env.AUDIT_LOG_PATH ?? "logs/saas-audit.ndjson";
  await mkdir(dirname(file), { recursive: true });
  await appendFile(file, `${JSON.stringify(record)}\n`, "utf8");
}

if (process.argv[1]?.endsWith("audit-log.mjs")) {
  await writeAudit({
    provider: "slack",
    action: "post_message",
    target: "#release",
    idempotencyKey: "demo-2026-06-03",
    status: "succeeded",
  });
}

पहले version के लिए NDJSON पर्याप्त है। बाद में इसे BigQuery, DuckDB या spreadsheet में import किया जा सकता है।

आम गलतियां

पहली गलती webhook को सीधे localhost पर deliver कराने की कोशिश है। GitHub troubleshooting docs बताते हैं कि webhook URL publicly reachable होना चाहिए। Local test के लिए forwarding service और production में HTTPS endpoint रखें।

दूसरी गलती webhook order पर भरोसा करना है। Providers events देर से या अलग order में भेज सकते हैं। Arrival order की जगह event timestamps, delivery ids और current resource state देखें।

तीसरी समस्या retry से duplicate काम बनना है। Payments, issues, Slack posts और emails users को दिखते हैं। POST requests में idempotency keys जोड़ें और webhook workers में processed delivery ids store करें।

चौथी गलती बहुत broad OAuth scope मांगना है। Read-only access, एक folder या workspace और short-lived tokens से शुरू करें। Risk साफ समझ आने पर ही scope बढ़ाएं।

पांचवीं गलती secrets को Claude Code में paste करना है। Claude Code से environment variable names इस्तेमाल करवाएं; real values secret manager, CI secret या local .env में रखें।

Connector Abstraction कब बनाएं

पहला script सीधा और simple हो सकता है। जब authorization, pagination, rate limiting, audit logging और error formatting तीन workflows में repeat होने लगें, connector बनाएं।

Abstraction को business language में नाम दें: sendMessage(), createTicket(), recordPaymentEvent(), writeAudit(). पतला callSlackApi() wrapper Claude Code के लिए उतना उपयोगी नहीं जितना वह function जो workflow का outcome बताता है।

पास के implementation topics के लिए Claude Code API Design Assistant और Claude Code API Testing देखें। Production access से पहले risk review के लिए Claude Code Security Best Practices पढ़ें।

Official References

अगर Claude Code integrations team workflows में जा रहे हैं, तो पहले reusable templates तैयार करें। Practical checklists /products/ में हैं और team enablement /training/ में उपलब्ध है।

Practical testing में पाया कि जिन integrations में पहले दिन से signature verification, idempotency, audit logs और अलग test environments थे, उन्हें बाद में extend करना बहुत आसान था। छोटी Slack notification भी ज्यादा reliable हो जाती है जब failure trace किया जा सके और सोच-समझकर replay किया जा सके।

#claude-code #saas #notion #slack #linear #github #figma #integration
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.