설정에서 API 통화를 RUB, USD, EUR 중 선택합니다. 잔액, 카탈로그, 새 견적은 해당 currency를 사용합니다. 견적은 통화와 exchange_rate를 5분간 고정합니다. 설정이나 환율이 바뀌어도 기존 quote_id와 결제된 주문 가격은 변경되지 않습니다.
금액은 소수점 아래 최대 8자리의 문자열이며, unit_price는 작은 금액의 정밀도를 위해 최대 18자리를 사용합니다. exchange_rate는 통화 1단위당 RUB, rate_date는 환율 기준일입니다. 원래 결제 금액은 price_rub, 기본 잔액은 balance_rub에 있습니다. 예제에서는 RUB를 사용합니다.
요금제와 맞춤 설정은 중지된 구독을 생성하므로 start로 시작해야 합니다. YouTube 시청자 v2는 구매 후 자동 시작됩니다. pending, submitting, unknown은 거절을 뜻하지 않습니다. 새 주문을 만들지 말고 같은 주문을 확인하세요.
예제 변수
매개변수
설명
STREAMKIT_API_KEY
환경 변수에 저장된 전체 API 키입니다.
service_id
카탈로그의 서비스 ID입니다. 예: plan:12 또는 smm:45.
quote_id
POST /quotes에서 반환되는 견적 UUID입니다.
order_id
구매 응답의 전체 id입니다. 예: subscription:123.
target
서비스 대상 채널, 동영상 또는 프로필입니다.
Idempotency-Key
고유한 구매 키입니다. 재시도 시 원래 값을 유지하세요.
예제의 식별자, 가격, 응답은 설명용입니다. 본인의 카탈로그, 견적, 주문에 있는 값을 사용하세요.
서비스
상품, 요금제, 맞춤 설정, YouTube 시청자 v2, AI 챗봇은 공통 견적 및 구매 메서드를 사용합니다. family로 필터링하고 GET /services에서 실제 service_id와 허용된 매개변수를 확인하세요. available: false인 서비스는 일시적으로 이용할 수 없습니다.
페이지 정보는 pagination의 page, limit, total, pages로 반환됩니다. 카탈로그는 platform과 kind 필터도 지원합니다. service_id와 order_id는 서로 다른 객체를 가리키므로 응답의 전체 식별자를 사용하세요.
상품
모든 플랫폼의 팔로워, 좋아요, 조회수 등 상품입니다. 주문량은 quantity로 지정하고 parameters.quantity의 minimum, maximum, step을 준수하세요. 구매하면 product:<id> 주문이 반환됩니다.
Twitch, Kick, YouTube, VK Live용 고정 시청자 패키지입니다. 시청자 수는 요금제의 viewers에 정해져 있으며 채널과 duration을 선택합니다. 중지된 subscription:<id> 구독이 생성되고 API와 관리 화면에서 시작, 일시정지 등을 할 수 있습니다.
카탈로그 필터
GET /services?family=plan
매개변수
설명
target
선택한 플랫폼의 채널입니다. YouTube는 채널 링크 또는 @핸들을 사용하세요. 방송 링크는 소유자의 채널로 변환됩니다.
구매 후 자동으로 시작되는 YouTube 라이브 시청자 서비스입니다. product:<id> 주문을 반환합니다. v2에는 구독 관리 패널, 일시정지, 채널 변경, 시청자 수 조정 기능이 없습니다.
카탈로그 필터
GET /services?family=youtube_v2
매개변수
설명
target
YouTube 라이브 방송 URL입니다.
quantity
시청자 수입니다. 제한은 parameters.quantity에 있습니다.
duration_minutes
구매 매개변수가 아닌 카탈로그 항목입니다. 시청자 서비스 기간은 예를 들어 60분처럼 서비스별로 정해져 있습니다. 다른 기간은 다른 service_id를 선택하세요. 더 많은 시청자 수를 지원하며 정확한 상한은 parameters.quantity.maximum에 있습니다.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Get, "https://streamkit.su/api/v1/account");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Get, "https://streamkit.su/api/v1/services?family=youtube_v2&platform=youtube&page=1&limit=25");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Get, "https://streamkit.su/api/v1/services/plan:12");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/quotes");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"service_id\":\"plan:12\",\"parameters\":{\"target\":\"your_channel\",\"duration\":\"8h\"}}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"quote_id\":\"cebe71b9-c8cb-4dfb-8315-c56ad787c640\"}", Encoding.UTF8, "application/json");
request.Headers.Add("Idempotency-Key", "my-order-0001");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Get, "https://streamkit.su/api/v1/orders?page=1&limit=25");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Get, "https://streamkit.su/api/v1/orders/subscription:123");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders/subscription:123/actions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"action\":\"start\",\"viewers\":50}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
actions에는 지원되는 작업이 나열됩니다. 구독은 start, pause, stop, viewers, channel을 지원합니다. viewers는 1 이상 purchased_viewers 이하여야 합니다. 채널 변경에는 횟수와 대기 시간 제한이 있습니다. AI 주문은 ready 상태에서 start를 실행할 수 있습니다.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders/subscription:123/actions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"action\":\"start\",\"viewers\":50}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders/subscription:123/actions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"action\":\"pause\"}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders/subscription:123/actions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"action\":\"stop\"}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders/subscription:123/actions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"action\":\"viewers\",\"viewers\":25}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://streamkit.su/api/v1/orders/subscription:123/actions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"action\":\"channel\",\"target\":\"new_channel\"}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(responseBody);
전체 구매 예제입니다. 결제 전에 quote_id와 Idempotency-Key를 저장하고 네트워크 오류 후에도 같은 값을 사용하세요.
# 1. Read the catalog and choose a real service_id
curl "https://streamkit.su/api/v1/services?limit=25" \
-H "Authorization: Bearer $STREAMKIT_API_KEY"
# 2. Request a quote using that service's parameters
curl -X POST "https://streamkit.su/api/v1/quotes" \
-H "Authorization: Bearer $STREAMKIT_API_KEY" \
-H "Content-Type: application/json" \
-d '{"service_id":"product:123","parameters":{"target":"https://t.me/your_channel","quantity":100}}'
# 3. Replace QUOTE_ID with the quote_id returned above
curl -X POST "https://streamkit.su/api/v1/orders" \
-H "Authorization: Bearer $STREAMKIT_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: my-order-0001" \
-d '{"quote_id":"QUOTE_ID"}'
require 'net/http'
require 'json'
require 'securerandom'
BASE = "https://streamkit.su/api/v1"
API_KEY = ENV.fetch('STREAMKIT_API_KEY')
def call(path, method = 'GET', body = nil, idempotency_key = nil)
uri = URI(BASE + path)
request = (method == 'GET' ? Net::HTTP::Get : Net::HTTP::Post).new(uri)
request['Authorization'] = "Bearer #{API_KEY}"
if body
request['Content-Type'] = 'application/json'
request.body = JSON.generate(body)
end
request['Idempotency-Key'] = idempotency_key if idempotency_key
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = uri.scheme == 'https'
http.open_timeout = 10
http.read_timeout = http.write_timeout = 60
http.max_retries = 0
response = http.request(request)
response.value
JSON.parse(response.body)
end
puts JSON.pretty_generate(call('/services?family=product&limit=25'))
# Choose a real service_id and parameters from your catalog.
quote = call('/quotes', 'POST', JSON.parse('{"service_id":"product:123","parameters":{"target":"https://t.me/your_channel","quantity":100}}'))
purchase = { 'quote_id' => quote.fetch('data').fetch('quote_id'), 'idempotency_key' => SecureRandom.uuid }
# Persist BEFORE payment; refuse to overwrite an unresolved purchase.
File.open('streamkit-purchase.json', File::WRONLY | File::CREAT | File::EXCL, 0600) do |file|
file.write(JSON.generate(purchase))
end
puts JSON.pretty_generate(call('/orders', 'POST', { 'quote_id' => purchase.fetch('quote_id') }, purchase.fetch('idempotency_key')))
# On timeout, read the saved file and retry ONLY /orders with the same pair.
import json, os, uuid, requests
from pathlib import Path
base = "https://streamkit.su/api/v1"
headers = {"Authorization": "Bearer " + os.environ["STREAMKIT_API_KEY"]}
catalog = requests.get(base + "/services", headers=headers, timeout=30)
catalog.raise_for_status()
print(catalog.json())
# Select a real service_id from the catalog, then quote it.
quote = requests.post(base + "/quotes", headers=headers, json={
"service_id": "product:123",
"parameters": {"target": "https://t.me/your_channel", "quantity": 100}
}, timeout=30)
quote.raise_for_status()
# Save BOTH values before sending. Reuse them after any network timeout.
quote_id = quote.json()["data"]["quote_id"]
idempotency_key = str(uuid.uuid4())
# Persist BEFORE payment; refuse to overwrite an unresolved purchase.
with Path("streamkit-purchase.json").open("x", encoding="utf-8") as saved:
json.dump({"quote_id": quote_id, "idempotency_key": idempotency_key}, saved)
order = requests.post(base + "/orders",
headers={**headers, "Idempotency-Key": idempotency_key},
json={"quote_id": quote_id}, timeout=60)
order.raise_for_status()
print(order.json())
# On timeout, read the saved file and retry ONLY /orders with the same pair.
<?php
$base = "https://streamkit.su/api/v1";
$apiKey = getenv('STREAMKIT_API_KEY');
if (!$apiKey) throw new RuntimeException('Set STREAMKIT_API_KEY on the server');
function callApi(string $path, string $method = 'GET', ?array $body = null, ?string $idempotencyKey = null): array {
global $base, $apiKey;
$headers = ['Authorization: Bearer ' . $apiKey];
if ($body !== null) $headers[] = 'Content-Type: application/json';
if ($idempotencyKey !== null) $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
$client = curl_init($base . $path);
$options = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 60];
if ($body !== null) $options[CURLOPT_POSTFIELDS] = json_encode($body, JSON_THROW_ON_ERROR);
curl_setopt_array($client, $options);
$response = curl_exec($client);
if ($response === false) throw new RuntimeException(curl_error($client));
$status = curl_getinfo($client, CURLINFO_RESPONSE_CODE);
if ($status < 200 || $status >= 300) throw new RuntimeException("HTTP $status: $response");
return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
}
print_r(callApi('/services?family=product&limit=25'));
// Choose a real service_id and parameters from your catalog.
$quote = callApi('/quotes', 'POST', json_decode('{"service_id":"product:123","parameters":{"target":"https://t.me/your_channel","quantity":100}}', true, 512, JSON_THROW_ON_ERROR));
$purchase = ['quote_id' => $quote['data']['quote_id'], 'idempotency_key' => bin2hex(random_bytes(16))];
// Persist BEFORE payment; refuse to overwrite an unresolved purchase.
$saved = json_encode($purchase, JSON_THROW_ON_ERROR);
$file = fopen('streamkit-purchase.json', 'x');
if ($file === false) throw new RuntimeException('Check the saved purchase before continuing');
if (fwrite($file, $saved) !== strlen($saved)) throw new RuntimeException('Could not save purchase');
if (!fclose($file)) throw new RuntimeException('Could not close purchase file');
print_r(callApi('/orders', 'POST', ['quote_id' => $purchase['quote_id']], $purchase['idempotency_key']));
// On timeout, read the saved file and retry ONLY /orders with the same pair.
// Java 11+. Add com.fasterxml.jackson.core:jackson-databind (2.x) to your project.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.*;
import java.nio.file.*;
import java.time.Duration;
import java.util.*;
public class StreamKitExample {
private static final String BASE = "https://streamkit.su/api/v1";
private static final String API_KEY = System.getenv("STREAMKIT_API_KEY");
private static final ObjectMapper JSON = new ObjectMapper();
private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private static String call(String path, String method, Object body, String idempotencyKey) throws Exception {
if (API_KEY == null || API_KEY.isBlank()) throw new IllegalStateException("Set STREAMKIT_API_KEY");
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(BASE + path))
.timeout(Duration.ofSeconds(60)).header("Authorization", "Bearer " + API_KEY);
if (body != null) request.header("Content-Type", "application/json");
if (idempotencyKey != null) request.header("Idempotency-Key", idempotencyKey);
request.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)));
HttpResponse<String> response = CLIENT.send(request.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300)
throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body());
return response.body();
}
public static void main(String[] args) throws Exception {
System.out.println(call("/services?family=product&limit=25", "GET", null, null));
// Choose a real service_id and parameters from your catalog.
String quote = call("/quotes", "POST", JSON.readTree("{\"service_id\":\"product:123\",\"parameters\":{\"target\":\"https://t.me/your_channel\",\"quantity\":100}}"), null);
String quoteId = JSON.readTree(quote).path("data").path("quote_id").asText();
if (quoteId.isBlank()) throw new IllegalStateException("Missing quote_id");
String idempotencyKey = UUID.randomUUID().toString();
Map<String, String> purchase = Map.of("quote_id", quoteId, "idempotency_key", idempotencyKey);
// Persist BEFORE payment; refuse to overwrite an unresolved purchase.
Files.writeString(Path.of("streamkit-purchase.json"), JSON.writeValueAsString(purchase), StandardOpenOption.CREATE_NEW);
System.out.println(call("/orders", "POST", Map.of("quote_id", quoteId), idempotencyKey));
// On timeout, read the saved file and retry ONLY /orders with the same pair.
}
}
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
const base = "https://streamkit.su/api/v1";
const apiKey = process.env.STREAMKIT_API_KEY;
if (!apiKey) throw new Error("Set STREAMKIT_API_KEY on the server");
async function call(path, method = "GET", body, idempotencyKey) {
const headers = { Authorization: `Bearer ${apiKey}` };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const response = await fetch(base + path, {
method, headers, redirect: "error",
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(60_000),
});
const result = await response.json();
if (!response.ok) throw new Error(result.error?.message ?? `HTTP ${response.status}`);
return result;
}
console.log(await call("/services?family=product&limit=25"));
// Choose a real service_id and parameters from your catalog.
const quote = await call("/quotes", "POST", {"service_id":"product:123","parameters":{"target":"https://t.me/your_channel","quantity":100}});
const purchase = { quote_id: quote.data.quote_id, idempotency_key: randomUUID() };
// Persist BEFORE payment; do not overwrite an unresolved purchase.
await writeFile("streamkit-purchase.json", JSON.stringify(purchase), { flag: "wx", mode: 0o600 });
console.log(await call("/orders", "POST", { quote_id: purchase.quote_id }, purchase.idempotency_key));
// On timeout, read the saved file and retry ONLY /orders with the same pair.
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const base = "https://streamkit.su/api/v1"
func call(path, method string, body any, idempotencyKey string) (map[string]any, error) {
apiKey := os.Getenv("STREAMKIT_API_KEY")
if apiKey == "" { return nil, fmt.Errorf("set STREAMKIT_API_KEY") }
var payload []byte
var err error
if body != nil {
payload, err = json.Marshal(body)
if err != nil { return nil, err }
}
request, err := http.NewRequest(method, base + path, bytes.NewReader(payload))
if err != nil { return nil, err }
request.Header.Set("Authorization", "Bearer " + apiKey)
if body != nil { request.Header.Set("Content-Type", "application/json") }
if idempotencyKey != "" { request.Header.Set("Idempotency-Key", idempotencyKey) }
client := &http.Client{Timeout: 60 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
response, err := client.Do(request)
if err != nil { return nil, err }
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
if err != nil { return nil, err }
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, fmt.Errorf("HTTP %d: %s", response.StatusCode, data)
}
var result map[string]any
err = json.Unmarshal(data, &result)
return result, err
}
func main() {
catalog, err := call("/services?family=product&limit=25", "GET", nil, "")
if err != nil { panic(err) }
fmt.Println(catalog)
// Choose a real service_id and parameters from your catalog.
var parameters map[string]any
if err := json.Unmarshal([]byte("{\"service_id\":\"product:123\",\"parameters\":{\"target\":\"https://t.me/your_channel\",\"quantity\":100}}"), ¶meters); err != nil { panic(err) }
quote, err := call("/quotes", "POST", parameters, "")
if err != nil { panic(err) }
quoteID := quote["data"].(map[string]any)["quote_id"].(string)
random := make([]byte, 16)
if _, err := rand.Read(random); err != nil { panic(err) }
key := hex.EncodeToString(random)
purchase, err := json.Marshal(map[string]string{"quote_id": quoteID, "idempotency_key": key})
if err != nil { panic(err) }
// Persist BEFORE payment; refuse to overwrite an unresolved purchase.
file, err := os.OpenFile("streamkit-purchase.json", os.O_WRONLY | os.O_CREATE | os.O_EXCL, 0600)
if err != nil { panic(err) }
if _, err := file.Write(purchase); err != nil { file.Close(); panic(err) }
if err := file.Close(); err != nil { panic(err) }
order, err := call("/orders", "POST", map[string]string{"quote_id": quoteID}, key)
if err != nil { panic(err) }
fmt.Println(order)
// On timeout, read the saved file and retry ONLY /orders with the same pair.
}
#nullable enable
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
var apiKey = Environment.GetEnvironmentVariable("STREAMKIT_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Set STREAMKIT_API_KEY");
var baseUrl = "https://streamkit.su/api/v1";
using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromSeconds(60) };
async Task<string> CallAsync(string path, HttpMethod method, object? body = null, string? idempotencyKey = null) {
using var request = new HttpRequestMessage(method, baseUrl + path);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
if (body is not null) request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
return responseBody;
}
Console.WriteLine(await CallAsync("/services?family=product&limit=25", HttpMethod.Get));
// Choose a real service_id and parameters from your catalog.
using var parameters = JsonDocument.Parse("{\"service_id\":\"product:123\",\"parameters\":{\"target\":\"https://t.me/your_channel\",\"quantity\":100}}");
using var quote = JsonDocument.Parse(await CallAsync("/quotes", HttpMethod.Post, parameters.RootElement));
var quoteId = quote.RootElement.GetProperty("data").GetProperty("quote_id").GetString()
?? throw new InvalidOperationException("Missing quote_id");
var idempotencyKey = Guid.NewGuid().ToString();
var purchase = new { quote_id = quoteId, idempotency_key = idempotencyKey };
// Persist BEFORE payment; refuse to overwrite an unresolved purchase.
using (var file = new FileStream("streamkit-purchase.json", FileMode.CreateNew, FileAccess.Write, FileShare.None)) {
await JsonSerializer.SerializeAsync(file, purchase);
}
Console.WriteLine(await CallAsync("/orders", HttpMethod.Post, new { quote_id = quoteId }, idempotencyKey));
// On timeout, read the saved file and retry ONLY /orders with the same pair.
요청 재시도
네트워크 오류 후에는 동일한 quote_id와 Idempotency-Key로 재시도하세요. 추가 결제 없이 같은 주문과 현재 상태를 받습니다. 이미 사용한 키로 다른 quote_id를 전송하면 409가 반환됩니다. 각 견적은 한 번만 결제할 수 있습니다.