可灵专业级视频

具备先进运动控制能力的专业视频生成。提供 v1 至 v2.1 模型,支持标准和专业模式。

✓ 最长 10 秒视频

✓ 专业与标准模式

✓ 镜头控制

✓ 1080p 分辨率

身份验证

要通过 Doitong API 访问 可灵 (Kling),请使用您的 Doitong API 密钥。请将其包含在 GraphQL mutation 或 REST API 请求头中。

重要提示: 请妥善保管您的 Doitong API 密钥,切勿在客户端代码中泄露。请务必通过后端服务器发起 API 调用。
// GraphQL Header
{
  "Authorization": "Bearer YOUR_API_KEY"
}

// REST Header
"X-API-Key": "YOUR_API_KEY"

快速开始

只需几分钟即可上手 Kling API。按照以下简单步骤生成您的第一个 text to video。

步骤 1:获取 API 密钥

注册 Doitong 账号并前往控制台生成 API 密钥。

步骤 2:发起首次请求

使用下方的代码示例发起您的第一次 API 调用。

curl -X POST https://api.doitong.com/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: unique-request-id-123" \
  -d '{
    "query": "mutation Generate($input: GenerateInput!) { generate(input: $input) { id status type provider url metadata creditCost } }",
    "variables": {
      "input": {
        "type": "VIDEO",
        "provider": "kling",
        "input": {
          "text": "A serene landscape with mountains and a lake at sunset"
        },
        "options": {
          "duration": 5,
          "aspectRatio": "16:9"
        }
      }
    }
  }'
const response = await fetch('https://api.doitong.com/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY',
    'Idempotency-Key': 'unique-request-id-123'
  },
  body: JSON.stringify({
    query: `
      mutation Generate($input: GenerateInput!) {
        generate(input: $input) {
          id
          status
          type
          provider
          url
          metadata
          creditCost
        }
      }
    `,
    variables: {
      input: {
        type: 'VIDEO',
        provider: 'kling',
        input: {
          text: 'A serene landscape with mountains and a lake at sunset'
        },
        options: {
          duration: 5,
          aspectRatio: '16:9'
        }
      }
    }
  })
});

const data = await response.json();
console.log('Result:', data.data.generate);
import requests
import json

url = "https://api.doitong.com/graphql"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"
}

query = """
mutation Generate($input: GenerateInput!) {
  generate(input: $input) {
    id
    status
    type
    provider
    url
    metadata
    creditCost
  }
}
"""

variables = {
    "input": {
        "type": "VIDEO",
        "provider": "kling",
        "input": {
            "text": "A serene landscape with mountains and a lake at sunset"
        },
        "options": {
            "duration": 5,
            "aspectRatio": "16:9"
        }
    }
}

response = requests.post(url, json={
    "query": query,
    "variables": variables
}, headers=headers)

data = response.json()
print("Result:", data["data"]["generate"])
mutation Generate($input: GenerateInput!) {
  generate(input: $input) {
    id
    status
    type
    provider
    url
    metadata
    creditCost
    createdAt
  }
}

# Variables
{
  "input": {
    "type": "VIDEO",
    "provider": "kling",
    "input": {
      "text": "A serene landscape with mountains and a lake at sunset"
    },
    "options": {
      "duration": 5,
      "aspectRatio": "16:9",
      "version": "2.1-master",
      "quality": "high"
    }
  }
}

价格方案

Kling API 采用基于积分的计费模式。积分消耗取决于生成内容的复杂程度和时长。

功能 积分 描述
标准模式 100-200 积分 5-10 秒标准画质视频
专业模式 300-500 积分 5-10 秒专业画质视频

API 端点

Kling API 可通过我们的统一 GraphQL 端点访问。

GraphQL 端点

POST https://api.doitong.com/graphql

REST 端点

POST https://api.doitong.com/v1/text_to_video

参数

Kling API 请求的可用参数:

