Gelen dosyayı kendi sisteminize almak
Dosya iletimini açtığınızda, müşterinin gönderdiği dosya iletim adresinize mesaj kopyasından ayrı bir istek olarak gelir; imzasını doğrular, dosyayı saklar ve mesajıyla eşleştirirsiniz.
Adımlar
-
Dosya iletimini açın Panel
API altyapısı › Gönderdiğimiz sekmesinde, İletim adresi tanımlı bağlantıda Dosyalar da iletilsin seçeneğini işaretleyin: Olaylar › İletim adresi.
-
Dosya isteği adresinize gelir VeriTakibi
Müşteri dosya gönderdiğinde iletim adresinize mesaj kopyasından ayrı bir
POSTisteği gelir. Gövde dosyanın kendisidir,Content-Typedosyanın türüdür; dosyanın bilgisiX-Vt-Media-ile başlayan başlıklardadır. Başlıklar: Olaylar › Dosya. -
İmzayı doğrulayıp dosyayı saklayın Sizin sisteminiz
Dosya isteğinde imza dosyanın baytlarını kapsar;
X-Vt-Media-başlıkları imzanın kapsamında değildir: İmzalar › İsteğin içeriği. Gövdeyi ayrıştırmadan olduğu gibi saklayın.X-Vt-Media-Filenamebaşlığını dosya yolu olarak kullanmayın; dosyayı kendi belirlediğiniz adla saklayın.Bu örnek, adresinize gelen isteği karşılayan sunucu kodudur. cURL istek gönderir, gelen isteği karşılayamaz; bu yüzden panelde cURL sekmesi yoktur.
Örnek · iki istek türünü tek adreste karşılamak
// The secret is read from an environment variable, never written into the code // save_file and save_copy are your own storage functions $secret = getenv('VERITAKIBI_SIGNING_SECRET'); if ($secret === false || $secret === '') { // secret unset or empty: cannot verify http_response_code(500); exit; } $body = file_get_contents('php://input'); // raw body $signature = $_SERVER['HTTP_X_VT_SIGNATURE'] ?? ''; if (!hash_equals('sha256=' . hash_hmac('sha256', $body, $secret), $signature)) { http_response_code(401); exit; } $messageId = $_SERVER['HTTP_X_VT_MEDIA_MESSAGE_ID'] ?? ''; if ($messageId !== '') { // File request: the body is the file itself save_file($messageId, $_SERVER['CONTENT_TYPE'] ?? '', $body); } else { // Message copy: the body is JSON $message = json_decode($body, true); save_copy($message['message_id'], $message); } http_response_code(200);
// Node 18+: no npm packages needed; save as .mjs (import syntax) // The secret is read from an environment variable, never written into the code // saveFile and saveCopy are your own storage functions import { createServer } from 'node:http'; import { createHmac, timingSafeEqual } from 'node:crypto'; const secret = process.env.VERITAKIBI_SIGNING_SECRET; if (!secret) throw new Error('VERITAKIBI_SIGNING_SECRET is unset or empty'); function isValidSignature(body, signature) { const expected = Buffer.from('sha256=' + createHmac('sha256', secret).update(body).digest('hex')); const received = Buffer.from(signature ?? ''); return received.length === expected.length && timingSafeEqual(received, expected); } createServer((req, res) => { const chunks = []; req.on('data', (p) => chunks.push(p)); req.on('end', async () => { const body = Buffer.concat(chunks); // raw body if (!isValidSignature(body, req.headers['x-vt-signature'])) { res.writeHead(401).end(); return; } try { const messageId = req.headers['x-vt-media-message-id']; if (messageId) { // File request: the body is the file itself await saveFile(messageId, req.headers['content-type'], body); } else { // Message copy: the body is JSON const message = JSON.parse(body); await saveCopy(message.message_id, message); } res.writeHead(200).end(); } catch { res.writeHead(500).end(); } }); }).listen(3000);
# Python 3.6+: standard library only (hmac, hashlib, json) # The secret is read from an environment variable, never written into the code # save_file and save_copy are your own storage functions import hashlib, hmac, json, os SECRET = os.environ.get('VERITAKIBI_SIGNING_SECRET', '').encode() if not SECRET: raise RuntimeError('VERITAKIBI_SIGNING_SECRET is unset or empty') def handle(body: bytes, headers) -> int: # body: raw request bytes; headers: case-insensitive header mapping expected = 'sha256=' + hmac.new(SECRET, body, hashlib.sha256).hexdigest() if not hmac.compare_digest(expected.encode(), (headers.get('X-Vt-Signature') or '').encode()): return 401 message_id = headers.get('X-Vt-Media-Message-Id') if message_id: # File request: the body is the file itself save_file(message_id, headers.get('Content-Type'), body) else: # Message copy: the body is JSON message = json.loads(body) save_copy(message['message_id'], message) return 200
// Go 1.18+: standard library only // The secret is read from an environment variable, never written into the code // saveFile and saveCopy are your own storage functions package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "io" "net/http" "os" ) var secret = []byte(os.Getenv("VERITAKIBI_SIGNING_SECRET")) func isValidSignature(body []byte, signature string) bool { m := hmac.New(sha256.New, secret) m.Write(body) expected := "sha256=" + hex.EncodeToString(m.Sum(nil)) return hmac.Equal([]byte(expected), []byte(signature)) } func main() { if len(secret) == 0 { panic("VERITAKIBI_SIGNING_SECRET is unset or empty") } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) // raw body if err != nil || !isValidSignature(body, r.Header.Get("X-Vt-Signature")) { w.WriteHeader(http.StatusUnauthorized) return } if messageID := r.Header.Get("X-Vt-Media-Message-Id"); messageID != "" { // File request: the body is the file itself err = saveFile(messageID, r.Header.Get("Content-Type"), body) } else { // Message copy: the body is JSON var message struct { MessageID int64 `json:"message_id"` } if err = json.Unmarshal(body, &message); err == nil { err = saveCopy(message.MessageID, body) } } if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }) http.ListenAndServe(":3000", nil) }
// Java 11+: built-in javax.crypto for the signature; file name Example.java // Requires Jackson for JSON parsing (com.fasterxml.jackson.core:jackson-databind) // The secret is read from an environment variable, never written into the code // saveFile and saveCopy are your own storage functions import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class Example { // body: raw request bytes; signature, messageId, contentType: values of the X-Vt-Signature, // X-Vt-Media-Message-Id and Content-Type headers (null if absent) static int handle(byte[] body, String signature, String messageId, String contentType) throws Exception { String secretText = System.getenv("VERITAKIBI_SIGNING_SECRET"); if (secretText == null || secretText.isEmpty()) { return 500; // secret unset or empty: cannot verify } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secretText.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); StringBuilder hex = new StringBuilder("sha256="); for (byte b : mac.doFinal(body)) { hex.append(String.format("%02x", b)); } byte[] expected = hex.toString().getBytes(StandardCharsets.UTF_8); byte[] received = (signature == null ? "" : signature).getBytes(StandardCharsets.UTF_8); if (!MessageDigest.isEqual(expected, received)) { // constant time return 401; } if (messageId != null && !messageId.isEmpty()) { // File request: the body is the file itself saveFile(messageId, contentType, body); } else { // Message copy: the body is JSON JsonNode message = new ObjectMapper().readTree(body); saveCopy(message.get("message_id").asLong(), message); } return 200; } }
// .NET 6+: standard library only // The secret is read from an environment variable, never written into the code // SaveFile and SaveCopy are your own storage functions using System.Security.Cryptography; using System.Text; using System.Text.Json; // body: raw request bytes; signature, messageId, contentType: values of the X-Vt-Signature, // X-Vt-Media-Message-Id and Content-Type headers (null if absent) static int Handle(byte[] body, string? signature, string? messageId, string? contentType) { var secretText = Environment.GetEnvironmentVariable("VERITAKIBI_SIGNING_SECRET"); if (string.IsNullOrEmpty(secretText)) return 500; // secret unset or empty: cannot verify var digest = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secretText), body); var expected = Encoding.UTF8.GetBytes("sha256=" + Convert.ToHexString(digest).ToLowerInvariant()); var received = Encoding.UTF8.GetBytes(signature ?? ""); if (!CryptographicOperations.FixedTimeEquals(expected, received)) return 401; if (!string.IsNullOrEmpty(messageId)) { // File request: the body is the file itself SaveFile(messageId, contentType, body); } else { // Message copy: the body is JSON using var message = JsonDocument.Parse(body); SaveCopy(message.RootElement.GetProperty("message_id").GetInt64(), message.RootElement); } return 200; }
// C++11+: requires OpenSSL and nlohmann/json (link with -lcrypto) // The secret is read from an environment variable, never written into the code // saveFile and saveCopy are your own storage functions #include <openssl/evp.h> #include <openssl/hmac.h> #include <nlohmann/json.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> // Constant-time comparison: walks every byte when lengths match, never exits early static bool equal(const std::string& a, const std::string& b) { if (a.size() != b.size()) return false; unsigned char diff = 0; for (size_t i = 0; i < a.size(); ++i) { diff |= static_cast<unsigned char>(a[i] ^ b[i]); } return diff == 0; } // body: raw request bytes; signature, messageId, contentType: values of the X-Vt-Signature, // X-Vt-Media-Message-Id and Content-Type headers (empty if absent) int handle(const std::string& body, const std::string& signature, const std::string& messageId, const std::string& contentType) { const char* secret = std::getenv("VERITAKIBI_SIGNING_SECRET"); if (!secret || !*secret) return 500; // secret unset or empty: cannot verify unsigned char digest[EVP_MAX_MD_SIZE]; unsigned int len = 0; HMAC(EVP_sha256(), secret, static_cast<int>(std::strlen(secret)), reinterpret_cast<const unsigned char*>(body.data()), body.size(), digest, &len); std::string expected = "sha256="; char hexByte[3]; for (unsigned int i = 0; i < len; ++i) { std::snprintf(hexByte, sizeof hexByte, "%02x", digest[i]); expected += hexByte; } if (!equal(expected, signature)) return 401; if (!messageId.empty()) { // File request: the body is the file itself saveFile(messageId, contentType, body); } else { // Message copy: the body is JSON nlohmann::json message = nlohmann::json::parse(body); saveCopy(message["message_id"].get<long long>(), message); } return 200; }
-
Dosyayı mesajıyla eşleştirin Sizin sisteminiz
X-Vt-Media-Message-Idbaşlığı, dosyanın ait olduğu mesajın kopyasındakimessage_idile aynıdır. Dosya isteği mesaj kopyasından önce de gelebilir; ikisini bu değerle eşleştirin. Aynı istek birden çok kez gelebileceği için tekilleştirmeyi de bu değerle yapın: Olaylar › Yanıtınız.
Sürüm öneki, sayfalama, zaman biçimi ve hata gövdesi: Sürümleme, sayfalama, limitler →