wpkrypt

Dokümantasyon

İlk metin mesajınızı gönderin, anahtar izinlerini seçin ve webhook olaylarını güvenle doğrulayın.

OpenAPI belgesini aç

İlk mesajı gönderin

Panelde numaranızı bağlayın, e-postanızı doğrulayın ve aktif bir paket kullanın. Örnekleri sunucu tarafında çalıştırın. Panele git

WPKRYPT_API_URL
API’nin kök adresi. Sonuna /api/v1 eklemeyin. Canlı ortamda HTTPS kullanın.
WPKRYPT_API_KEY
Panelden oluşturduğunuz, mesaj gönderme izinli anahtar. Sunucuda saklayın.
WPKRYPT_TO
Kendi test numaranız. Ülke kodunu ekleyin.

PHP

<?php

$apiUrl = rtrim((string) getenv('WPKRYPT_API_URL'), '/');
$apiKey = (string) getenv('WPKRYPT_API_KEY');
$to = (string) getenv('WPKRYPT_TO');
if ($apiUrl === '' || $apiKey === '' || $to === '') {
    throw new RuntimeException('Set WPKRYPT_API_URL, WPKRYPT_API_KEY and WPKRYPT_TO.');
}

$request = curl_init($apiUrl.'/api/v1/messages');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer '.$apiKey,
        'Accept: application/json',
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode(['to' => $to, 'text' => 'Merhaba'], JSON_THROW_ON_ERROR),
]);

$body = curl_exec($request);
if ($body === false) {
    throw new RuntimeException('Request outcome unknown; check message history before retrying.');
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$result = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
if ($status !== 202) {
    throw new RuntimeException('API error: '.($result['code'] ?? $status));
}
echo $result['data']['id'], PHP_EOL;

Node.js

const { WPKRYPT_API_URL: base, WPKRYPT_API_KEY: key, WPKRYPT_TO: to } = process.env;
if (!base || !key || !to) throw new Error('Set the wpkrypt environment variables.');

const response = await fetch(new URL('/api/v1/messages', base), {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${key}`,
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ to, text: 'Merhaba' }),
  redirect: 'error',
  signal: AbortSignal.timeout(10_000),
});
const result = await response.json();
if (response.status !== 202) throw new Error(`API error: ${result.code ?? response.status}`);
console.log(result.data.id);

Python

import json
import os
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, Request, build_opener

base = os.environ["WPKRYPT_API_URL"].rstrip("/")
request = Request(
    base + "/api/v1/messages",
    data=json.dumps({"to": os.environ["WPKRYPT_TO"], "text": "Merhaba"}).encode(),
    headers={
        "Authorization": "Bearer " + os.environ["WPKRYPT_API_KEY"],
        "Accept": "application/json",
        "Content-Type": "application/json",
    },
    method="POST",
)

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


try:
    with build_opener(NoRedirect()).open(request, timeout=10) as response:
        if response.status != 202:
            raise RuntimeError(f"Unexpected status: {response.status}")
        print(json.load(response)["data"]["id"])
except HTTPError as error:
    result = json.load(error)
    raise RuntimeError(f"API error: {result.get('code', error.code)}") from None

HTTP 202, mesajın kuyruğa alındığını gösterir. Yanıttaki kimlikle mesaj durumunu sorgulayabilir veya webhook olaylarını izleyebilirsiniz. GET /api/v1/messages/{id}

402 kredi yetersizliğini, 403 izin, e-posta doğrulaması veya paket sorununu, 422 ise doğrulama hatasını gösterebilir. Zaman aşımından sonra aynı isteği tekrar göndermeden önce mesaj geçmişine bakın.

API anahtarı izinleri

Kampanya izinleri anahtar oluştururken toplu gönderim seçeneğiyle verilir. Webhook ve API anahtarı yönetimi panel oturumu gerektirir.

İzinİşlem
messages:sendTekli mesaj gönderme veya zamanlama
messages:readMesajları listeleme ve durum sorgulama
campaigns:writeKampanya önizleme, oluşturma ve iptal
campaigns:readKampanyaları listeleme ve durum sorgulama

Webhook imzasını doğrulayın

Panelde bir webhook adresi oluşturun ve imza anahtarını alıcı sunucuda WPKRYPT_WEBHOOK_SECRET olarak saklayın. Anahtar yalnızca oluşturma veya yenileme yanıtında gösterilir.

X-Wpkrypt-Timestamp değerini, bir noktayı ve ham istek gövdesini birleştirin. Bu baytlar üzerinden HMAC-SHA256 hesaplayın, sha256= önekini ekleyin ve X-Wpkrypt-Signature ile sabit süreli karşılaştırın. İmzayı JSON’u ayrıştırmadan önce doğrulayın.

PHP ile webhook doğrulama

<?php

$rawBody = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_WPKRYPT_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_WPKRYPT_SIGNATURE'] ?? '';
$secret = (string) getenv('WPKRYPT_WEBHOOK_SECRET');

if ($secret === '') {
    http_response_code(500);
    exit;
}

$expected = 'sha256='.hash_hmac('sha256', $timestamp.'.'.$rawBody, $secret);
if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300
    || !hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}

try {
    $event = json_decode($rawBody, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
    http_response_code(400);
    exit;
}

// Persist or process $event idempotently before acknowledging.
http_response_code(204);

Örnek, 5 dakikadan eski veya ileri zaman damgalarını reddeder. Teslimatlar yeniden denenebildiği için aynı olayın tekrar gelmesini hesaba katın. Olayı işledikten veya kalıcı olarak kaydettikten sonra 2xx dönün. Paneldeki webhook.test ile alıcıyı deneyebilirsiniz.

API sözleşmesi

Mesaj, kampanya ve webhook uçlarının istek ve yanıt biçimlerini, yetkilerini ve hata kodlarını OpenAPI belgesinde bulabilirsiniz.

OpenAPI belgesini aç