参数 类型 必填 描述
service 字符串 Yes 服务标识符: "kling"
prompt 字符串 Yes 生成内容的文本描述
duration 整数 No 视频时长(秒)(默认值:5)
aspectRatio 字符串 No 纵横比:"16:9"、"9:16"、"1:1"(默认值:"16:9")
version 字符串 No Model version: "1.0", "1.5", "1.6", "2.0", "2.1", "2.1-master"
webhookUrl 字符串 No 接收完成通知的 URL

响应格式

所有 API 响应均遵循统一格式:

成功响应

{
  "data": {
    "generatevideo": {
      "id": "abc123xyz",
      "status": "processing",
      "url": null,
      "webhookUrl": "https://your-webhook.com/callback",
      "createdAt": "2024-01-01T00:00:00Z"
    }
  }
}

完成响应

{
  "data": {
    "generatevideo": {
      "id": "abc123xyz",
      "status": "completed",
      "url": "https://cdn.doitong.com/outputs/abc123xyz.mp4",
      "duration": 5,
      "createdAt": "2024-01-01T00:00:00Z"
    }
  }
}

错误处理

API 使用标准 HTTP 状态码并返回详细的错误信息。

常见错误代码

状态码 错误类型 描述
400 Bad Request Invalid parameters or malformed request
401 Unauthorized Missing or invalid API key
402 Payment Required Insufficient credits
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error, please retry

错误响应格式

{
  "errors": [
    {
      "message": "Insufficient credits for this operation",
      "extensions": {
        "code": "INSUFFICIENT_CREDITS",
        "creditsRequired": 100,
        "creditsAvailable": 50
      }
    }
  ]
}

Webhooks

在 text to video 生成完成后接收实时通知。

设置 Webhooks

Include a <code>webhookUrl</code> parameter in your request to receive a POST notification when processing is complete.

Webhook 负载

{
  "id": "abc123xyz",
  "status": "completed",
  "url": "https://cdn.doitong.com/outputs/abc123xyz.mp4",
  "service": "kling",
  "createdAt": "2024-01-01T00:00:00Z",
  "completedAt": "2024-01-01T00:01:00Z",
  "metadata": {
    "duration": 5,
    "width": 1920,
    "height": 1080
  }
}

Webhook 安全

所有 Webhook 请求都包含一个用于验证的签名请求头:

X-Doitong-Signature: sha256=abc123...

速率限制

为确保公平使用和系统稳定性,适用以下速率限制:

方案 每分钟请求数 (RPM) 并行任务数 每日上限
免费版 10 1 100
入门版 30 3 1,000
专业版 60 10 10,000
企业版 定制化 定制化 无限制
速率限制请求头: 检查响应头以获取当前的限制状态:
  • X-RateLimit-Limit: Maximum requests per window
  • X-RateLimit-Remaining: Requests remaining
  • X-RateLimit-Reset: Window reset timestamp

最佳实践

1. 优化提示词 (Prompts)

编写清晰、描述性的提示词以获得最佳效果:

  • Be specific about visual elements, style, and mood
  • Include details about lighting, camera angles, and composition
  • Avoid contradictory or impossible requests

2. 处理异步流程

生成过程是异步的。请实现适当的轮询或 Webhook:

// Polling example
async function pollStatus(jobId) {
  let status = 'processing';
  while (status === 'processing') {
    await sleep(2000); // Wait 2 seconds
    const result = await checkJobStatus(jobId);
    status = result.status;
  }
  return result;
}

3. 错误恢复

实现带有指数退避机制的重试逻辑:

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

4. 监控积分使用情况

追踪您的积分消耗以避免服务中断:

  • Check credit balance before large batch operations
  • Set up alerts for low credit thresholds
  • Implement credit-aware request queuing

准备好开始了吗?

加入成千上万名开发者的行列,使用 Kling API 创作精彩内容

立即获取 API 密钥 查看价格