Consultez le catalogue, calculez les prix et gérez les commandes depuis vos applications. Les mêmes services, prix et solde que dans votre compte.
Authentification
Ouvrez les paramètres du compte. Dans « Clé API », cliquez sur « Créer une clé » et enregistrez-la.
La clé complète n’est affichée qu’une fois. Son renouvellement invalide immédiatement l’ancienne. Transmettez-la dans l’en-tête Authorization: Bearer, jamais dans l’URL.
Authorization: Bearer YOUR_API_KEY
URL de base
https://streamkit.su/api/v1
Achat de services
Récupérez service_id dans le catalogue et demandez un devis. Pour acheter, envoyez quote_id avec un Idempotency-Key unique. Consultez ensuite l’état avec order_id. Le devis est gratuit et valable 5 minutes.
La devise API se choisit dans les paramètres : RUB, USD ou EUR. Le solde, le catalogue et les nouveaux devis utilisent currency. Un devis fixe la devise et exchange_rate pendant 5 minutes ; modifier les paramètres ou le taux ne change ni un quote_id existant ni le prix d’une commande payée.
Les montants sont des chaînes avec jusqu’à 8 décimales ; unit_price en accepte 18 pour préserver les petits montants. exchange_rate indique les RUB par unité de devise, et rate_date la date du taux. Le débit initial figure dans price_rub, le solde de base dans balance_rub. Les exemples utilisent RUB.
Les forfaits et configurateurs créent des abonnements arrêtés ; lancez-les avec start. Les spectateurs YouTube v2 démarrent après l’achat. Les états pending, submitting et unknown ne signifient pas un refus : vérifiez la même commande sans en créer une autre.
Variables des exemples
Paramètre
Description
STREAMKIT_API_KEY
Votre clé API complète dans une variable d’environnement.
service_id
Identifiant du catalogue, par exemple plan:12 ou smm:45.
quote_id
UUID du devis renvoyé par POST /quotes.
order_id
Le id complet de la réponse d’achat, par exemple subscription:123.
target
Chaîne, vidéo ou profil recevant le service.
Idempotency-Key
Votre clé d’achat unique. Conservez sa valeur initiale pour les nouvelles tentatives.
Les identifiants, prix et réponses sont donnés à titre d’exemple. Utilisez les valeurs de votre catalogue, devis et commande.
Services
Produits, forfaits, configurateurs, spectateurs YouTube v2 et chatbots IA partagent les méthodes de devis et d’achat. Filtrez avec family. Obtenez les service_id et paramètres autorisés via GET /services. Les services avec available: false sont temporairement indisponibles.
La pagination est renvoyée dans pagination : page, limit, total, pages. Le catalogue accepte aussi platform et kind. service_id et order_id désignent des objets différents : utilisez les identifiants complets des réponses.
Produits
Abonnés, mentions J’aime, vues et autres produits sur toutes les plateformes. Indiquez le volume dans quantity et respectez minimum, maximum et step de parameters.quantity. L’achat renvoie une commande product:<id>.
Filtre du catalogue
GET /services?family=product
Paramètre
Description
target
Identifiant ou URL de la chaîne, du profil, de la publication ou de la vidéo de la plateforme choisie.
quantity
Nombre entier d’unités respectant le pas du service.
Forfaits de spectateurs pour Twitch, Kick, YouTube et VK Live. Le nombre est défini par viewers ; choisissez la chaîne et duration. Un abonnement subscription:<id> arrêté est créé. Démarrage, pause et autres actions sont accessibles via l’API et le tableau de bord.
Filtre du catalogue
GET /services?family=plan
Paramètre
Description
target
Chaîne de la plateforme choisie ; pour YouTube, utilisez son lien ou @handle. Le lien d'un direct est converti vers la chaîne de son propriétaire.
Choisissez le nombre de spectateurs et la durée pour Twitch, Kick, YouTube et VK Live. Le prix dépend des paramètres. Comme un forfait, cela crée un abonnement subscription:<id> avec commandes dans le tableau de bord. Lancez start après l’achat.
Filtre du catalogue
GET /services?family=configurator
Paramètre
Description
target
Chaîne de la plateforme choisie. Pour YouTube, utilisez youtube.com/@handle ou youtube.com/channel/UC….
viewers
Nombre entier de spectateurs entre parameters.viewers.minimum et maximum.
Spectateurs pour les directs YouTube, lancés automatiquement après l’achat. Une commande product:<id> est renvoyée. v2 ne propose ni panneau d’abonnement, ni pause, ni changement de chaîne ou du nombre de spectateurs.
Filtre du catalogue
GET /services?family=youtube_v2
Paramètre
Description
target
URL du direct YouTube.
quantity
Nombre de spectateurs. Les limites figurent dans parameters.quantity.
duration_minutes
Champ du catalogue, pas un paramètre d’achat. La durée est fixée par le service, par exemple 60 minutes. Choisissez un autre service_id pour une autre durée. De grands volumes sont possibles ; la limite exacte est parameters.quantity.maximum.
Chatbots IA pour Twitch, Kick, VK Live et YouTube. Pour Twitch, Kick et VK Live, envoyez bots, hours et variant ; pour YouTube, messages, speed et language. Choisissez les valeurs dans offers. Tous les achats renvoient chatbot:<id>.
Filtre du catalogue
GET /services?family=ai_chatbots
Twitch / Kick / VK Live
Paramètre
Description
target
Chaîne du direct.
bots
Nombre de bots d’une offre disponible dans offers.
YouTube est facturé selon messages, et non selon le nombre de bots ou les heures. Choisissez la vitesse avec speed_min et speed_max dans offers, par exemple 2-5.
Paramètre
Description
target
URL du direct ou de la première YouTube.
messages
Nombre entier de messages dans les limites de l’offre.
speed
Vitesse de offers, par exemple 2-5 messages par minute.
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);
Le champ actions liste les opérations disponibles. Les abonnements acceptent start, pause, stop, viewers et channel. viewers doit être compris entre 1 et purchased_viewers. Les changements de chaîne dépendent du quota et du délai. Une commande IA accepte start à l’état ready.
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);
Exemple complet d’achat. Enregistrez quote_id et Idempotency-Key avant le paiement et réutilisez-les après une erreur réseau.
# 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.
Nouvelles tentatives
Après une erreur réseau, renvoyez le même quote_id avec le même Idempotency-Key. Vous recevrez la même commande et son état actuel sans nouveau débit. Réutiliser la clé avec un autre quote_id renvoie 409. Chaque devis ne peut être payé qu’une fois.
600 requêtes GET et 120 POST par minute et par clé. limit : de 1 à 100, 25 par défaut. Corps JSON : 32 Kio maximum. La réponse 429 inclut Retry-After avec le délai en secondes.