API v1 · שרת 0.10.0

SibLinks API

הצעות לקישורים פנימיים מכל מערכת ניהול תוכן. שולחים עמוד ורשימה של עמודים באתר, ומקבלים את המשפטים שכדאי להפוך לקישור, את המילים לקישור, ולאן לקשר.

terminal
$ curl https://api.siblinks.co.il/v1/health
{"ok": true, "version": "0.10.0"}

איך זה עובד

השרת שלכם שולח בדיקה, שואל עליה עד שהיא מסתיימת, ומאשר שקיבל את התוצאה. כל בקשה חתומה, וכל תשובה חתומה בחזרה.

השרת שלכם SibLinks API POST /v1/jobs 202 · job_id כל 3 שניות, עד done GET /v1/jobs/{job_id} status: processing status: done · suggestions POST /v1/jobs/{job_id}/ack 200 · ok

בדיקה מחויבת פעם אחת, רק כשהיא מסתיימת ב־done. ראו מחזור החיים של בדיקה.

כתובת השרת

כל הנתיבים מתחילים ב־/v1, וכל הגופים הם JSON בקידוד UTF-8. השרת עשוי להוסיף שדות חדשים לתשובות, ולכן מתעלמים משדה לא מוכר.

Base URL
https://api.siblinks.co.il

מה צריך כדי להתחיל

  • Site ID ו־Secret. יוצרים "אתר" באזור הלקוחות, app.siblinks.co.il. כל אתר משתמש בבדיקות של החשבון.
  • שעון מסונכרן בשרת שלכם (NTP). בקשה עם זמן שרחוק ביותר מ־5 דקות נדחית.
  • מזהה מספרי לכל עמוד. אם המזהים אצלכם הם UUID או slug, ראו המלצות יישום.

ה־Secret נשאר בשרת שלכםהוא מוצג פעם אחת בלבד, כשיוצרים את האתר. כל הקריאות ל־API יוצאות מהשרת שלכם. ה־Secret לא נכנס לדפדפן, לאפליקציה או לקוד שהלקוח מוריד.

התחלה

התחלה מהירה

בדיקה ראשונה בארבעה צעדים: פרטי גישה, קריאה חתומה, שליחת בדיקה וקבלת ההצעות. בוחרים שפה ברשימה שבראש הקוד, וכל הדוגמאות בתיעוד עוברות אליה. מתחת לכל דוגמה מוצג הפלט שלה.

  1. מקבלים פרטי גישה

    באזור הלקוחות יוצרים אתר חדש ומעתיקים את ה־Site ID ואת ה־Secret. שומרים אותם במשתני סביבה בשרת שלכם.

    .env
    export SIBLINKS_SITE_ID="site_ab12cd34ef56"
    export SIBLINKS_SECRET="the-secret-from-the-customer-area"
  2. מוסיפים פונקציה לקריאה חתומה

    הפונקציה חותמת על כל בקשה, ובודקת את החתימה של כל תשובה. כל שאר הדוגמאות משתמשות בה. ההסבר המלא נמצא באימות וחתימות.

    Signed client
    #!/usr/bin/env bash
    # SibLinks API from the shell (bash, curl, openssl, jq).
    # Note: openssl receives the secret as an argument, so other users on the same machine can see it
    # in the process list. Use this for testing; in production use one of the language clients.
    set -euo pipefail
    BASE_URL="${SIBLINKS_BASE_URL:-https://api.siblinks.co.il}"
    
    hmac_hex() { openssl dgst -sha256 -hmac "$SIBLINKS_SECRET" -r | cut -d' ' -f1; }
    
    # siblinks_call METHOD PATH [BODY_JSON]: prints the verified response body.
    siblinks_call() {
      local method="$1" path="$2" body="${3-}"
      local ts nonce sig tmp status expected got
      ts=$(date +%s)
      nonce=$(openssl rand -hex 16)
      sig=$(printf '%s\n%s\n%s\n%s\n%s' "$ts" "$method" "$path" \
        "$(printf '%s' "$body" | openssl dgst -sha256 -r | cut -d' ' -f1)" "$nonce" | hmac_hex)
    
      tmp=$(mktemp -d)
      local args=(-sS -X "$method" "$BASE_URL$path" --compressed -D "$tmp/headers" -o "$tmp/body" -w '%{http_code}'
        -H "X-Site-Id: $SIBLINKS_SITE_ID" -H "X-Timestamp: $ts" -H "X-Nonce: $nonce" -H "X-Signature: $sig")
      if [ -n "$body" ]; then
        args+=(-H "Content-Type: application/json" --data-binary "$body")
      fi
      status=$(curl "${args[@]}")
    
      expected=$(printf 'response\n%s\n%s\n%s' "$sig" "$status" \
        "$(openssl dgst -sha256 -r < "$tmp/body" | cut -d' ' -f1)" | hmac_hex)
      got=$( (grep -i '^x-siblinks-signature:' "$tmp/headers" || true) | tail -1 | cut -d: -f2 | tr -d ' \r' | tr 'A-F' 'a-f')
      if [ "$status" -lt 400 ] && [ "$expected" != "$got" ]; then
        echo "unsigned_response" >&2; rm -rf "$tmp"; return 1 # never trust it
      fi
      if [ "$status" -ge 400 ]; then
        echo "error $status $(jq -r '.error.code // "unknown"' "$tmp/body")" >&2; rm -rf "$tmp"; return 1
      fi
      cat "$tmp/body"
      rm -rf "$tmp"
    }
    import hashlib
    import hmac
    import json
    import os
    import secrets
    import time
    
    import requests
    
    BASE_URL = os.environ.get("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
    SITE_ID = os.environ["SIBLINKS_SITE_ID"]
    SECRET = os.environ["SIBLINKS_SECRET"]
    
    
    class SibLinksError(Exception):
        def __init__(self, status, code):
            super().__init__(f"{status} {code}")
            self.status, self.code = status, code
    
    
    def _hmac(text: str) -> str:
        return hmac.new(SECRET.encode("utf-8"), text.encode("utf-8"), hashlib.sha256).hexdigest()
    
    
    def call(method: str, path: str, body=None):
        raw = b"" if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
        ts = str(int(time.time()))
        nonce = secrets.token_hex(16)
        signature = _hmac(f"{ts}\n{method}\n{path}\n{hashlib.sha256(raw).hexdigest()}\n{nonce}")
        headers = {"X-Site-Id": SITE_ID, "X-Timestamp": ts, "X-Nonce": nonce, "X-Signature": signature}
        if body is not None:
            headers["Content-Type"] = "application/json"
        r = requests.request(method, BASE_URL + path, data=raw if body is not None else None,
                             headers=headers, timeout=30)
        expected = _hmac(f"response\n{signature}\n{r.status_code}\n{hashlib.sha256(r.content).hexdigest()}")
        signed = hmac.compare_digest(expected, r.headers.get("X-SibLinks-Signature", "").lower())
        if r.status_code < 400 and not signed:
            raise SibLinksError(r.status_code, "unsigned_response")  # never trust it
        data = r.json()
        if r.status_code >= 400:
            raise SibLinksError(r.status_code, (data.get("error") or {}).get("code", "unknown"))
        return data
    // SibLinks API client example (Node.js 18+, no dependencies).
    import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
    
    const BASE_URL = process.env.SIBLINKS_BASE_URL || 'https://api.siblinks.co.il';
    const SITE_ID = process.env.SIBLINKS_SITE_ID;
    const SECRET = process.env.SIBLINKS_SECRET;
    
    const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
    const hmac = (text) => createHmac('sha256', SECRET).update(text, 'utf8').digest('hex');
    
    export async function call(method, path, body) {
      const raw = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body), 'utf8');
      const ts = String(Math.floor(Date.now() / 1000));
      const nonce = randomBytes(16).toString('hex');
      const signature = hmac(`${ts}\n${method}\n${path}\n${sha256(raw)}\n${nonce}`);
      const headers = { 'X-Site-Id': SITE_ID, 'X-Timestamp': ts, 'X-Nonce': nonce, 'X-Signature': signature };
      if (body !== undefined) headers['Content-Type'] = 'application/json';
    
      const res = await fetch(BASE_URL + path, { method, headers, body: body === undefined ? undefined : raw });
      const resBody = Buffer.from(await res.arrayBuffer());
      const expected = Buffer.from(hmac(`response\n${signature}\n${res.status}\n${sha256(resBody)}`));
      const got = Buffer.from((res.headers.get('x-siblinks-signature') || '').toLowerCase());
      const signedOk = got.length === expected.length && timingSafeEqual(got, expected);
      if (res.status < 400 && !signedOk) throw new Error('unsigned_response'); // never trust it
    
      const data = JSON.parse(resBody.toString('utf8'));
      if (res.status >= 400) throw Object.assign(new Error(data.error?.code || 'unknown'), { status: res.status });
      return data;
    }
    <?php
    // SibLinks API client example (PHP 8, curl extension).
    
    $base_url = getenv( 'SIBLINKS_BASE_URL' ) ?: 'https://api.siblinks.co.il';
    $site_id  = getenv( 'SIBLINKS_SITE_ID' );
    $secret   = getenv( 'SIBLINKS_SECRET' );
    
    function siblinks_call( string $method, string $path, ?array $body = null ): array {
    	global $base_url, $site_id, $secret;
    
    	$raw   = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE );
    	$ts    = (string) time();
    	$nonce = bin2hex( random_bytes( 16 ) );
    	$sig   = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $secret );
    
    	$headers = array( "X-Site-Id: {$site_id}", "X-Timestamp: {$ts}", "X-Nonce: {$nonce}", "X-Signature: {$sig}" );
    	if ( null !== $body ) {
    		$headers[] = 'Content-Type: application/json';
    	}
    
    	$resp_sig = '';
    	$ch       = curl_init( $base_url . $path );
    	curl_setopt_array(
    		$ch,
    		array(
    			CURLOPT_CUSTOMREQUEST  => $method,
    			CURLOPT_HTTPHEADER     => $headers,
    			CURLOPT_RETURNTRANSFER => true,
    			CURLOPT_ENCODING       => '', // decode gzip/br if a proxy compressed the response
    			CURLOPT_TIMEOUT        => 30,
    			CURLOPT_HEADERFUNCTION => function ( $ch, $line ) use ( &$resp_sig ) {
    				if ( 0 === stripos( $line, 'X-SibLinks-Signature:' ) ) {
    					$resp_sig = strtolower( trim( substr( $line, 21 ) ) );
    				}
    				return strlen( $line );
    			},
    		)
    	);
    	if ( null !== $body ) {
    		curl_setopt( $ch, CURLOPT_POSTFIELDS, $raw );
    	}
    	$resp   = curl_exec( $ch );
    	$status = (int) curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
    	if ( false === $resp ) {
    		throw new RuntimeException( 'connection_failed: ' . curl_error( $ch ) );
    	}
    
    	$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $secret );
    	if ( $status < 400 && ! hash_equals( $expected, $resp_sig ) ) {
    		throw new RuntimeException( 'unsigned_response' ); // never trust it
    	}
    	$data = json_decode( $resp, true );
    	if ( $status >= 400 ) {
    		throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
    	}
    	return $data;
    }
    <?php
    // SibLinks API client example (PHP 8.0+, Guzzle 7: composer require guzzlehttp/guzzle).
    require __DIR__ . '/vendor/autoload.php';
    
    use GuzzleHttp\Client;
    
    final class SibLinksClient {
    	private Client $http;
    
    	public function __construct( private string $site_id, private string $secret, string $base_url = 'https://api.siblinks.co.il' ) {
    		$this->http = new Client(
    			array(
    				'base_uri'    => $base_url,
    				'timeout'     => 30,
    				'http_errors' => false, // errors are read from the JSON body below
    			)
    		);
    	}
    
    	public function call( string $method, string $path, ?array $body = null ): array {
    		$raw   = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR );
    		$ts    = (string) time();
    		$nonce = bin2hex( random_bytes( 16 ) );
    		$sig   = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $this->secret );
    
    		$headers = array(
    			'X-Site-Id'   => $this->site_id,
    			'X-Timestamp' => $ts,
    			'X-Nonce'     => $nonce,
    			'X-Signature' => $sig,
    		);
    		if ( null !== $body ) {
    			$headers['Content-Type'] = 'application/json';
    		}
    
    		$res    = $this->http->request( $method, $path, array( 'headers' => $headers, 'body' => $raw ) );
    		$status = $res->getStatusCode();
    		$resp   = (string) $res->getBody();
    
    		$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $this->secret );
    		if ( $status < 400 && ! hash_equals( $expected, strtolower( $res->getHeaderLine( 'X-SibLinks-Signature' ) ) ) ) {
    			throw new RuntimeException( 'unsigned_response' ); // never trust it
    		}
    		$data = json_decode( $resp, true );
    		if ( $status >= 400 ) {
    			throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
    		}
    		return $data;
    	}
    }
    // SibLinks API client example (Java 17+, Jackson 2.x: com.fasterxml.jackson.core:jackson-databind).
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.security.SecureRandom;
    import java.time.Duration;
    import java.util.HexFormat;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;
    import java.util.Optional;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    
    public class SibLinksClient {
        static final String BASE_URL = Optional.ofNullable(System.getenv("SIBLINKS_BASE_URL")).orElse("https://api.siblinks.co.il");
        static final String SITE_ID = System.getenv("SIBLINKS_SITE_ID");
        static final String SECRET = System.getenv("SIBLINKS_SECRET");
    
        static final ObjectMapper JSON = new ObjectMapper();
        static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
        static final SecureRandom RANDOM = new SecureRandom();
        static final HexFormat HEX = HexFormat.of();
    
        static class SibLinksException extends Exception {
            final int status;
            final String code;
    
            SibLinksException(int status, String code) {
                super(status + " " + code);
                this.status = status;
                this.code = code;
            }
        }
    
        static String sha256(byte[] data) throws Exception {
            return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(data));
        }
    
        static String hmac(String message) throws Exception {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return HEX.formatHex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
        }
    
        static JsonNode call(String method, String path, Object body) throws Exception {
            byte[] raw = body == null ? new byte[0] : JSON.writeValueAsBytes(body);
            String ts = Long.toString(System.currentTimeMillis() / 1000);
            byte[] nonceBytes = new byte[16];
            RANDOM.nextBytes(nonceBytes);
            String nonce = HEX.formatHex(nonceBytes);
            String signature = hmac(ts + "\n" + method + "\n" + path + "\n" + sha256(raw) + "\n" + nonce);
    
            HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(BASE_URL + path))
                    .timeout(Duration.ofSeconds(30))
                    .header("X-Site-Id", SITE_ID)
                    .header("X-Timestamp", ts)
                    .header("X-Nonce", nonce)
                    .header("X-Signature", signature)
                    .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(raw));
            if (body != null) {
                req.header("Content-Type", "application/json");
            }
            HttpResponse<byte[]> res = HTTP.send(req.build(), HttpResponse.BodyHandlers.ofByteArray());
    
            int status = res.statusCode();
            String expected = hmac("response\n" + signature + "\n" + status + "\n" + sha256(res.body()));
            String got = res.headers().firstValue("X-SibLinks-Signature").orElse("").toLowerCase(Locale.ROOT);
            boolean signed = MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), got.getBytes(StandardCharsets.UTF_8));
            if (status < 400 && !signed) {
                throw new SibLinksException(status, "unsigned_response"); // never trust it
            }
            JsonNode data = JSON.readTree(res.body());
            if (status >= 400) {
                throw new SibLinksException(status, data.path("error").path("code").asText("unknown"));
            }
            return data;
        }
        // main() and your own code go here
    }
    // SibLinks API client example (.NET 6+, no extra packages).
    using System.Net;
    using System.Net.Http.Headers;
    using System.Security.Cryptography;
    using System.Text;
    using System.Text.Json;
    using System.Text.Json.Nodes;
    
    public class SibLinksException : Exception
    {
        public int Status { get; }
        public string Code { get; }
    
        public SibLinksException(int status, string code) : base($"{status} {code}")
        {
            Status = status;
            Code = code;
        }
    }
    
    public static class SibLinks
    {
        static readonly string BaseUrl = Environment.GetEnvironmentVariable("SIBLINKS_BASE_URL") ?? "https://api.siblinks.co.il";
        static readonly string SiteId = Environment.GetEnvironmentVariable("SIBLINKS_SITE_ID")!;
        static readonly byte[] Secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SIBLINKS_SECRET")!);
    
        static readonly HttpClient Http = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All })
        {
            Timeout = TimeSpan.FromSeconds(30),
        };
    
        static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant();
    
        static string Hmac(string message) => Hex(HMACSHA256.HashData(Secret, Encoding.UTF8.GetBytes(message)));
    
        public static async Task<JsonNode> Call(string method, string path, object? body = null)
        {
            byte[] raw = body is null ? Array.Empty<byte>() : JsonSerializer.SerializeToUtf8Bytes(body);
            string ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            string nonce = Hex(RandomNumberGenerator.GetBytes(16));
            string signature = Hmac($"{ts}\n{method}\n{path}\n{Hex(SHA256.HashData(raw))}\n{nonce}");
    
            using var req = new HttpRequestMessage(new HttpMethod(method), BaseUrl + path);
            req.Headers.Add("X-Site-Id", SiteId);
            req.Headers.Add("X-Timestamp", ts);
            req.Headers.Add("X-Nonce", nonce);
            req.Headers.Add("X-Signature", signature);
            if (body is not null)
            {
                req.Content = new ByteArrayContent(raw);
                req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
    
            using var res = await Http.SendAsync(req);
            byte[] resBody = await res.Content.ReadAsByteArrayAsync();
            int status = (int)res.StatusCode;
    
            string expected = Hmac($"response\n{signature}\n{status}\n{Hex(SHA256.HashData(resBody))}");
            string got = res.Headers.TryGetValues("X-SibLinks-Signature", out var values) ? values.First().ToLowerInvariant() : "";
            bool signed = CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(got));
            if (status < 400 && !signed)
            {
                throw new SibLinksException(status, "unsigned_response"); // never trust it
            }
            JsonNode data = JsonNode.Parse(resBody)!;
            if (status >= 400)
            {
                throw new SibLinksException(status, data["error"]?["code"]?.GetValue<string>() ?? "unknown");
            }
            return data;
        }
    }
    // SibLinks API client example (Go 1.20+, standard library only).
    package main
    
    import (
    	"bytes"
    	"crypto/hmac"
    	"crypto/rand"
    	"crypto/sha256"
    	"encoding/hex"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    	"strconv"
    	"strings"
    	"time"
    )
    
    var (
    	baseURL    = envOr("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
    	siteID     = os.Getenv("SIBLINKS_SITE_ID")
    	secret     = os.Getenv("SIBLINKS_SECRET")
    	httpClient = &http.Client{Timeout: 30 * time.Second}
    )
    
    func envOr(key, fallback string) string {
    	if v := os.Getenv(key); v != "" {
    		return v
    	}
    	return fallback
    }
    
    func sha256Hex(b []byte) string {
    	h := sha256.Sum256(b)
    	return hex.EncodeToString(h[:])
    }
    
    func hmacHex(message string) string {
    	m := hmac.New(sha256.New, []byte(secret))
    	m.Write([]byte(message))
    	return hex.EncodeToString(m.Sum(nil))
    }
    
    // APIError is an error answered by the API ({"error": {"code": ...}}).
    type APIError struct {
    	Status int
    	Code   string
    }
    
    func (e *APIError) Error() string { return fmt.Sprintf("%d %s", e.Status, e.Code) }
    
    // call sends a signed request and returns the verified JSON response.
    func call(method, path string, body any) (map[string]any, error) {
    	var raw []byte
    	if body != nil {
    		var err error
    		if raw, err = json.Marshal(body); err != nil {
    			return nil, err
    		}
    	}
    	ts := strconv.FormatInt(time.Now().Unix(), 10)
    	nonceBytes := make([]byte, 16)
    	if _, err := rand.Read(nonceBytes); err != nil {
    		return nil, err
    	}
    	nonce := hex.EncodeToString(nonceBytes)
    	signature := hmacHex(ts + "\n" + method + "\n" + path + "\n" + sha256Hex(raw) + "\n" + nonce)
    
    	req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(raw))
    	if err != nil {
    		return nil, err
    	}
    	req.Header.Set("X-Site-Id", siteID)
    	req.Header.Set("X-Timestamp", ts)
    	req.Header.Set("X-Nonce", nonce)
    	req.Header.Set("X-Signature", signature)
    	if body != nil {
    		req.Header.Set("Content-Type", "application/json")
    	}
    	resp, err := httpClient.Do(req)
    	if err != nil {
    		return nil, err
    	}
    	defer resp.Body.Close()
    	resBody, err := io.ReadAll(resp.Body)
    	if err != nil {
    		return nil, err
    	}
    
    	expected := hmacHex("response\n" + signature + "\n" + strconv.Itoa(resp.StatusCode) + "\n" + sha256Hex(resBody))
    	got := strings.ToLower(resp.Header.Get("X-SibLinks-Signature"))
    	if resp.StatusCode < 400 && !hmac.Equal([]byte(expected), []byte(got)) {
    		return nil, &APIError{resp.StatusCode, "unsigned_response"} // never trust it
    	}
    	var data map[string]any
    	if err := json.Unmarshal(resBody, &data); err != nil {
    		return nil, err
    	}
    	if resp.StatusCode >= 400 {
    		code := "unknown"
    		if e, ok := data["error"].(map[string]any); ok {
    			if c, ok := e["code"].(string); ok {
    				code = c
    			}
    		}
    		return nil, &APIError{resp.StatusCode, code}
    	}
    	return data, nil
    }
    # SibLinks API client example (Ruby 3.0+, standard library only).
    require "json"
    require "net/http"
    require "openssl"
    require "securerandom"
    
    BASE_URL = ENV.fetch("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
    SITE_ID = ENV.fetch("SIBLINKS_SITE_ID")
    SECRET = ENV.fetch("SIBLINKS_SECRET")
    
    class SibLinksError < StandardError
      attr_reader :status, :code
    
      def initialize(status, code)
        super("#{status} #{code}")
        @status = status
        @code = code
      end
    end
    
    def hmac_hex(message)
      OpenSSL::HMAC.hexdigest("SHA256", SECRET, message)
    end
    
    def call(method, path, body = nil)
      raw = body.nil? ? "" : JSON.generate(body)
      ts = Time.now.to_i.to_s
      nonce = SecureRandom.hex(16)
      signature = hmac_hex("#{ts}\n#{method}\n#{path}\n#{OpenSSL::Digest::SHA256.hexdigest(raw)}\n#{nonce}")
    
      uri = URI(BASE_URL + path)
      req = method == "GET" ? Net::HTTP::Get.new(uri) : Net::HTTP::Post.new(uri)
      req["X-Site-Id"] = SITE_ID
      req["X-Timestamp"] = ts
      req["X-Nonce"] = nonce
      req["X-Signature"] = signature
      unless body.nil?
        req["Content-Type"] = "application/json"
        req.body = raw
      end
      res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 30) { |http| http.request(req) }
    
      status = res.code.to_i
      res_body = res.body.to_s
      expected = hmac_hex("response\n#{signature}\n#{status}\n#{OpenSSL::Digest::SHA256.hexdigest(res_body)}")
      signed = OpenSSL.secure_compare(expected, res["X-SibLinks-Signature"].to_s.downcase)
      raise SibLinksError.new(status, "unsigned_response") if status < 400 && !signed # never trust it
    
      data = JSON.parse(res_body)
      raise SibLinksError.new(status, data.dig("error", "code") || "unknown") if status >= 400
    
      data
    end
  3. שולחים בדיקה

    שולחים את העמוד ואת העמודים שאפשר לקשר אליהם. התשובה חוזרת מיד עם job_id, והבדיקה רצה ברקע.

    POST/v1/jobs
    body=$(jq -cn '{
      source: {
        id: 123,
        title: "חופשה במינכן",
        content_html: "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
        existing_link_ids: [67]
      },
      targets: [{id: 45, title: "מלונות במינכן", description: "המלצות על מלונות במינכן לפי שכונות"}],
      options: {max_links: 10}
    }')
    job_id=$(siblinks_call POST /v1/jobs "$body" | jq -r .job_id)
    echo "$job_id"
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    job = call("POST", "/v1/jobs", {
        "source": {
            "id": 123,
            "title": "חופשה במינכן",
            "content_html": "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
            "existing_link_ids": [67],
        },
        "targets": [
            {"id": 45, "title": "מלונות במינכן",
             "description": "המלצות על מלונות במינכן לפי שכונות"},
        ],
        "options": {"max_links": 10},
    })
    job_id = job["job_id"]
    print(job_id)
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    const job = await call('POST', '/v1/jobs', {
      source: {
        id: 123,
        title: 'חופשה במינכן',
        content_html: '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
        existing_link_ids: [67],
      },
      targets: [
        { id: 45, title: 'מלונות במינכן', description: 'המלצות על מלונות במינכן לפי שכונות' },
      ],
      options: { max_links: 10 },
    });
    const jobId = job.job_id;
    console.log(jobId);
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    $job = siblinks_call(
    	'POST',
    	'/v1/jobs',
    	array(
    		'source'  => array(
    			'id'                => 123,
    			'title'             => 'חופשה במינכן',
    			'content_html'      => '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
    			'existing_link_ids' => array( 67 ),
    		),
    		'targets' => array(
    			array(
    				'id'          => 45,
    				'title'       => 'מלונות במינכן',
    				'description' => 'המלצות על מלונות במינכן לפי שכונות',
    			),
    		),
    		'options' => array( 'max_links' => 10 ),
    	)
    );
    $job_id = $job['job_id'];
    echo $job_id . "\n";
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    $job = $client->call(
    	'POST',
    	'/v1/jobs',
    	array(
    		'source'  => array(
    			'id'                => 123,
    			'title'             => 'חופשה במינכן',
    			'content_html'      => '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
    			'existing_link_ids' => array( 67 ),
    		),
    		'targets' => array(
    			array(
    				'id'          => 45,
    				'title'       => 'מלונות במינכן',
    				'description' => 'המלצות על מלונות במינכן לפי שכונות',
    			),
    		),
    		'options' => array( 'max_links' => 10 ),
    	)
    );
    $job_id = $job['job_id'];
    echo $job_id . "\n";
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    JsonNode job = call("POST", "/v1/jobs", Map.of(
            "source", Map.of(
                    "id", 123,
                    "title", "חופשה במינכן",
                    "content_html", "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
                    "existing_link_ids", List.of(67)),
            "targets", List.of(Map.of(
                    "id", 45,
                    "title", "מלונות במינכן",
                    "description", "המלצות על מלונות במינכן לפי שכונות")),
            "options", Map.of("max_links", 10)));
    String jobId = job.get("job_id").asText();
    System.out.println(jobId);
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    JsonNode job = await SibLinks.Call("POST", "/v1/jobs", new
    {
        source = new
        {
            id = 123,
            title = "חופשה במינכן",
            content_html = "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
            existing_link_ids = new[] { 67 },
        },
        targets = new[]
        {
            new { id = 45, title = "מלונות במינכן", description = "המלצות על מלונות במינכן לפי שכונות" },
        },
        options = new { max_links = 10 },
    });
    string jobId = job["job_id"]!.GetValue<string>();
    Console.WriteLine(jobId);
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    job, err := call("POST", "/v1/jobs", map[string]any{
    	"source": map[string]any{
    		"id":                123,
    		"title":             "חופשה במינכן",
    		"content_html":      "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
    		"existing_link_ids": []int{67},
    	},
    	"targets": []map[string]any{
    		{"id": 45, "title": "מלונות במינכן", "description": "המלצות על מלונות במינכן לפי שכונות"},
    	},
    	"options": map[string]any{"max_links": 10},
    })
    if err != nil {
    	return err
    }
    jobID := job["job_id"].(string)
    fmt.Println(jobID)
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
    job = call("POST", "/v1/jobs", {
      source: {
        id: 123,
        title: "חופשה במינכן",
        content_html: "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
        existing_link_ids: [67]
      },
      targets: [
        { id: 45, title: "מלונות במינכן", description: "המלצות על מלונות במינכן לפי שכונות" }
      ],
      options: { max_links: 10 }
    })
    job_id = job["job_id"]
    puts job_id
    Output
    job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
  4. מקבלים את ההצעות ומאשרים קבלה

    שואלים כל 3 שניות עד שהסטטוס הוא done, שומרים את ההצעות אצלכם, ושולחים אישור קבלה.

    GET/v1/jobs/{job_id}
    res=$(siblinks_call GET "/v1/jobs/$job_id")
    jq -r '.status' <<<"$res"
    jq -r '.suggestions[]? | "\(.target_id) \(.anchor_hint) \(.strength)"' <<<"$res"
    Output
    done
    45 מלונות טובים במינכן high
    res = call("GET", f"/v1/jobs/{job_id}")
    if res["status"] == "done":
        for s in res["suggestions"]:
            print(s["target_id"], s["anchor_hint"], s["strength"])
    Output
    45 מלונות טובים במינכן high
    const res = await call('GET', `/v1/jobs/${jobId}`);
    if (res.status === 'done') {
      for (const s of res.suggestions) console.log(s.target_id, s.anchor_hint, s.strength);
    }
    Output
    45 מלונות טובים במינכן high
    $res = siblinks_call( 'GET', '/v1/jobs/' . $job_id );
    if ( 'done' === $res['status'] ) {
    	foreach ( $res['suggestions'] as $s ) {
    		echo $s['target_id'] . ' ' . $s['anchor_hint'] . "\n";
    	}
    }
    Output
    45 מלונות טובים במינכן
    $res = $client->call( 'GET', '/v1/jobs/' . $job_id );
    if ( 'done' === $res['status'] ) {
    	foreach ( $res['suggestions'] as $s ) {
    		echo $s['target_id'] . ' ' . $s['anchor_hint'] . "\n";
    	}
    }
    Output
    45 מלונות טובים במינכן
    JsonNode res = call("GET", "/v1/jobs/" + jobId, null);
    if (res.get("status").asText().equals("done")) {
        for (JsonNode s : res.path("suggestions")) {
            System.out.println(s.get("target_id") + " " + s.get("anchor_hint").asText());
        }
    }
    Output
    45 מלונות טובים במינכן
    JsonNode res = await SibLinks.Call("GET", $"/v1/jobs/{jobId}");
    if (res["status"]!.GetValue<string>() == "done")
    {
        foreach (JsonNode? s in res["suggestions"]!.AsArray())
        {
            Console.WriteLine($"{s!["target_id"]} {s["anchor_hint"]}");
        }
    }
    Output
    45 מלונות טובים במינכן
    res, err := call("GET", "/v1/jobs/"+jobID, nil)
    if err != nil {
    	return err
    }
    if res["status"] == "done" {
    	for _, item := range res["suggestions"].([]any) {
    		s := item.(map[string]any)
    		fmt.Println(s["target_id"], s["anchor_hint"], s["strength"])
    	}
    }
    Output
    45 מלונות טובים במינכן high
    res = call("GET", "/v1/jobs/#{job_id}")
    if res["status"] == "done"
      res["suggestions"].each { |s| puts "#{s['target_id']} #{s['anchor_hint']}" }
    end
    Output
    45 מלונות טובים במינכן
    POST/v1/jobs/{job_id}/ack
    siblinks_call POST "/v1/jobs/$job_id/ack" '{}' | jq -c .
    Output
    {"ok":true}
    res = call("POST", f"/v1/jobs/{job_id}/ack", {})
    print(res)
    Output
    {'ok': True}
    const ack = await call('POST', `/v1/jobs/${jobId}/ack`, {});
    console.log(ack);
    Output
    { ok: true }
    $ack = siblinks_call( 'POST', '/v1/jobs/' . $job_id . '/ack', array() );
    echo json_encode( $ack ) . "\n";
    Output
    {"ok":true}
    $ack = $client->call( 'POST', '/v1/jobs/' . $job_id . '/ack', array() );
    echo json_encode( $ack ) . "\n";
    Output
    {"ok":true}
    JsonNode ack = call("POST", "/v1/jobs/" + jobId + "/ack", Map.of());
    System.out.println(ack);
    Output
    {"ok":true}
    JsonNode ack = await SibLinks.Call("POST", $"/v1/jobs/{jobId}/ack", new { });
    Console.WriteLine(ack.ToJsonString());
    Output
    {"ok":true}
    ack, err := call("POST", "/v1/jobs/"+jobID+"/ack", map[string]any{})
    if err != nil {
    	return err
    }
    fmt.Println(ack)
    Output
    map[ok:true]
    ack = call("POST", "/v1/jobs/#{job_id}/ack", {})
    p ack
    Output
    {"ok"=>true}

מה הלאה

התחלה

אימות וחתימות

כל בקשה, חוץ מ־/v1/health, חתומה ב־HMAC-SHA256 עם ה־Secret. ה־Secret עצמו אף פעם לא נשלח. כל תשובה מוצלחת חתומה בחזרה, וכך אתם יודעים שהיא באמת הגיעה מ־SibLinks.

כותרות בכל בקשה

  • X-Site-Idstringחובה

    ה־Site ID, בדיוק כפי שקיבלתם. אותיות גדולות וקטנות חשובות.

  • X-Timestampstringחובה

    זמן Unix בשניות.

  • X-Noncestringחובה

    מחרוזת אקראית חדשה לכל בקשה. אותיות באנגלית וספרות בלבד, עד 64 תווים. מומלץ 32 תווי hex.

  • X-Signaturehex · 64חובה

    החתימה, לפי הנוסחה בהמשך.

  • Content-Typestring

    application/json, כשיש גוף.

  • Content-Encodingstring

    gzip, רק אם דחסתם את הגוף. לא חובה.

חתימת הבקשה

Request signature
X-Signature = hex(HMAC-SHA256(secret,
    timestamp + "\n" +
    METHOD    + "\n" +
    path      + "\n" +
    sha256_hex(raw_body) + "\n" +
    nonce))
  • METHOD באותיות גדולות: GET או POST.
  • path הוא הנתיב בלבד, בלי הכתובת ובלי query string. למשל /v1/jobs/job_6f1c….
  • raw_body הם הבתים בדיוק כפי שנשלחים. חותמים על אותה מחרוזת שנשלחת, ולא מקודדים את ה־JSON שוב אחרי החתימה. בלי גוף, זה ה־hash של מחרוזת ריקה.
  • עם Content-Encoding: gzip, החתימה היא על הבתים הדחוסים.
  • אותה חתימה פעמיים נדחית (replayed_request). כל ניסיון חוזר צריך X-Timestamp ו־X-Nonce חדשים.

אימות התשובה

תשובה לבקשה מאומתת מגיעה עם הכותרת X-SibLinks-Signature. היא קשורה לחתימה של הבקשה, ולכן אי אפשר להעתיק תשובה לבקשה אחרת.

Response signature
X-SibLinks-Signature = hex(HMAC-SHA256(secret,
    "response" + "\n" +
    request_signature + "\n" +
    status_code + "\n" +
    sha256_hex(response_body)))

request_signature הוא ה־X-Signature ששלחתם. response_body הוא גוף התשובה אחרי פתיחת דחיסה של התעבורה, אם הייתה. רוב ספריות ה־HTTP עושות את זה לבד.

תשובה 2xx בלי חתימה תקינה לא מקבליםגם אם היא נראית תקינה. שגיאה שקרתה לפני שהבקשה אומתה, למשל invalid_signature, מגיעה בלי חתימה. מותר להתייחס אליה כשגיאה, אבל לא לסמוך על התוכן שלה.

קריאה חתומה בקוד

פונקציה אחת שחותמת, שולחת ובודקת את התשובה. כל הדוגמאות בתיעוד משתמשות בה.

Signed client
#!/usr/bin/env bash
# SibLinks API from the shell (bash, curl, openssl, jq).
# Note: openssl receives the secret as an argument, so other users on the same machine can see it
# in the process list. Use this for testing; in production use one of the language clients.
set -euo pipefail
BASE_URL="${SIBLINKS_BASE_URL:-https://api.siblinks.co.il}"

hmac_hex() { openssl dgst -sha256 -hmac "$SIBLINKS_SECRET" -r | cut -d' ' -f1; }

# siblinks_call METHOD PATH [BODY_JSON]: prints the verified response body.
siblinks_call() {
  local method="$1" path="$2" body="${3-}"
  local ts nonce sig tmp status expected got
  ts=$(date +%s)
  nonce=$(openssl rand -hex 16)
  sig=$(printf '%s\n%s\n%s\n%s\n%s' "$ts" "$method" "$path" \
    "$(printf '%s' "$body" | openssl dgst -sha256 -r | cut -d' ' -f1)" "$nonce" | hmac_hex)

  tmp=$(mktemp -d)
  local args=(-sS -X "$method" "$BASE_URL$path" --compressed -D "$tmp/headers" -o "$tmp/body" -w '%{http_code}'
    -H "X-Site-Id: $SIBLINKS_SITE_ID" -H "X-Timestamp: $ts" -H "X-Nonce: $nonce" -H "X-Signature: $sig")
  if [ -n "$body" ]; then
    args+=(-H "Content-Type: application/json" --data-binary "$body")
  fi
  status=$(curl "${args[@]}")

  expected=$(printf 'response\n%s\n%s\n%s' "$sig" "$status" \
    "$(openssl dgst -sha256 -r < "$tmp/body" | cut -d' ' -f1)" | hmac_hex)
  got=$( (grep -i '^x-siblinks-signature:' "$tmp/headers" || true) | tail -1 | cut -d: -f2 | tr -d ' \r' | tr 'A-F' 'a-f')
  if [ "$status" -lt 400 ] && [ "$expected" != "$got" ]; then
    echo "unsigned_response" >&2; rm -rf "$tmp"; return 1 # never trust it
  fi
  if [ "$status" -ge 400 ]; then
    echo "error $status $(jq -r '.error.code // "unknown"' "$tmp/body")" >&2; rm -rf "$tmp"; return 1
  fi
  cat "$tmp/body"
  rm -rf "$tmp"
}
import hashlib
import hmac
import json
import os
import secrets
import time

import requests

BASE_URL = os.environ.get("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
SITE_ID = os.environ["SIBLINKS_SITE_ID"]
SECRET = os.environ["SIBLINKS_SECRET"]


class SibLinksError(Exception):
    def __init__(self, status, code):
        super().__init__(f"{status} {code}")
        self.status, self.code = status, code


def _hmac(text: str) -> str:
    return hmac.new(SECRET.encode("utf-8"), text.encode("utf-8"), hashlib.sha256).hexdigest()


def call(method: str, path: str, body=None):
    raw = b"" if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
    ts = str(int(time.time()))
    nonce = secrets.token_hex(16)
    signature = _hmac(f"{ts}\n{method}\n{path}\n{hashlib.sha256(raw).hexdigest()}\n{nonce}")
    headers = {"X-Site-Id": SITE_ID, "X-Timestamp": ts, "X-Nonce": nonce, "X-Signature": signature}
    if body is not None:
        headers["Content-Type"] = "application/json"
    r = requests.request(method, BASE_URL + path, data=raw if body is not None else None,
                         headers=headers, timeout=30)
    expected = _hmac(f"response\n{signature}\n{r.status_code}\n{hashlib.sha256(r.content).hexdigest()}")
    signed = hmac.compare_digest(expected, r.headers.get("X-SibLinks-Signature", "").lower())
    if r.status_code < 400 and not signed:
        raise SibLinksError(r.status_code, "unsigned_response")  # never trust it
    data = r.json()
    if r.status_code >= 400:
        raise SibLinksError(r.status_code, (data.get("error") or {}).get("code", "unknown"))
    return data
// SibLinks API client example (Node.js 18+, no dependencies).
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';

const BASE_URL = process.env.SIBLINKS_BASE_URL || 'https://api.siblinks.co.il';
const SITE_ID = process.env.SIBLINKS_SITE_ID;
const SECRET = process.env.SIBLINKS_SECRET;

const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
const hmac = (text) => createHmac('sha256', SECRET).update(text, 'utf8').digest('hex');

export async function call(method, path, body) {
  const raw = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body), 'utf8');
  const ts = String(Math.floor(Date.now() / 1000));
  const nonce = randomBytes(16).toString('hex');
  const signature = hmac(`${ts}\n${method}\n${path}\n${sha256(raw)}\n${nonce}`);
  const headers = { 'X-Site-Id': SITE_ID, 'X-Timestamp': ts, 'X-Nonce': nonce, 'X-Signature': signature };
  if (body !== undefined) headers['Content-Type'] = 'application/json';

  const res = await fetch(BASE_URL + path, { method, headers, body: body === undefined ? undefined : raw });
  const resBody = Buffer.from(await res.arrayBuffer());
  const expected = Buffer.from(hmac(`response\n${signature}\n${res.status}\n${sha256(resBody)}`));
  const got = Buffer.from((res.headers.get('x-siblinks-signature') || '').toLowerCase());
  const signedOk = got.length === expected.length && timingSafeEqual(got, expected);
  if (res.status < 400 && !signedOk) throw new Error('unsigned_response'); // never trust it

  const data = JSON.parse(resBody.toString('utf8'));
  if (res.status >= 400) throw Object.assign(new Error(data.error?.code || 'unknown'), { status: res.status });
  return data;
}
<?php
// SibLinks API client example (PHP 8, curl extension).

$base_url = getenv( 'SIBLINKS_BASE_URL' ) ?: 'https://api.siblinks.co.il';
$site_id  = getenv( 'SIBLINKS_SITE_ID' );
$secret   = getenv( 'SIBLINKS_SECRET' );

function siblinks_call( string $method, string $path, ?array $body = null ): array {
	global $base_url, $site_id, $secret;

	$raw   = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE );
	$ts    = (string) time();
	$nonce = bin2hex( random_bytes( 16 ) );
	$sig   = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $secret );

	$headers = array( "X-Site-Id: {$site_id}", "X-Timestamp: {$ts}", "X-Nonce: {$nonce}", "X-Signature: {$sig}" );
	if ( null !== $body ) {
		$headers[] = 'Content-Type: application/json';
	}

	$resp_sig = '';
	$ch       = curl_init( $base_url . $path );
	curl_setopt_array(
		$ch,
		array(
			CURLOPT_CUSTOMREQUEST  => $method,
			CURLOPT_HTTPHEADER     => $headers,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING       => '', // decode gzip/br if a proxy compressed the response
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_HEADERFUNCTION => function ( $ch, $line ) use ( &$resp_sig ) {
				if ( 0 === stripos( $line, 'X-SibLinks-Signature:' ) ) {
					$resp_sig = strtolower( trim( substr( $line, 21 ) ) );
				}
				return strlen( $line );
			},
		)
	);
	if ( null !== $body ) {
		curl_setopt( $ch, CURLOPT_POSTFIELDS, $raw );
	}
	$resp   = curl_exec( $ch );
	$status = (int) curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
	if ( false === $resp ) {
		throw new RuntimeException( 'connection_failed: ' . curl_error( $ch ) );
	}

	$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $secret );
	if ( $status < 400 && ! hash_equals( $expected, $resp_sig ) ) {
		throw new RuntimeException( 'unsigned_response' ); // never trust it
	}
	$data = json_decode( $resp, true );
	if ( $status >= 400 ) {
		throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
	}
	return $data;
}
<?php
// SibLinks API client example (PHP 8.0+, Guzzle 7: composer require guzzlehttp/guzzle).
require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client;

final class SibLinksClient {
	private Client $http;

	public function __construct( private string $site_id, private string $secret, string $base_url = 'https://api.siblinks.co.il' ) {
		$this->http = new Client(
			array(
				'base_uri'    => $base_url,
				'timeout'     => 30,
				'http_errors' => false, // errors are read from the JSON body below
			)
		);
	}

	public function call( string $method, string $path, ?array $body = null ): array {
		$raw   = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR );
		$ts    = (string) time();
		$nonce = bin2hex( random_bytes( 16 ) );
		$sig   = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $this->secret );

		$headers = array(
			'X-Site-Id'   => $this->site_id,
			'X-Timestamp' => $ts,
			'X-Nonce'     => $nonce,
			'X-Signature' => $sig,
		);
		if ( null !== $body ) {
			$headers['Content-Type'] = 'application/json';
		}

		$res    = $this->http->request( $method, $path, array( 'headers' => $headers, 'body' => $raw ) );
		$status = $res->getStatusCode();
		$resp   = (string) $res->getBody();

		$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $this->secret );
		if ( $status < 400 && ! hash_equals( $expected, strtolower( $res->getHeaderLine( 'X-SibLinks-Signature' ) ) ) ) {
			throw new RuntimeException( 'unsigned_response' ); // never trust it
		}
		$data = json_decode( $resp, true );
		if ( $status >= 400 ) {
			throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
		}
		return $data;
	}
}
// SibLinks API client example (Java 17+, Jackson 2.x: com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SibLinksClient {
    static final String BASE_URL = Optional.ofNullable(System.getenv("SIBLINKS_BASE_URL")).orElse("https://api.siblinks.co.il");
    static final String SITE_ID = System.getenv("SIBLINKS_SITE_ID");
    static final String SECRET = System.getenv("SIBLINKS_SECRET");

    static final ObjectMapper JSON = new ObjectMapper();
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
    static final SecureRandom RANDOM = new SecureRandom();
    static final HexFormat HEX = HexFormat.of();

    static class SibLinksException extends Exception {
        final int status;
        final String code;

        SibLinksException(int status, String code) {
            super(status + " " + code);
            this.status = status;
            this.code = code;
        }
    }

    static String sha256(byte[] data) throws Exception {
        return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(data));
    }

    static String hmac(String message) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        return HEX.formatHex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
    }

    static JsonNode call(String method, String path, Object body) throws Exception {
        byte[] raw = body == null ? new byte[0] : JSON.writeValueAsBytes(body);
        String ts = Long.toString(System.currentTimeMillis() / 1000);
        byte[] nonceBytes = new byte[16];
        RANDOM.nextBytes(nonceBytes);
        String nonce = HEX.formatHex(nonceBytes);
        String signature = hmac(ts + "\n" + method + "\n" + path + "\n" + sha256(raw) + "\n" + nonce);

        HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(BASE_URL + path))
                .timeout(Duration.ofSeconds(30))
                .header("X-Site-Id", SITE_ID)
                .header("X-Timestamp", ts)
                .header("X-Nonce", nonce)
                .header("X-Signature", signature)
                .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(raw));
        if (body != null) {
            req.header("Content-Type", "application/json");
        }
        HttpResponse<byte[]> res = HTTP.send(req.build(), HttpResponse.BodyHandlers.ofByteArray());

        int status = res.statusCode();
        String expected = hmac("response\n" + signature + "\n" + status + "\n" + sha256(res.body()));
        String got = res.headers().firstValue("X-SibLinks-Signature").orElse("").toLowerCase(Locale.ROOT);
        boolean signed = MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), got.getBytes(StandardCharsets.UTF_8));
        if (status < 400 && !signed) {
            throw new SibLinksException(status, "unsigned_response"); // never trust it
        }
        JsonNode data = JSON.readTree(res.body());
        if (status >= 400) {
            throw new SibLinksException(status, data.path("error").path("code").asText("unknown"));
        }
        return data;
    }
    // main() and your own code go here
}
// SibLinks API client example (.NET 6+, no extra packages).
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

public class SibLinksException : Exception
{
    public int Status { get; }
    public string Code { get; }

    public SibLinksException(int status, string code) : base($"{status} {code}")
    {
        Status = status;
        Code = code;
    }
}

public static class SibLinks
{
    static readonly string BaseUrl = Environment.GetEnvironmentVariable("SIBLINKS_BASE_URL") ?? "https://api.siblinks.co.il";
    static readonly string SiteId = Environment.GetEnvironmentVariable("SIBLINKS_SITE_ID")!;
    static readonly byte[] Secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SIBLINKS_SECRET")!);

    static readonly HttpClient Http = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All })
    {
        Timeout = TimeSpan.FromSeconds(30),
    };

    static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant();

    static string Hmac(string message) => Hex(HMACSHA256.HashData(Secret, Encoding.UTF8.GetBytes(message)));

    public static async Task<JsonNode> Call(string method, string path, object? body = null)
    {
        byte[] raw = body is null ? Array.Empty<byte>() : JsonSerializer.SerializeToUtf8Bytes(body);
        string ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        string nonce = Hex(RandomNumberGenerator.GetBytes(16));
        string signature = Hmac($"{ts}\n{method}\n{path}\n{Hex(SHA256.HashData(raw))}\n{nonce}");

        using var req = new HttpRequestMessage(new HttpMethod(method), BaseUrl + path);
        req.Headers.Add("X-Site-Id", SiteId);
        req.Headers.Add("X-Timestamp", ts);
        req.Headers.Add("X-Nonce", nonce);
        req.Headers.Add("X-Signature", signature);
        if (body is not null)
        {
            req.Content = new ByteArrayContent(raw);
            req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }

        using var res = await Http.SendAsync(req);
        byte[] resBody = await res.Content.ReadAsByteArrayAsync();
        int status = (int)res.StatusCode;

        string expected = Hmac($"response\n{signature}\n{status}\n{Hex(SHA256.HashData(resBody))}");
        string got = res.Headers.TryGetValues("X-SibLinks-Signature", out var values) ? values.First().ToLowerInvariant() : "";
        bool signed = CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(got));
        if (status < 400 && !signed)
        {
            throw new SibLinksException(status, "unsigned_response"); // never trust it
        }
        JsonNode data = JsonNode.Parse(resBody)!;
        if (status >= 400)
        {
            throw new SibLinksException(status, data["error"]?["code"]?.GetValue<string>() ?? "unknown");
        }
        return data;
    }
}
// SibLinks API client example (Go 1.20+, standard library only).
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

var (
	baseURL    = envOr("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
	siteID     = os.Getenv("SIBLINKS_SITE_ID")
	secret     = os.Getenv("SIBLINKS_SECRET")
	httpClient = &http.Client{Timeout: 30 * time.Second}
)

func envOr(key, fallback string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return fallback
}

func sha256Hex(b []byte) string {
	h := sha256.Sum256(b)
	return hex.EncodeToString(h[:])
}

func hmacHex(message string) string {
	m := hmac.New(sha256.New, []byte(secret))
	m.Write([]byte(message))
	return hex.EncodeToString(m.Sum(nil))
}

// APIError is an error answered by the API ({"error": {"code": ...}}).
type APIError struct {
	Status int
	Code   string
}

func (e *APIError) Error() string { return fmt.Sprintf("%d %s", e.Status, e.Code) }

// call sends a signed request and returns the verified JSON response.
func call(method, path string, body any) (map[string]any, error) {
	var raw []byte
	if body != nil {
		var err error
		if raw, err = json.Marshal(body); err != nil {
			return nil, err
		}
	}
	ts := strconv.FormatInt(time.Now().Unix(), 10)
	nonceBytes := make([]byte, 16)
	if _, err := rand.Read(nonceBytes); err != nil {
		return nil, err
	}
	nonce := hex.EncodeToString(nonceBytes)
	signature := hmacHex(ts + "\n" + method + "\n" + path + "\n" + sha256Hex(raw) + "\n" + nonce)

	req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(raw))
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-Site-Id", siteID)
	req.Header.Set("X-Timestamp", ts)
	req.Header.Set("X-Nonce", nonce)
	req.Header.Set("X-Signature", signature)
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	resp, err := httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	resBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	expected := hmacHex("response\n" + signature + "\n" + strconv.Itoa(resp.StatusCode) + "\n" + sha256Hex(resBody))
	got := strings.ToLower(resp.Header.Get("X-SibLinks-Signature"))
	if resp.StatusCode < 400 && !hmac.Equal([]byte(expected), []byte(got)) {
		return nil, &APIError{resp.StatusCode, "unsigned_response"} // never trust it
	}
	var data map[string]any
	if err := json.Unmarshal(resBody, &data); err != nil {
		return nil, err
	}
	if resp.StatusCode >= 400 {
		code := "unknown"
		if e, ok := data["error"].(map[string]any); ok {
			if c, ok := e["code"].(string); ok {
				code = c
			}
		}
		return nil, &APIError{resp.StatusCode, code}
	}
	return data, nil
}
# SibLinks API client example (Ruby 3.0+, standard library only).
require "json"
require "net/http"
require "openssl"
require "securerandom"

BASE_URL = ENV.fetch("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
SITE_ID = ENV.fetch("SIBLINKS_SITE_ID")
SECRET = ENV.fetch("SIBLINKS_SECRET")

class SibLinksError < StandardError
  attr_reader :status, :code

  def initialize(status, code)
    super("#{status} #{code}")
    @status = status
    @code = code
  end
end

def hmac_hex(message)
  OpenSSL::HMAC.hexdigest("SHA256", SECRET, message)
end

def call(method, path, body = nil)
  raw = body.nil? ? "" : JSON.generate(body)
  ts = Time.now.to_i.to_s
  nonce = SecureRandom.hex(16)
  signature = hmac_hex("#{ts}\n#{method}\n#{path}\n#{OpenSSL::Digest::SHA256.hexdigest(raw)}\n#{nonce}")

  uri = URI(BASE_URL + path)
  req = method == "GET" ? Net::HTTP::Get.new(uri) : Net::HTTP::Post.new(uri)
  req["X-Site-Id"] = SITE_ID
  req["X-Timestamp"] = ts
  req["X-Nonce"] = nonce
  req["X-Signature"] = signature
  unless body.nil?
    req["Content-Type"] = "application/json"
    req.body = raw
  end
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 30) { |http| http.request(req) }

  status = res.code.to_i
  res_body = res.body.to_s
  expected = hmac_hex("response\n#{signature}\n#{status}\n#{OpenSSL::Digest::SHA256.hexdigest(res_body)}")
  signed = OpenSSL.secure_compare(expected, res["X-SibLinks-Signature"].to_s.downcase)
  raise SibLinksError.new(status, "unsigned_response") if status < 400 && !signed # never trust it

  data = JSON.parse(res_body)
  raise SibLinksError.new(status, data.dig("error", "code") || "unknown") if status >= 400

  data
end

בודקים את החתימה

המחשבון מחשב את החתימות כמו השרת. הוא מגיע עם ערכי בדיקה קבועים: אם הקוד שלכם מחזיר את אותן חתימות לאותם ערכים, החתימה נכונה.

מחשבון חתימותהחישוב נעשה בדפדפן, ושום דבר לא נשלח.
sha256(raw_body)…
המחרוזת לחתימה…
X-Signature…
X-SibLinks-Signature…
ערכים משלכם: השוו לחתימה שהקוד שלכם מחשב.
התחלה

מחזור החיים של בדיקה

בדיקה רצה ברקע. היא מתחילה ב־queued, ומסתיימת ב־done עם ההצעות או ב־failed עם סיבה.

queued processing done failed מחויבת פעם אחת לא מחויבת

הצעדים

  1. שליחה. POST /v1/jobs עם העמוד ועם עמודי היעד. התשובה מחזירה job_id.
  2. המתנה. GET /v1/jobs/{job_id} כל 3 שניות, עד done או failed.
  3. שמירה. ב־done התשובה כוללת את suggestions. שומרים אותן אצלכם. השרת לא שומר אותן לאורך זמן.
  4. אישור קבלה. POST /v1/jobs/{job_id}/ack מוחק את התוצאה מהשרת. בלי אישור היא נמחקת לבד אחרי 24 שעות.

חיוב

בדיקה מחויבת רק כשהיא מסתיימת ב־done. בדיקה שנכשלה לא עולה כלום. בזמן שבדיקה רצה, היא כבר נספרת כמשומשת ב־credits_remaining, ואם היא נכשלת היא חוזרת ליתרה.

בקשה כפולה

בקשה זהה (אותו עמוד, אותו תוכן, אותם יעדים ואותן options) בזמן שהבדיקה הקודמת עוד רצה מחזירה את אותו job_id, ולא מחויבת פעמיים. כך אפשר לשלוח שוב בבטחה אחרי תקלת רשת.

מדריכים

שגיאות

שגיאה חוזרת עם קוד HTTP מתאים וגוף JSON. מחליטים לפי error.code. ה־message נועד למתכנת ויכול להשתנות. קוד שאינכם מכירים מטפלים בו כשגיאה כללית.

Error response402
{
  "error": {
    "code": "insufficient_credits",
    "message": "no checks left"
  }
}

שגיאות בבקשה

קודHTTPמה קרה, ומה לעשות
invalid_signature401כותרת חסרה, חתימה שגויה, nonce לא תקין, או שעון לא מסונכרן. בודקים את ה־Secret, את החתימה במחשבון, ואת השעון.
replayed_request401אותה חתימה נשלחה פעמיים. שולחים שוב עם X-Timestamp ו־X-Nonce חדשים.
license_inactive403ה־Site ID לא קיים, מושהה, או שהחשבון מושבת. בודקים את מצב האתר באזור הלקוחות.
invalid_payload400JSON פגום, שדה חובה חסר, או מזהה לא תקין. מתקנים את הבקשה, ולא שולחים שוב כמו שהיא.
payload_too_large413הגוף גדול מדי. שולחים פחות תוכן או פחות יעדים, או דוחסים ב־gzip.
targets_exceed_plan413יותר עמודי יעד מ־plan.max_targets.
insufficient_credits402נגמרו הבדיקות. רוכשים בדיקות נוספות.
rate_limited429יותר מדי בדיקות פתוחות, או יותר מדי בדיקות בשעה. מחכים לפי Retry-After.
job_not_found404הבדיקה לא קיימת, נמחקה, או שאינה של האתר.
job_open409ack לבדיקה שעוד רצה. ממשיכים לשאול עד done.
job_not_ready409שלב 2 של קישורים אל עמוד נשלח מוקדם מדי. מחכים 5 שניות.
job_not_awaiting409שלב 2 לבדיקה שכבר לא מחכה לתוכן. בודקים את הסטטוס ב־GET.

סיבות לבדיקה שנכשלה

בדיקה עם status: "failed" מחזירה את הסיבה ב־error.code. בדיקה שנכשלה לא מחויבת.

קודמה קרה, ומה לעשות
no_contentלא נמצא בעמוד טקסט מתאים. בודקים ש־content_html מכיל את התוכן עצמו ולא רק תבנית.
upstream_unavailableהשירות לא זמין זמנית. מנסים שוב בעוד כמה דקות.
internal_errorתקלה בשרת. מנסים שוב. אם זה חוזר, פונים לתמיכה.
server_restartedהשרת הופעל מחדש בזמן הבדיקה. מתחילים בדיקה חדשה.
timeoutהבדיקה לא הסתיימה תוך 30 דקות. מתחילים בדיקה חדשה.
site_inactiveהאתר הושהה, או שהחשבון הושבת, בזמן הבדיקה.
no_candidatesקישורים אל עמוד: לא נמצאו עמודים מתאימים.
expiredקישורים אל עמוד: שלב 2 לא נשלח תוך 10 דקות.
cancelledקישורים אל עמוד: בוטל ב־ack לפני שלב 2.

פנייה לתמיכה

כותבים ל־info@siblinks.co.il, ומצרפים את ה־job_id ואת הזמן. את ה־Secret לא שולחים.

מדריכים

מגבלות וחיוב

בדיקה עולה בדיקה אחת מהיתרה, רק כשהיא מסתיימת ב־done. הערכים כאן הם הערכים הנוכחיים, והם יכולים להשתנות.

מגבלות

מגבלהערךמעבר לה
גודל גוף הבקשה25MB אחרי דחיסה. פתוח: עד פי 4413 / 400
עמודי יעד בבדיקהplan.max_targets, בדרך כלל 1000413 targets_exceed_plan
בדיקות פתוחות במקביל3 לכל אתר429, Retry-After: 10
בדיקות חדשות בשעה120 לכל אתר429, Retry-After: 600
max_links1 עד 50מתוקן לגבול
הפרש שעונים5 דקות401 invalid_signature
שמירת תוצאה24 שעות, או עד ack404 job_not_found
בדיקה שלא הסתיימה30 דקותfailed עם timeout, בלי חיוב
429 Too Many Requests
HTTP/1.1 429 Too Many Requests
Retry-After: 10
Content-Type: application/json

{"error": {"code": "rate_limited", "message": "too many open jobs"}}

יתרה

  • בדיקה שרצה כבר נספרת כמשומשת ב־credits_remaining. אם היא נכשלת, הבדיקה חוזרת ליתרה.
  • כל האתרים של אותו חשבון משתמשים באותה יתרה, כולל אתרים שמחוברים דרך התוסף לוורדפרס.
  • כשהיתרה נגמרת, יצירת בדיקה מחזירה 402 insufficient_credits. רוכשים בדיקות נוספות בכתובת שב־plan.portal_url.
מדריכים

המלצות יישום

מה לשלוח, איך לשמור על ה־Secret, איך להמתין, ואיך להציג את ההצעות למשתמש.

ה־Secret

  • שומרים אותו במשתנה סביבה או במנהל סודות. לא בקוד, לא במסד בטקסט גלוי, ולא בלוגים.
  • אם הוא דלף, מחליפים אותו באזור הלקוחות. הישן מפסיק לעבוד מיד.
  • כל אתר מקבל Site ID ו־Secret משלו. לא משתפים אותם בין אתרים.

מזהי עמודים

  • המזהים הם מספרים שלמים. אם המערכת שלכם משתמשת ב־UUID או ב־slug, שומרים טבלת מיפוי למספר קבוע לכל עמוד.
  • אותו עמוד מקבל תמיד אותו מספר, גם כשהוא מקור וגם כשהוא יעד. אחרת existing_link_ids ו־exclude_ids לא יעבדו.

מה לשלוח

  • ב־content_html: רק אזור התוכן של העמוד, אחרי שהוא מוכן להצגה. בלי shortcodes ובלי תבניות שלא עובדו.
  • לכל עמוד יעד: כותרת, תיאור ותקציר טובים. הם מה שקובע אם עמוד יוצע.
  • ב־existing_link_ids: העמודים שכבר מקושרים מהעמוד. ב־exclude_ids: עמודים שאסור להציע, כמו צור קשר או תנאי שימוש.
  • באתר גדול מ־max_targets: קודם עמודים מאותה קטגוריה או תגית, ואחר כך החדשים ביותר.

המתנה וניסיונות חוזרים

  • שואלים כל 3 שניות. אחרי דקה אפשר להאט ל־10 עד 15 שניות. אחרי 30 דקות הבדיקה נכשלת ממילא.
  • אחרי תקלת רשת אפשר לשלוח שוב את אותה בדיקה, עם חתימה חדשה. אם הבדיקה הראשונה עוד רצה, תחזור אותה בדיקה ולא תחויב שוב.
  • ב־429 מחכים לפי Retry-After. ב־400, 402 ו־413 לא שולחים שוב את אותה בקשה.

הצגת ההצעות למשתמש

  • מחפשים את sentence בתוכן הנוכחי, אחרי נרמול רווחים. אם התוכן השתנה והמשפט לא נמצא, מציגים "המשפט השתנה" ולא מוסיפים קישור.
  • עוטפים את anchor_hint בתוך המשפט בתגית <a> לכתובת של target_id. כש־anchor_hint הוא null, נותנים למשתמש לבחור את המילים.
  • מציגים את reason ואת strength (למשל "התאמה חזקה") כדי לעזור להחליט, ונותנים לדחות הצעה.
  • שומרים אצלכם את מצב כל הצעה: חדשה, בוצעה או נדחתה. השרת לא זוכר אותו.
Insert the link
# Links are inserted by your own application code, not from the shell.
# Pick one of the other languages to see a function that does it.
import html

def link_sentence(sentence: str, anchor: str, url: str) -> str:
    """Wrap the first occurrence of anchor in the sentence with a link."""
    i = sentence.find(anchor)
    if i < 0:
        return html.escape(sentence)
    return (html.escape(sentence[:i])
            + f'<a href="{html.escape(url)}">{html.escape(anchor)}</a>'
            + html.escape(sentence[i + len(anchor):]))
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);

function linkSentence(sentence, anchor, url) {
  const i = sentence.indexOf(anchor);
  if (i < 0) return esc(sentence);
  return esc(sentence.slice(0, i))
    + `<a href="${esc(url)}">${esc(anchor)}</a>`
    + esc(sentence.slice(i + anchor.length));
}
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
function siblinks_link_sentence( string $sentence, string $anchor, string $url ): string {
	$i = mb_strpos( $sentence, $anchor );
	if ( false === $i ) {
		return htmlspecialchars( $sentence );
	}
	return htmlspecialchars( mb_substr( $sentence, 0, $i ) )
		. '<a href="' . htmlspecialchars( $url ) . '">' . htmlspecialchars( $anchor ) . '</a>'
		. htmlspecialchars( mb_substr( $sentence, $i + mb_strlen( $anchor ) ) );
}
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
function siblinks_link_sentence( string $sentence, string $anchor, string $url ): string {
	$i = mb_strpos( $sentence, $anchor );
	if ( false === $i ) {
		return htmlspecialchars( $sentence );
	}
	return htmlspecialchars( mb_substr( $sentence, 0, $i ) )
		. '<a href="' . htmlspecialchars( $url ) . '">' . htmlspecialchars( $anchor ) . '</a>'
		. htmlspecialchars( mb_substr( $sentence, $i + mb_strlen( $anchor ) ) );
}
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
static String esc(String s) {
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}

static String linkSentence(String sentence, String anchor, String url) {
    int i = sentence.indexOf(anchor);
    if (i < 0) {
        return esc(sentence);
    }
    return esc(sentence.substring(0, i))
            + "<a href=\"" + esc(url) + "\">" + esc(anchor) + "</a>"
            + esc(sentence.substring(i + anchor.length()));
}
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
static string Esc(string s) =>
    s.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;");

static string LinkSentence(string sentence, string anchor, string url)
{
    int i = sentence.IndexOf(anchor, StringComparison.Ordinal);
    if (i < 0) return Esc(sentence);
    return Esc(sentence[..i])
        + $"<a href=\"{Esc(url)}\">{Esc(anchor)}</a>"
        + Esc(sentence[(i + anchor.Length)..]);
}
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
func linkSentence(sentence, anchor, url string) string {
	i := strings.Index(sentence, anchor)
	if i < 0 {
		return html.EscapeString(sentence)
	}
	return html.EscapeString(sentence[:i]) +
		`<a href="` + html.EscapeString(url) + `">` + html.EscapeString(anchor) + `</a>` +
		html.EscapeString(sentence[i+len(anchor):])
}
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
require "cgi"

def link_sentence(sentence, anchor, url)
  i = sentence.index(anchor)
  return CGI.escapeHTML(sentence) if i.nil?

  CGI.escapeHTML(sentence[0...i]) +
    %(<a href="#{CGI.escapeHTML(url)}">#{CGI.escapeHTML(anchor)}</a>) +
    CGI.escapeHTML(sentence[(i + anchor.length)..])
end
Output
יש הרבה <a href="https://example.co.il/munich-hotels">מלונות טובים במינכן</a> ליד התחנה.
API Reference

אובייקט ההצעה

כל הצעה אומרת איזה משפט בעמוד להפוך לקישור, אילו מילים בו, ולאיזה עמוד. ההצעות מגיעות ברשימה suggestions של בדיקה שהסתיימה, לפי סדר עדיפות.

שדות

  • target_idinteger

    העמוד שהקישור יוביל אליו.

  • sentencestring

    המשפט מתוך העמוד, עם רווחים מנורמלים. משפט ארוך מאוד מקוצר.

  • anchor_hintstring | null

    המילים המוצעות לטקסט הקישור. תמיד קטע מדויק מתוך sentence, או null.

  • strength"high" | "mid" | "low"

    עד כמה ההתאמה חזקה.

  • reasonstring

    הסבר קצר בעברית למה ההצעה מתאימה. לא תמיד קיים.

  • paragraph_indexinteger

    מספר בלוק הטקסט בתוכן, בלי כותרות. מתחיל מ־0.

  • sentence_indexinteger

    מספר המשפט בתוך הבלוק. מתחיל מ־0.

  • source_idinteger

    רק בקישורים אל עמוד: העמוד שצריך לערוך ולהוסיף בו את הקישור.

כל משפט, כל עמוד יעד וכל בלוק טקסט מופיעים לכל היותר בהצעה אחת.

The suggestion object
{
  "target_id": 45,
  "sentence": "יש הרבה מלונות טובים במינכן ליד התחנה.",
  "paragraph_index": 0,
  "sentence_index": 0,
  "anchor_hint": "מלונות טובים במינכן",
  "strength": "high",
  "reason": "אותה עיר: מינכן"
}
API Reference

יצירת בדיקה

POST/v1/jobs

מתחיל בדיקה של עמוד אחד מול רשימת עמודי יעד. הבדיקה רצה ברקע, והתשובה חוזרת מיד עם job_id.

גוף הבקשה

  • sourceobjectחובה

    העמוד שבודקים.

    השדות של source
    • idintegerחובה

      מספר שלם בין 0 ל־263−1, או מחרוזת של ספרות.

    • content_htmlstringחובה

      ה־HTML של אזור התוכן בלבד, בלי תפריט, פוטר וסרגל צד.

    • titlestringמומלץ

      כותרת העמוד. עוזרת להבין את ההקשר של המשפטים.

    • content_hashstring

      כל מחרוזת שמשתנה כשהתוכן משתנה. משמשת לזיהוי בקשה כפולה.

    • existing_link_idsinteger[]

      מזהי עמודים שהעמוד כבר מקשר אליהם. לא יוצעו שוב.

  • targetsobject[]חובה

    העמודים שאפשר לקשר אליהם, עד plan.max_targets. עמוד יעד בלי כותרת, בלי תיאור ובלי תקציר לא נבדק.

    השדות של כל יעד
    • idintegerחובה

      מזהה העמוד, באותו פורמט כמו source.id.

    • titlestringמומלץ

      כותרת העמוד.

    • descriptionstringמומלץ

      תיאור מטא.

    • excerptstringמומלץ

      תקציר, או תחילת התוכן. טקסט או HTML.

    • h1string

      כותרת H1, אם היא שונה מהכותרת.

    • focus_keywordstring

      ביטוי המפתח של העמוד.

    • priority"money" | "normal"

      money לעמוד שחשוב לכם לקדם. מקבל עדיפות קלה.

  • optionsobject

    שדות אחרים ב־options לא משפיעים.

    השדות של options
    • max_linksinteger

      מספר ההצעות המרבי, 1 עד 50. ברירת מחדל 15.

    • exclude_idsinteger[]

      מזהים שאסור להציע.

מה נקרא מתוך content_html

  • כותרות (h1 עד h6), תפריטים, טפסים, כפתורים, סקריפטים ותמונות לא נקראים.
  • משפט שכבר יש בו קישור, או שיש בו פחות מ־5 מילים, לא מוצע.
  • נבדקים עד 400 המשפטים הראשונים.

תשובה

  • job_idstring

    מזהה הבדיקה, לשימוש בקבלת בדיקה.

  • statusstring

    queued, או הסטטוס של בדיקה זהה שעוד רצה.

  • credits_remaininginteger | null

    היתרה, כשהבדיקה הזו כבר נספרת.

בקשה זהה בזמן שהבדיקה הקודמת עוד רצה מחזירה את אותו job_id, ולא מחויבת פעמיים.

POST/v1/jobs
body=$(jq -cn '{
  source: {
    id: 123,
    title: "חופשה במינכן",
    content_html: "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
    existing_link_ids: [67]
  },
  targets: [{id: 45, title: "מלונות במינכן", description: "המלצות על מלונות במינכן לפי שכונות"}],
  options: {max_links: 10}
}')
job_id=$(siblinks_call POST /v1/jobs "$body" | jq -r .job_id)
echo "$job_id"
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
job = call("POST", "/v1/jobs", {
    "source": {
        "id": 123,
        "title": "חופשה במינכן",
        "content_html": "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
        "existing_link_ids": [67],
    },
    "targets": [
        {"id": 45, "title": "מלונות במינכן",
         "description": "המלצות על מלונות במינכן לפי שכונות"},
    ],
    "options": {"max_links": 10},
})
job_id = job["job_id"]
print(job_id)
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
const job = await call('POST', '/v1/jobs', {
  source: {
    id: 123,
    title: 'חופשה במינכן',
    content_html: '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
    existing_link_ids: [67],
  },
  targets: [
    { id: 45, title: 'מלונות במינכן', description: 'המלצות על מלונות במינכן לפי שכונות' },
  ],
  options: { max_links: 10 },
});
const jobId = job.job_id;
console.log(jobId);
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
$job = siblinks_call(
	'POST',
	'/v1/jobs',
	array(
		'source'  => array(
			'id'                => 123,
			'title'             => 'חופשה במינכן',
			'content_html'      => '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
			'existing_link_ids' => array( 67 ),
		),
		'targets' => array(
			array(
				'id'          => 45,
				'title'       => 'מלונות במינכן',
				'description' => 'המלצות על מלונות במינכן לפי שכונות',
			),
		),
		'options' => array( 'max_links' => 10 ),
	)
);
$job_id = $job['job_id'];
echo $job_id . "\n";
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
$job = $client->call(
	'POST',
	'/v1/jobs',
	array(
		'source'  => array(
			'id'                => 123,
			'title'             => 'חופשה במינכן',
			'content_html'      => '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
			'existing_link_ids' => array( 67 ),
		),
		'targets' => array(
			array(
				'id'          => 45,
				'title'       => 'מלונות במינכן',
				'description' => 'המלצות על מלונות במינכן לפי שכונות',
			),
		),
		'options' => array( 'max_links' => 10 ),
	)
);
$job_id = $job['job_id'];
echo $job_id . "\n";
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
JsonNode job = call("POST", "/v1/jobs", Map.of(
        "source", Map.of(
                "id", 123,
                "title", "חופשה במינכן",
                "content_html", "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
                "existing_link_ids", List.of(67)),
        "targets", List.of(Map.of(
                "id", 45,
                "title", "מלונות במינכן",
                "description", "המלצות על מלונות במינכן לפי שכונות")),
        "options", Map.of("max_links", 10)));
String jobId = job.get("job_id").asText();
System.out.println(jobId);
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
JsonNode job = await SibLinks.Call("POST", "/v1/jobs", new
{
    source = new
    {
        id = 123,
        title = "חופשה במינכן",
        content_html = "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
        existing_link_ids = new[] { 67 },
    },
    targets = new[]
    {
        new { id = 45, title = "מלונות במינכן", description = "המלצות על מלונות במינכן לפי שכונות" },
    },
    options = new { max_links = 10 },
});
string jobId = job["job_id"]!.GetValue<string>();
Console.WriteLine(jobId);
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
job, err := call("POST", "/v1/jobs", map[string]any{
	"source": map[string]any{
		"id":                123,
		"title":             "חופשה במינכן",
		"content_html":      "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
		"existing_link_ids": []int{67},
	},
	"targets": []map[string]any{
		{"id": 45, "title": "מלונות במינכן", "description": "המלצות על מלונות במינכן לפי שכונות"},
	},
	"options": map[string]any{"max_links": 10},
})
if err != nil {
	return err
}
jobID := job["job_id"].(string)
fmt.Println(jobID)
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
job = call("POST", "/v1/jobs", {
  source: {
    id: 123,
    title: "חופשה במינכן",
    content_html: "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
    existing_link_ids: [67]
  },
  targets: [
    { id: 45, title: "מלונות במינכן", description: "המלצות על מלונות במינכן לפי שכונות" }
  ],
  options: { max_links: 10 }
})
job_id = job["job_id"]
puts job_id
Output
job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70
Response
{
  "job_id": "job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70",
  "status": "queued",
  "credits_remaining": 86
}
API Reference

קבלת בדיקה

GET/v1/jobs/{job_id}

מחזיר את הסטטוס של הבדיקה, ואת ההצעות כשהיא מסתיימת. שואלים כל 3 שניות עד done או failed.

פרמטרים בנתיב

תשובה

  • job_idstring

    מזהה הבדיקה.

  • statusstring

    queued או processing: ממשיכים לשאול. done או failed: סיום. בקישורים אל עמוד יש גם awaiting.

  • source_idinteger

    העמוד שנבדק.

  • suggestionsobject[]

    רק ב־done. רשימה של אובייקטי הצעה.

  • summary.quality_checkedboolean

    רק ב־done. true כשבדיקת האיכות הסופית של ההצעות רצה. false: ההצעות פחות מסוננות.

  • credits_remaininginteger | null

    רק ב־done. היתרה אחרי הבדיקה.

  • error.codestring

    רק ב־failed. ראו סיבות לבדיקה שנכשלה.

GET/v1/jobs/{job_id}
res=$(siblinks_call GET "/v1/jobs/$job_id")
jq -r '.status' <<<"$res"
jq -r '.suggestions[]? | "\(.target_id) \(.anchor_hint) \(.strength)"' <<<"$res"
Output
done
45 מלונות טובים במינכן high
res = call("GET", f"/v1/jobs/{job_id}")
if res["status"] == "done":
    for s in res["suggestions"]:
        print(s["target_id"], s["anchor_hint"], s["strength"])
Output
45 מלונות טובים במינכן high
const res = await call('GET', `/v1/jobs/${jobId}`);
if (res.status === 'done') {
  for (const s of res.suggestions) console.log(s.target_id, s.anchor_hint, s.strength);
}
Output
45 מלונות טובים במינכן high
$res = siblinks_call( 'GET', '/v1/jobs/' . $job_id );
if ( 'done' === $res['status'] ) {
	foreach ( $res['suggestions'] as $s ) {
		echo $s['target_id'] . ' ' . $s['anchor_hint'] . "\n";
	}
}
Output
45 מלונות טובים במינכן
$res = $client->call( 'GET', '/v1/jobs/' . $job_id );
if ( 'done' === $res['status'] ) {
	foreach ( $res['suggestions'] as $s ) {
		echo $s['target_id'] . ' ' . $s['anchor_hint'] . "\n";
	}
}
Output
45 מלונות טובים במינכן
JsonNode res = call("GET", "/v1/jobs/" + jobId, null);
if (res.get("status").asText().equals("done")) {
    for (JsonNode s : res.path("suggestions")) {
        System.out.println(s.get("target_id") + " " + s.get("anchor_hint").asText());
    }
}
Output
45 מלונות טובים במינכן
JsonNode res = await SibLinks.Call("GET", $"/v1/jobs/{jobId}");
if (res["status"]!.GetValue<string>() == "done")
{
    foreach (JsonNode? s in res["suggestions"]!.AsArray())
    {
        Console.WriteLine($"{s!["target_id"]} {s["anchor_hint"]}");
    }
}
Output
45 מלונות טובים במינכן
res, err := call("GET", "/v1/jobs/"+jobID, nil)
if err != nil {
	return err
}
if res["status"] == "done" {
	for _, item := range res["suggestions"].([]any) {
		s := item.(map[string]any)
		fmt.Println(s["target_id"], s["anchor_hint"], s["strength"])
	}
}
Output
45 מלונות טובים במינכן high
res = call("GET", "/v1/jobs/#{job_id}")
if res["status"] == "done"
  res["suggestions"].each { |s| puts "#{s['target_id']} #{s['anchor_hint']}" }
end
Output
45 מלונות טובים במינכן
Response
{
  "job_id": "job_6f1c0e2a9b8d4c7e8f1a2b3c4d5e6f70",
  "status": "done",
  "source_id": 123,
  "suggestions": [
    {
      "target_id": 45,
      "sentence": "יש הרבה מלונות טובים במינכן ליד התחנה.",
      "paragraph_index": 0,
      "sentence_index": 0,
      "anchor_hint": "מלונות טובים במינכן",
      "strength": "high",
      "reason": "אותה עיר: מינכן"
    }
  ],
  "summary": {"quality_checked": true},
  "credits_remaining": 86
}
API Reference

אישור קבלה

POST/v1/jobs/{job_id}/ack

מוחק בדיקה שהסתיימה מהשרת, אחרי ששמרתם את התוצאה. הגוף ריק או {}.

תשובות

תשובהמשמעות
200נמחקה.
409 job_openהבדיקה עוד רצה. היא לא נמחקת, וממשיכה להיספר ביתרה עד שתסתיים.
404 job_not_foundכבר נמחקה, או שאינה של האתר הזה.

בקישורים אל עמוד, ack על בדיקה שמחכה לשלב 2 מבטל אותה בלי חיוב.

POST/v1/jobs/{job_id}/ack
siblinks_call POST "/v1/jobs/$job_id/ack" '{}' | jq -c .
Output
{"ok":true}
res = call("POST", f"/v1/jobs/{job_id}/ack", {})
print(res)
Output
{'ok': True}
const ack = await call('POST', `/v1/jobs/${jobId}/ack`, {});
console.log(ack);
Output
{ ok: true }
$ack = siblinks_call( 'POST', '/v1/jobs/' . $job_id . '/ack', array() );
echo json_encode( $ack ) . "\n";
Output
{"ok":true}
$ack = $client->call( 'POST', '/v1/jobs/' . $job_id . '/ack', array() );
echo json_encode( $ack ) . "\n";
Output
{"ok":true}
JsonNode ack = call("POST", "/v1/jobs/" + jobId + "/ack", Map.of());
System.out.println(ack);
Output
{"ok":true}
JsonNode ack = await SibLinks.Call("POST", $"/v1/jobs/{jobId}/ack", new { });
Console.WriteLine(ack.ToJsonString());
Output
{"ok":true}
ack, err := call("POST", "/v1/jobs/"+jobID+"/ack", map[string]any{})
if err != nil {
	return err
}
fmt.Println(ack)
Output
map[ok:true]
ack = call("POST", "/v1/jobs/#{job_id}/ack", {})
p ack
Output
{"ok"=>true}
Response
{"ok": true}
API Reference

פרטי האתר והיתרה

GET/v1/account

מחזיר את פרטי האתר והיתרה. מתאים לכפתור "בדיקת חיבור": אם הקריאה מצליחה והחתימה של התשובה תקינה, ה־Site ID וה־Secret נכונים.

תשובה

  • site_idstring

    מזהה האתר.

  • namestring

    שם האתר, כפי שנקבע באזור הלקוחות.

  • versionstring

    גרסת השרת.

  • planobject

    מגבלות ויתרה.

    השדות של plan
    • max_targetsinteger

      כמה עמודי יעד מותר לשלוח בבדיקה אחת.

    • credits_remaininginteger | null

      כמה בדיקות אפשר עוד להתחיל. בדיקות שרצות כבר נספרות כמשומשות. null אומר שאין הגבלה.

    • billing"credits" | "monthly"

      חבילות בדיקות של החשבון, או מכסה חודשית.

    • monthly_checksinteger | null

      המכסה החודשית, רק כש־billing הוא monthly.

    • portal_urlstring

      כתובת לרכישת בדיקות נוספות, או מחרוזת ריקה.

GET/v1/account
siblinks_call GET /v1/account | jq '.plan.credits_remaining'
Output
87
account = call("GET", "/v1/account")
print(account["plan"]["credits_remaining"])
Output
87
const account = await call('GET', '/v1/account');
console.log(account.plan.credits_remaining);
Output
87
$account = siblinks_call( 'GET', '/v1/account' );
echo $account['plan']['credits_remaining'] . "\n";
Output
87
$account = $client->call( 'GET', '/v1/account' );
echo $account['plan']['credits_remaining'] . "\n";
Output
87
JsonNode account = call("GET", "/v1/account", null);
System.out.println(account.path("plan").path("credits_remaining"));
Output
87
JsonNode account = await SibLinks.Call("GET", "/v1/account");
Console.WriteLine(account["plan"]?["credits_remaining"]);
Output
87
account, err := call("GET", "/v1/account", nil)
if err != nil {
	return err
}
fmt.Println(account["plan"].(map[string]any)["credits_remaining"])
Output
87
account = call("GET", "/v1/account")
puts account.dig("plan", "credits_remaining")
Output
87
Response
{
  "site_id": "site_ab12cd34ef56",
  "name": "האתר שלי",
  "version": "0.10.0",
  "plan": {
    "max_targets": 1000,
    "monthly_checks": null,
    "credits_remaining": 87,
    "billing": "credits",
    "portal_url": "https://app.siblinks.co.il"
  }
}
API Reference

זמינות השירות

GET/v1/health

בודק שהשירות זמין. זו הקריאה היחידה בלי חתימה, ולכן אפשר להריץ אותה גם מהטרמינל.

היא לא בודקת את פרטי הגישה. לזה משתמשים בפרטי האתר והיתרה.

תשובה

  • okboolean

    תמיד true כשהשירות עונה.

  • versionstring

    גרסת השרת.

GET/v1/health
curl https://api.siblinks.co.il/v1/health
Response200
{"ok": true, "version": "0.10.0"}
קישורים אל עמוד

שלב 1: בחירת עמודים

POST/v1/jobs

הבדיקה הרגילה עונה על "לאן העמוד הזה צריך לקשר". המצב הזה עונה על השאלה ההפוכה: אילו עמודים קיימים צריכים לקשר אל עמוד מסוים, למשל עמוד חדש.

זו בדיקה אחת בשני שלבים, והיא מחויבת פעם אחת, כשהיא מסתיימת. בשלב 1 שולחים תקצירים בלבד, והשרת בוחר עד 20 עמודים שכדאי לקרוא.

גוף הבקשה

  • mode"inbound"חובה

    מסמן שזו בדיקה של קישורים אל עמוד.

  • targetobjectחובה

    העמוד שרוצים לקשר אליו, באותם שדות כמו עמוד יעד.

  • candidatesobject[]חובה

    עמודים באתר שאולי יקשרו אליו, באותם שדות. עד plan.max_targets, ולא יותר מ־1000.

  • optionsobject

    max_links ו־exclude_ids, כמו בבדיקה רגילה.

תשובה

  • status"awaiting" | "failed"

    awaiting: מחכה לתוכן של העמודים שנבחרו. failed עם no_candidates: אין עמוד מתאים, ולא מחויב.

  • sourcesinteger[]

    עד 20 מזהים, הקרובים ביותר קודם. את התוכן שלהם שולחים בשלב 2.

POST/v1/jobs
body=$(jq -cn '{
  mode: "inbound",
  target: {id: 57, title: "מלונות במינכן", description: "…"},
  candidates: [
    {id: 12, title: "חופשה בבוואריה", description: "…"},
    {id: 19, title: "מה לעשות במינכן", description: "…"}
  ]
}')
job=$(siblinks_call POST /v1/jobs "$body")
jq -c '.sources' <<<"$job"
Output
[19,12]
job = call("POST", "/v1/jobs", {
    "mode": "inbound",
    "target": {"id": 57, "title": "מלונות במינכן", "description": "…"},
    "candidates": [
        {"id": 12, "title": "חופשה בבוואריה", "description": "…"},
        {"id": 19, "title": "מה לעשות במינכן", "description": "…"},
    ],
})
print("pages to send:", job.get("sources"))
Output
pages to send: [19, 12]
const job = await call('POST', '/v1/jobs', {
  mode: 'inbound',
  target: { id: 57, title: 'מלונות במינכן', description: '…' },
  candidates: [
    { id: 12, title: 'חופשה בבוואריה', description: '…' },
    { id: 19, title: 'מה לעשות במינכן', description: '…' },
  ],
});
console.log('pages to send:', job.sources);
Output
pages to send: [ 19, 12 ]
$job = siblinks_call(
	'POST',
	'/v1/jobs',
	array(
		'mode'       => 'inbound',
		'target'     => array( 'id' => 57, 'title' => 'מלונות במינכן', 'description' => '…' ),
		'candidates' => array(
			array( 'id' => 12, 'title' => 'חופשה בבוואריה', 'description' => '…' ),
			array( 'id' => 19, 'title' => 'מה לעשות במינכן', 'description' => '…' ),
		),
	)
);
echo 'pages to send: ' . implode( ', ', $job['sources'] ?? array() ) . "\n";
Output
pages to send: 19, 12
$job = $client->call(
	'POST',
	'/v1/jobs',
	array(
		'mode'       => 'inbound',
		'target'     => array( 'id' => 57, 'title' => 'מלונות במינכן', 'description' => '…' ),
		'candidates' => array(
			array( 'id' => 12, 'title' => 'חופשה בבוואריה', 'description' => '…' ),
			array( 'id' => 19, 'title' => 'מה לעשות במינכן', 'description' => '…' ),
		),
	)
);
echo 'pages to send: ' . implode( ', ', $job['sources'] ?? array() ) . "\n";
Output
pages to send: 19, 12
JsonNode job = call("POST", "/v1/jobs", Map.of(
        "mode", "inbound",
        "target", Map.of("id", 57, "title", "מלונות במינכן", "description", "…"),
        "candidates", List.of(
                Map.of("id", 12, "title", "חופשה בבוואריה", "description", "…"),
                Map.of("id", 19, "title", "מה לעשות במינכן", "description", "…"))));
System.out.println("pages to send: " + job.path("sources"));
Output
pages to send: [19,12]
JsonNode job = await SibLinks.Call("POST", "/v1/jobs", new
{
    mode = "inbound",
    target = new { id = 57, title = "מלונות במינכן", description = "…" },
    candidates = new[]
    {
        new { id = 12, title = "חופשה בבוואריה", description = "…" },
        new { id = 19, title = "מה לעשות במינכן", description = "…" },
    },
});
Console.WriteLine($"pages to send: {job["sources"]?.ToJsonString()}");
Output
pages to send: [19,12]
job, err := call("POST", "/v1/jobs", map[string]any{
	"mode":   "inbound",
	"target": map[string]any{"id": 57, "title": "מלונות במינכן", "description": "…"},
	"candidates": []map[string]any{
		{"id": 12, "title": "חופשה בבוואריה", "description": "…"},
		{"id": 19, "title": "מה לעשות במינכן", "description": "…"},
	},
})
if err != nil {
	return err
}
fmt.Println("pages to send:", job["sources"])
Output
pages to send: [19 12]
job = call("POST", "/v1/jobs", {
  mode: "inbound",
  target: { id: 57, title: "מלונות במינכן", description: "…" },
  candidates: [
    { id: 12, title: "חופשה בבוואריה", description: "…" },
    { id: 19, title: "מה לעשות במינכן", description: "…" }
  ]
})
puts "pages to send: #{job['sources'].inspect}"
Output
pages to send: [19, 12]
Response
{
  "job_id": "job_9a0b1c2d3e4f5061728394a5b6c7d8e9",
  "status": "awaiting",
  "sources": [19, 12],
  "credits_remaining": 85
}
קישורים אל עמוד

שלב 2: שליחת תוכן

POST/v1/jobs/{job_id}/sources

שולחים את התוכן של העמודים שנבחרו בשלב 1. משם ממשיכים כמו בבדיקה רגילה: קבלת בדיקה עד done, ואז אישור קבלה.

גוף הבקשה

  • sourcesobject[]חובה

    רק מזהים מתוך sources של שלב 1, כל אחד פעם אחת. אפשר לשלוח חלק מהם.

    השדות של כל עמוד
    • idintegerחובה

      מזהה העמוד.

    • content_htmlstringחובה

      אזור התוכן של העמוד.

    • titlestringמומלץ

      כותרת העמוד.

חשוב לדעת

  • שולחים תוך 10 דקות. אחרי זה הבדיקה נכשלת עם expired, ולא מחויבת.
  • 409 job_not_ready עם Retry-After: 5: הבחירה של שלב 1 עוד רצה. מחכים ושולחים שוב.
  • 409 job_not_awaiting: הבדיקה כבר לא מחכה לתוכן. בודקים את הסטטוס.
  • בתוצאה, לכל הצעה יש source_id: העמוד שצריך לערוך. target_id הוא העמוד שחיפשתם אליו קישורים. כל עמוד מקבל לכל היותר הצעה אחת.
POST/v1/jobs/{job_id}/sources
body=$(jq -cn '{sources: [
  {id: 19, title: "מה לעשות במינכן", content_html: "<p>…</p>"},
  {id: 12, title: "חופשה בבוואריה", content_html: "<p>…</p>"}
]}')
siblinks_call POST "/v1/jobs/$(jq -r .job_id <<<"$job")/sources" "$body" | jq -r .status
Output
queued
step2 = call("POST", f"/v1/jobs/{job['job_id']}/sources", {
    "sources": [
        {"id": 19, "title": "מה לעשות במינכן", "content_html": "<p>…</p>"},
        {"id": 12, "title": "חופשה בבוואריה", "content_html": "<p>…</p>"},
    ],
})
print(step2["status"])
Output
queued
const step2 = await call('POST', `/v1/jobs/${job.job_id}/sources`, {
  sources: [
    { id: 19, title: 'מה לעשות במינכן', content_html: '<p>…</p>' },
    { id: 12, title: 'חופשה בבוואריה', content_html: '<p>…</p>' },
  ],
});
console.log(step2.status);
Output
queued
$step2 = siblinks_call(
	'POST',
	'/v1/jobs/' . $job['job_id'] . '/sources',
	array(
		'sources' => array(
			array( 'id' => 19, 'title' => 'מה לעשות במינכן', 'content_html' => '<p>…</p>' ),
			array( 'id' => 12, 'title' => 'חופשה בבוואריה', 'content_html' => '<p>…</p>' ),
		),
	)
);
echo $step2['status'] . "\n";
Output
queued
$step2 = $client->call(
	'POST',
	'/v1/jobs/' . $job['job_id'] . '/sources',
	array(
		'sources' => array(
			array( 'id' => 19, 'title' => 'מה לעשות במינכן', 'content_html' => '<p>…</p>' ),
			array( 'id' => 12, 'title' => 'חופשה בבוואריה', 'content_html' => '<p>…</p>' ),
		),
	)
);
echo $step2['status'] . "\n";
Output
queued
JsonNode step2 = call("POST", "/v1/jobs/" + job.get("job_id").asText() + "/sources", Map.of(
        "sources", List.of(
                Map.of("id", 19, "title", "מה לעשות במינכן", "content_html", "<p>…</p>"),
                Map.of("id", 12, "title", "חופשה בבוואריה", "content_html", "<p>…</p>"))));
System.out.println(step2.get("status").asText());
Output
queued
JsonNode step2 = await SibLinks.Call("POST", $"/v1/jobs/{job["job_id"]}/sources", new
{
    sources = new[]
    {
        new { id = 19, title = "מה לעשות במינכן", content_html = "<p>…</p>" },
        new { id = 12, title = "חופשה בבוואריה", content_html = "<p>…</p>" },
    },
});
Console.WriteLine(step2["status"]);
Output
queued
step2, err := call("POST", "/v1/jobs/"+job["job_id"].(string)+"/sources", map[string]any{
	"sources": []map[string]any{
		{"id": 19, "title": "מה לעשות במינכן", "content_html": "<p>…</p>"},
		{"id": 12, "title": "חופשה בבוואריה", "content_html": "<p>…</p>"},
	},
})
if err != nil {
	return err
}
fmt.Println(step2["status"])
Output
queued
step2 = call("POST", "/v1/jobs/#{job['job_id']}/sources", {
  sources: [
    { id: 19, title: "מה לעשות במינכן", content_html: "<p>…</p>" },
    { id: 12, title: "חופשה בבוואריה", content_html: "<p>…</p>" }
  ]
})
puts step2["status"]
Output
queued
Response
{"job_id": "job_9a0b1c2d3e4f5061728394a5b6c7d8e9", "status": "queued"}
משאבים

דוגמאות מלאות

תוכנית שלמה, מוכנה להרצה: בדיקת חיבור, שליחת בדיקה, המתנה, אישור קבלה והדפסת ההצעות. כל תוכנית חותמת על הבקשות ומאמתת את חתימת התשובות.

כל קוד בתיעוד נבדקכל התוכניות, וכל דוגמאות הקוד בעמודים, הורצו מקצה לקצה מול מימוש החתימות של השרת. הפלט שמוצג מתחת לכל דוגמה הוא הפלט שלה מההרצה, עם הנתונים שבדוגמאות התשובה. כל תוכנית גם דוחה תשובה עם חתימה מזויפת.

דרישות והרצה

פרטי הגישה נקראים ממשתני הסביבה SIBLINKS_SITE_ID ו־SIBLINKS_SECRET.

שפהדרישותהרצה
cURLbash, curl, openssl, jqbash siblinks-client.sh
PythonPython 3.9+, pip install requestspython siblinks_client.py
Node.jsNode.js 18+, בלי תלויותnode siblinks-client.mjs
PHPPHP 8.0+, הרחבת curlphp siblinks-client.php
PHP · GuzzlePHP 8.0+, composer require guzzlehttp/guzzlephp siblinks-client-guzzle.php
JavaJava 17+, Jackson (jackson-databind)java -cp 'lib/*' SibLinksClient.java
C#.NET 6+, בלי חבילותdotnet run
GoGo 1.18+, ספרייה סטנדרטיתgo run main.go
RubyRuby 3.0+, ספרייה סטנדרטיתruby siblinks_client.rb

הקוד

siblinks-client.sh
#!/usr/bin/env bash
# SibLinks API from the shell (bash, curl, openssl, jq).
# Note: openssl receives the secret as an argument, so other users on the same machine can see it
# in the process list. Use this for testing; in production use one of the language clients.
set -euo pipefail
BASE_URL="${SIBLINKS_BASE_URL:-https://api.siblinks.co.il}"

hmac_hex() { openssl dgst -sha256 -hmac "$SIBLINKS_SECRET" -r | cut -d' ' -f1; }

# siblinks_call METHOD PATH [BODY_JSON]: prints the verified response body.
siblinks_call() {
  local method="$1" path="$2" body="${3-}"
  local ts nonce sig tmp status expected got
  ts=$(date +%s)
  nonce=$(openssl rand -hex 16)
  sig=$(printf '%s\n%s\n%s\n%s\n%s' "$ts" "$method" "$path" \
    "$(printf '%s' "$body" | openssl dgst -sha256 -r | cut -d' ' -f1)" "$nonce" | hmac_hex)

  tmp=$(mktemp -d)
  local args=(-sS -X "$method" "$BASE_URL$path" --compressed -D "$tmp/headers" -o "$tmp/body" -w '%{http_code}'
    -H "X-Site-Id: $SIBLINKS_SITE_ID" -H "X-Timestamp: $ts" -H "X-Nonce: $nonce" -H "X-Signature: $sig")
  if [ -n "$body" ]; then
    args+=(-H "Content-Type: application/json" --data-binary "$body")
  fi
  status=$(curl "${args[@]}")

  expected=$(printf 'response\n%s\n%s\n%s' "$sig" "$status" \
    "$(openssl dgst -sha256 -r < "$tmp/body" | cut -d' ' -f1)" | hmac_hex)
  got=$( (grep -i '^x-siblinks-signature:' "$tmp/headers" || true) | tail -1 | cut -d: -f2 | tr -d ' \r' | tr 'A-F' 'a-f')
  if [ "$status" -lt 400 ] && [ "$expected" != "$got" ]; then
    echo "unsigned_response" >&2; rm -rf "$tmp"; return 1 # never trust it
  fi
  if [ "$status" -ge 400 ]; then
    echo "error $status $(jq -r '.error.code // "unknown"' "$tmp/body")" >&2; rm -rf "$tmp"; return 1
  fi
  cat "$tmp/body"
  rm -rf "$tmp"
}

siblinks_call GET /v1/account | jq -c '.plan'

body=$(jq -cn '{
  source: {id: 123, title: "חופשה במינכן", content_html: "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>"},
  targets: [{id: 45, title: "מלונות במינכן", description: "המלצות על מלונות במינכן"}],
  options: {max_links: 10}
}')
job_id=$(siblinks_call POST /v1/jobs "$body" | jq -r .job_id)

for _ in $(seq 100); do
  sleep 3
  res=$(siblinks_call GET "/v1/jobs/$job_id")
  status=$(jq -r .status <<<"$res")
  if [ "$status" = done ] || [ "$status" = failed ]; then break; fi
done
siblinks_call POST "/v1/jobs/$job_id/ack" '{}' > /dev/null
jq -r '.suggestions[]? | "\(.target_id) \(.anchor_hint) \(.strength)"' <<<"$res"
Output
{"max_targets":1000,"monthly_checks":null,"credits_remaining":87,"billing":"credits","portal_url":"https://app.siblinks.co.il"}
45 מלונות טובים במינכן high
siblinks_client.py
import hashlib
import hmac
import json
import os
import secrets
import time

import requests

BASE_URL = os.environ.get("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
SITE_ID = os.environ["SIBLINKS_SITE_ID"]
SECRET = os.environ["SIBLINKS_SECRET"]


class SibLinksError(Exception):
    def __init__(self, status, code):
        super().__init__(f"{status} {code}")
        self.status, self.code = status, code


def _hmac(text: str) -> str:
    return hmac.new(SECRET.encode("utf-8"), text.encode("utf-8"), hashlib.sha256).hexdigest()


def call(method: str, path: str, body=None):
    raw = b"" if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
    ts = str(int(time.time()))
    nonce = secrets.token_hex(16)
    signature = _hmac(f"{ts}\n{method}\n{path}\n{hashlib.sha256(raw).hexdigest()}\n{nonce}")
    headers = {"X-Site-Id": SITE_ID, "X-Timestamp": ts, "X-Nonce": nonce, "X-Signature": signature}
    if body is not None:
        headers["Content-Type"] = "application/json"
    r = requests.request(method, BASE_URL + path, data=raw if body is not None else None,
                         headers=headers, timeout=30)
    expected = _hmac(f"response\n{signature}\n{r.status_code}\n{hashlib.sha256(r.content).hexdigest()}")
    signed = hmac.compare_digest(expected, r.headers.get("X-SibLinks-Signature", "").lower())
    if r.status_code < 400 and not signed:
        raise SibLinksError(r.status_code, "unsigned_response")  # never trust it
    data = r.json()
    if r.status_code >= 400:
        raise SibLinksError(r.status_code, (data.get("error") or {}).get("code", "unknown"))
    return data


def suggest_links(source: dict, targets: list) -> list:
    job = call("POST", "/v1/jobs", {"source": source, "targets": targets, "options": {"max_links": 10}})
    job_id = job["job_id"]
    deadline = time.time() + 300
    while time.time() < deadline:
        time.sleep(3)
        res = call("GET", f"/v1/jobs/{job_id}")
        if res["status"] in ("done", "failed"):
            call("POST", f"/v1/jobs/{job_id}/ack", {})
            if res["status"] == "failed":
                raise SibLinksError(200, res["error"]["code"])
            return res["suggestions"]
    raise TimeoutError(job_id)


if __name__ == "__main__":
    print(call("GET", "/v1/account")["plan"])
    suggestions = suggest_links(
        {"id": 123, "title": "חופשה במינכן", "content_html": "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>"},
        [{"id": 45, "title": "מלונות במינכן", "description": "המלצות על מלונות במינכן"}],
    )
    for s in suggestions:
        print(s["target_id"], s["anchor_hint"], s["strength"])
Output
{'max_targets': 1000, 'monthly_checks': None, 'credits_remaining': 87, 'billing': 'credits', 'portal_url': 'https://app.siblinks.co.il'}
45 מלונות טובים במינכן high
siblinks-client.mjs
// SibLinks API client example (Node.js 18+, no dependencies).
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';

const BASE_URL = process.env.SIBLINKS_BASE_URL || 'https://api.siblinks.co.il';
const SITE_ID = process.env.SIBLINKS_SITE_ID;
const SECRET = process.env.SIBLINKS_SECRET;

const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
const hmac = (text) => createHmac('sha256', SECRET).update(text, 'utf8').digest('hex');

export async function call(method, path, body) {
  const raw = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body), 'utf8');
  const ts = String(Math.floor(Date.now() / 1000));
  const nonce = randomBytes(16).toString('hex');
  const signature = hmac(`${ts}\n${method}\n${path}\n${sha256(raw)}\n${nonce}`);
  const headers = { 'X-Site-Id': SITE_ID, 'X-Timestamp': ts, 'X-Nonce': nonce, 'X-Signature': signature };
  if (body !== undefined) headers['Content-Type'] = 'application/json';

  const res = await fetch(BASE_URL + path, { method, headers, body: body === undefined ? undefined : raw });
  const resBody = Buffer.from(await res.arrayBuffer());
  const expected = Buffer.from(hmac(`response\n${signature}\n${res.status}\n${sha256(resBody)}`));
  const got = Buffer.from((res.headers.get('x-siblinks-signature') || '').toLowerCase());
  const signedOk = got.length === expected.length && timingSafeEqual(got, expected);
  if (res.status < 400 && !signedOk) throw new Error('unsigned_response'); // never trust it

  const data = JSON.parse(resBody.toString('utf8'));
  if (res.status >= 400) throw Object.assign(new Error(data.error?.code || 'unknown'), { status: res.status });
  return data;
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function suggestLinks(source, targets) {
  const job = await call('POST', '/v1/jobs', { source, targets, options: { max_links: 10 } });
  const deadline = Date.now() + 300_000;
  while (Date.now() < deadline) {
    await sleep(3000);
    const res = await call('GET', `/v1/jobs/${job.job_id}`);
    if (res.status === 'done' || res.status === 'failed') {
      await call('POST', `/v1/jobs/${job.job_id}/ack`, {});
      if (res.status === 'failed') throw new Error(res.error.code);
      return res.suggestions;
    }
  }
  throw new Error(`timeout ${job.job_id}`);
}

const account = await call('GET', '/v1/account');
console.log('credits_remaining:', account.plan.credits_remaining);
const suggestions = await suggestLinks(
  { id: 123, title: 'חופשה במינכן', content_html: '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>' },
  [{ id: 45, title: 'מלונות במינכן', description: 'המלצות על מלונות במינכן' }],
);
for (const s of suggestions) console.log(s.target_id, s.anchor_hint, s.strength);
Output
credits_remaining: 87
45 מלונות טובים במינכן high
siblinks-client.php
<?php
// SibLinks API client example (PHP 8, curl extension).

$base_url = getenv( 'SIBLINKS_BASE_URL' ) ?: 'https://api.siblinks.co.il';
$site_id  = getenv( 'SIBLINKS_SITE_ID' );
$secret   = getenv( 'SIBLINKS_SECRET' );

function siblinks_call( string $method, string $path, ?array $body = null ): array {
	global $base_url, $site_id, $secret;

	$raw   = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE );
	$ts    = (string) time();
	$nonce = bin2hex( random_bytes( 16 ) );
	$sig   = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $secret );

	$headers = array( "X-Site-Id: {$site_id}", "X-Timestamp: {$ts}", "X-Nonce: {$nonce}", "X-Signature: {$sig}" );
	if ( null !== $body ) {
		$headers[] = 'Content-Type: application/json';
	}

	$resp_sig = '';
	$ch       = curl_init( $base_url . $path );
	curl_setopt_array(
		$ch,
		array(
			CURLOPT_CUSTOMREQUEST  => $method,
			CURLOPT_HTTPHEADER     => $headers,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING       => '', // decode gzip/br if a proxy compressed the response
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_HEADERFUNCTION => function ( $ch, $line ) use ( &$resp_sig ) {
				if ( 0 === stripos( $line, 'X-SibLinks-Signature:' ) ) {
					$resp_sig = strtolower( trim( substr( $line, 21 ) ) );
				}
				return strlen( $line );
			},
		)
	);
	if ( null !== $body ) {
		curl_setopt( $ch, CURLOPT_POSTFIELDS, $raw );
	}
	$resp   = curl_exec( $ch );
	$status = (int) curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
	if ( false === $resp ) {
		throw new RuntimeException( 'connection_failed: ' . curl_error( $ch ) );
	}

	$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $secret );
	if ( $status < 400 && ! hash_equals( $expected, $resp_sig ) ) {
		throw new RuntimeException( 'unsigned_response' ); // never trust it
	}
	$data = json_decode( $resp, true );
	if ( $status >= 400 ) {
		throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
	}
	return $data;
}

$plan = siblinks_call( 'GET', '/v1/account' )['plan'];
echo 'credits_remaining: ' . var_export( $plan['credits_remaining'], true ) . "\n";

$job = siblinks_call(
	'POST',
	'/v1/jobs',
	array(
		'source'  => array(
			'id'           => 123,
			'title'        => 'חופשה במינכן',
			'content_html' => '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
		),
		'targets' => array(
			array( 'id' => 45, 'title' => 'מלונות במינכן', 'description' => 'המלצות על מלונות במינכן' ),
		),
		'options' => array( 'max_links' => 10 ),
	)
);

$deadline = time() + 300;
do {
	sleep( 3 );
	$res = siblinks_call( 'GET', '/v1/jobs/' . $job['job_id'] );
} while ( ! in_array( $res['status'], array( 'done', 'failed' ), true ) && time() < $deadline );

siblinks_call( 'POST', '/v1/jobs/' . $job['job_id'] . '/ack', array() );
foreach ( $res['suggestions'] ?? array() as $s ) {
	echo $s['target_id'] . ' ' . $s['anchor_hint'] . ' ' . $s['strength'] . "\n";
}
Output
credits_remaining: 87
45 מלונות טובים במינכן high
siblinks-client-guzzle.php
<?php
// SibLinks API client example (PHP 8.0+, Guzzle 7: composer require guzzlehttp/guzzle).
require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client;

final class SibLinksClient {
	private Client $http;

	public function __construct( private string $site_id, private string $secret, string $base_url = 'https://api.siblinks.co.il' ) {
		$this->http = new Client(
			array(
				'base_uri'    => $base_url,
				'timeout'     => 30,
				'http_errors' => false, // errors are read from the JSON body below
			)
		);
	}

	public function call( string $method, string $path, ?array $body = null ): array {
		$raw   = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR );
		$ts    = (string) time();
		$nonce = bin2hex( random_bytes( 16 ) );
		$sig   = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $this->secret );

		$headers = array(
			'X-Site-Id'   => $this->site_id,
			'X-Timestamp' => $ts,
			'X-Nonce'     => $nonce,
			'X-Signature' => $sig,
		);
		if ( null !== $body ) {
			$headers['Content-Type'] = 'application/json';
		}

		$res    = $this->http->request( $method, $path, array( 'headers' => $headers, 'body' => $raw ) );
		$status = $res->getStatusCode();
		$resp   = (string) $res->getBody();

		$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $this->secret );
		if ( $status < 400 && ! hash_equals( $expected, strtolower( $res->getHeaderLine( 'X-SibLinks-Signature' ) ) ) ) {
			throw new RuntimeException( 'unsigned_response' ); // never trust it
		}
		$data = json_decode( $resp, true );
		if ( $status >= 400 ) {
			throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
		}
		return $data;
	}
}

$client = new SibLinksClient(
	getenv( 'SIBLINKS_SITE_ID' ),
	getenv( 'SIBLINKS_SECRET' ),
	getenv( 'SIBLINKS_BASE_URL' ) ?: 'https://api.siblinks.co.il'
);

echo 'credits_remaining: ' . var_export( $client->call( 'GET', '/v1/account' )['plan']['credits_remaining'], true ) . "\n";

$job = $client->call(
	'POST',
	'/v1/jobs',
	array(
		'source'  => array(
			'id'           => 123,
			'title'        => 'חופשה במינכן',
			'content_html' => '<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>',
		),
		'targets' => array(
			array( 'id' => 45, 'title' => 'מלונות במינכן', 'description' => 'המלצות על מלונות במינכן' ),
		),
		'options' => array( 'max_links' => 10 ),
	)
);

$deadline = time() + 300;
do {
	sleep( 3 );
	$res = $client->call( 'GET', '/v1/jobs/' . $job['job_id'] );
} while ( ! in_array( $res['status'], array( 'done', 'failed' ), true ) && time() < $deadline );

$client->call( 'POST', '/v1/jobs/' . $job['job_id'] . '/ack', array() );
foreach ( $res['suggestions'] ?? array() as $s ) {
	echo $s['target_id'] . ' ' . $s['anchor_hint'] . ' ' . $s['strength'] . "\n";
}
Output
credits_remaining: 87
45 מלונות טובים במינכן high
SibLinksClient.java
// SibLinks API client example (Java 17+, Jackson 2.x: com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SibLinksClient {
    static final String BASE_URL = Optional.ofNullable(System.getenv("SIBLINKS_BASE_URL")).orElse("https://api.siblinks.co.il");
    static final String SITE_ID = System.getenv("SIBLINKS_SITE_ID");
    static final String SECRET = System.getenv("SIBLINKS_SECRET");

    static final ObjectMapper JSON = new ObjectMapper();
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
    static final SecureRandom RANDOM = new SecureRandom();
    static final HexFormat HEX = HexFormat.of();

    static class SibLinksException extends Exception {
        final int status;
        final String code;

        SibLinksException(int status, String code) {
            super(status + " " + code);
            this.status = status;
            this.code = code;
        }
    }

    static String sha256(byte[] data) throws Exception {
        return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(data));
    }

    static String hmac(String message) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        return HEX.formatHex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
    }

    static JsonNode call(String method, String path, Object body) throws Exception {
        byte[] raw = body == null ? new byte[0] : JSON.writeValueAsBytes(body);
        String ts = Long.toString(System.currentTimeMillis() / 1000);
        byte[] nonceBytes = new byte[16];
        RANDOM.nextBytes(nonceBytes);
        String nonce = HEX.formatHex(nonceBytes);
        String signature = hmac(ts + "\n" + method + "\n" + path + "\n" + sha256(raw) + "\n" + nonce);

        HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(BASE_URL + path))
                .timeout(Duration.ofSeconds(30))
                .header("X-Site-Id", SITE_ID)
                .header("X-Timestamp", ts)
                .header("X-Nonce", nonce)
                .header("X-Signature", signature)
                .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(raw));
        if (body != null) {
            req.header("Content-Type", "application/json");
        }
        HttpResponse<byte[]> res = HTTP.send(req.build(), HttpResponse.BodyHandlers.ofByteArray());

        int status = res.statusCode();
        String expected = hmac("response\n" + signature + "\n" + status + "\n" + sha256(res.body()));
        String got = res.headers().firstValue("X-SibLinks-Signature").orElse("").toLowerCase(Locale.ROOT);
        boolean signed = MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), got.getBytes(StandardCharsets.UTF_8));
        if (status < 400 && !signed) {
            throw new SibLinksException(status, "unsigned_response"); // never trust it
        }
        JsonNode data = JSON.readTree(res.body());
        if (status >= 400) {
            throw new SibLinksException(status, data.path("error").path("code").asText("unknown"));
        }
        return data;
    }

    public static void main(String[] args) throws Exception {
        JsonNode account = call("GET", "/v1/account", null);
        System.out.println("credits_remaining: " + account.path("plan").path("credits_remaining"));

        JsonNode job = call("POST", "/v1/jobs", Map.of(
                "source", Map.of(
                        "id", 123,
                        "title", "חופשה במינכן",
                        "content_html", "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>"),
                "targets", List.of(Map.of(
                        "id", 45,
                        "title", "מלונות במינכן",
                        "description", "המלצות על מלונות במינכן")),
                "options", Map.of("max_links", 10)));
        String jobId = job.get("job_id").asText();

        JsonNode res = null;
        long deadline = System.currentTimeMillis() + 300_000;
        while (System.currentTimeMillis() < deadline) {
            Thread.sleep(3000);
            res = call("GET", "/v1/jobs/" + jobId, null);
            String status = res.get("status").asText();
            if (status.equals("done") || status.equals("failed")) {
                break;
            }
        }
        call("POST", "/v1/jobs/" + jobId + "/ack", Map.of());
        for (JsonNode s : res.path("suggestions")) {
            System.out.println(s.get("target_id") + " " + s.get("anchor_hint").asText() + " " + s.get("strength").asText());
        }
    }
}
Output
credits_remaining: 87
45 מלונות טובים במינכן high
Program.cs
// SibLinks API client example (.NET 6+, no extra packages).
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

public class SibLinksException : Exception
{
    public int Status { get; }
    public string Code { get; }

    public SibLinksException(int status, string code) : base($"{status} {code}")
    {
        Status = status;
        Code = code;
    }
}

public static class SibLinks
{
    static readonly string BaseUrl = Environment.GetEnvironmentVariable("SIBLINKS_BASE_URL") ?? "https://api.siblinks.co.il";
    static readonly string SiteId = Environment.GetEnvironmentVariable("SIBLINKS_SITE_ID")!;
    static readonly byte[] Secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SIBLINKS_SECRET")!);

    static readonly HttpClient Http = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All })
    {
        Timeout = TimeSpan.FromSeconds(30),
    };

    static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant();

    static string Hmac(string message) => Hex(HMACSHA256.HashData(Secret, Encoding.UTF8.GetBytes(message)));

    public static async Task<JsonNode> Call(string method, string path, object? body = null)
    {
        byte[] raw = body is null ? Array.Empty<byte>() : JsonSerializer.SerializeToUtf8Bytes(body);
        string ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        string nonce = Hex(RandomNumberGenerator.GetBytes(16));
        string signature = Hmac($"{ts}\n{method}\n{path}\n{Hex(SHA256.HashData(raw))}\n{nonce}");

        using var req = new HttpRequestMessage(new HttpMethod(method), BaseUrl + path);
        req.Headers.Add("X-Site-Id", SiteId);
        req.Headers.Add("X-Timestamp", ts);
        req.Headers.Add("X-Nonce", nonce);
        req.Headers.Add("X-Signature", signature);
        if (body is not null)
        {
            req.Content = new ByteArrayContent(raw);
            req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }

        using var res = await Http.SendAsync(req);
        byte[] resBody = await res.Content.ReadAsByteArrayAsync();
        int status = (int)res.StatusCode;

        string expected = Hmac($"response\n{signature}\n{status}\n{Hex(SHA256.HashData(resBody))}");
        string got = res.Headers.TryGetValues("X-SibLinks-Signature", out var values) ? values.First().ToLowerInvariant() : "";
        bool signed = CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(got));
        if (status < 400 && !signed)
        {
            throw new SibLinksException(status, "unsigned_response"); // never trust it
        }
        JsonNode data = JsonNode.Parse(resBody)!;
        if (status >= 400)
        {
            throw new SibLinksException(status, data["error"]?["code"]?.GetValue<string>() ?? "unknown");
        }
        return data;
    }
}

public static class Program
{
    public static async Task Main()
    {
        JsonNode account = await SibLinks.Call("GET", "/v1/account");
        Console.WriteLine($"credits_remaining: {account["plan"]?["credits_remaining"]}");

        JsonNode job = await SibLinks.Call("POST", "/v1/jobs", new
        {
            source = new
            {
                id = 123,
                title = "חופשה במינכן",
                content_html = "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
            },
            targets = new[]
            {
                new { id = 45, title = "מלונות במינכן", description = "המלצות על מלונות במינכן" },
            },
            options = new { max_links = 10 },
        });
        string jobId = job["job_id"]!.GetValue<string>();

        JsonNode? res = null;
        var deadline = DateTime.UtcNow.AddMinutes(5);
        while (DateTime.UtcNow < deadline)
        {
            await Task.Delay(3000);
            res = await SibLinks.Call("GET", $"/v1/jobs/{jobId}");
            string status = res["status"]!.GetValue<string>();
            if (status is "done" or "failed")
            {
                break;
            }
        }
        await SibLinks.Call("POST", $"/v1/jobs/{jobId}/ack", new { });
        foreach (JsonNode? s in res?["suggestions"]?.AsArray() ?? new JsonArray())
        {
            Console.WriteLine($"{s!["target_id"]} {s["anchor_hint"]} {s["strength"]}");
        }
    }
}
Output
credits_remaining: 87
45 מלונות טובים במינכן high
main.go
// SibLinks API client example (Go 1.20+, standard library only).
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

var (
	baseURL    = envOr("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
	siteID     = os.Getenv("SIBLINKS_SITE_ID")
	secret     = os.Getenv("SIBLINKS_SECRET")
	httpClient = &http.Client{Timeout: 30 * time.Second}
)

func envOr(key, fallback string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return fallback
}

func sha256Hex(b []byte) string {
	h := sha256.Sum256(b)
	return hex.EncodeToString(h[:])
}

func hmacHex(message string) string {
	m := hmac.New(sha256.New, []byte(secret))
	m.Write([]byte(message))
	return hex.EncodeToString(m.Sum(nil))
}

// APIError is an error answered by the API ({"error": {"code": ...}}).
type APIError struct {
	Status int
	Code   string
}

func (e *APIError) Error() string { return fmt.Sprintf("%d %s", e.Status, e.Code) }

// call sends a signed request and returns the verified JSON response.
func call(method, path string, body any) (map[string]any, error) {
	var raw []byte
	if body != nil {
		var err error
		if raw, err = json.Marshal(body); err != nil {
			return nil, err
		}
	}
	ts := strconv.FormatInt(time.Now().Unix(), 10)
	nonceBytes := make([]byte, 16)
	if _, err := rand.Read(nonceBytes); err != nil {
		return nil, err
	}
	nonce := hex.EncodeToString(nonceBytes)
	signature := hmacHex(ts + "\n" + method + "\n" + path + "\n" + sha256Hex(raw) + "\n" + nonce)

	req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(raw))
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-Site-Id", siteID)
	req.Header.Set("X-Timestamp", ts)
	req.Header.Set("X-Nonce", nonce)
	req.Header.Set("X-Signature", signature)
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	resp, err := httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	resBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	expected := hmacHex("response\n" + signature + "\n" + strconv.Itoa(resp.StatusCode) + "\n" + sha256Hex(resBody))
	got := strings.ToLower(resp.Header.Get("X-SibLinks-Signature"))
	if resp.StatusCode < 400 && !hmac.Equal([]byte(expected), []byte(got)) {
		return nil, &APIError{resp.StatusCode, "unsigned_response"} // never trust it
	}
	var data map[string]any
	if err := json.Unmarshal(resBody, &data); err != nil {
		return nil, err
	}
	if resp.StatusCode >= 400 {
		code := "unknown"
		if e, ok := data["error"].(map[string]any); ok {
			if c, ok := e["code"].(string); ok {
				code = c
			}
		}
		return nil, &APIError{resp.StatusCode, code}
	}
	return data, nil
}

func main() {
	account, err := call("GET", "/v1/account", nil)
	if err != nil {
		panic(err)
	}
	fmt.Println("credits_remaining:", account["plan"].(map[string]any)["credits_remaining"])

	job, err := call("POST", "/v1/jobs", map[string]any{
		"source": map[string]any{
			"id":           123,
			"title":        "חופשה במינכן",
			"content_html": "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>",
		},
		"targets": []map[string]any{
			{"id": 45, "title": "מלונות במינכן", "description": "המלצות על מלונות במינכן"},
		},
		"options": map[string]any{"max_links": 10},
	})
	if err != nil {
		panic(err)
	}
	jobID := job["job_id"].(string)

	var res map[string]any
	for deadline := time.Now().Add(5 * time.Minute); time.Now().Before(deadline); {
		time.Sleep(3 * time.Second)
		if res, err = call("GET", "/v1/jobs/"+jobID, nil); err != nil {
			panic(err)
		}
		if s := res["status"]; s == "done" || s == "failed" {
			break
		}
	}
	if _, err := call("POST", "/v1/jobs/"+jobID+"/ack", map[string]any{}); err != nil {
		panic(err)
	}
	suggestions, _ := res["suggestions"].([]any)
	for _, item := range suggestions {
		s := item.(map[string]any)
		fmt.Println(s["target_id"], s["anchor_hint"], s["strength"])
	}
}
Output
credits_remaining: 87
45 מלונות טובים במינכן high
siblinks_client.rb
# SibLinks API client example (Ruby 3.0+, standard library only).
require "json"
require "net/http"
require "openssl"
require "securerandom"

BASE_URL = ENV.fetch("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
SITE_ID = ENV.fetch("SIBLINKS_SITE_ID")
SECRET = ENV.fetch("SIBLINKS_SECRET")

class SibLinksError < StandardError
  attr_reader :status, :code

  def initialize(status, code)
    super("#{status} #{code}")
    @status = status
    @code = code
  end
end

def hmac_hex(message)
  OpenSSL::HMAC.hexdigest("SHA256", SECRET, message)
end

def call(method, path, body = nil)
  raw = body.nil? ? "" : JSON.generate(body)
  ts = Time.now.to_i.to_s
  nonce = SecureRandom.hex(16)
  signature = hmac_hex("#{ts}\n#{method}\n#{path}\n#{OpenSSL::Digest::SHA256.hexdigest(raw)}\n#{nonce}")

  uri = URI(BASE_URL + path)
  req = method == "GET" ? Net::HTTP::Get.new(uri) : Net::HTTP::Post.new(uri)
  req["X-Site-Id"] = SITE_ID
  req["X-Timestamp"] = ts
  req["X-Nonce"] = nonce
  req["X-Signature"] = signature
  unless body.nil?
    req["Content-Type"] = "application/json"
    req.body = raw
  end
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 30) { |http| http.request(req) }

  status = res.code.to_i
  res_body = res.body.to_s
  expected = hmac_hex("response\n#{signature}\n#{status}\n#{OpenSSL::Digest::SHA256.hexdigest(res_body)}")
  signed = OpenSSL.secure_compare(expected, res["X-SibLinks-Signature"].to_s.downcase)
  raise SibLinksError.new(status, "unsigned_response") if status < 400 && !signed # never trust it

  data = JSON.parse(res_body)
  raise SibLinksError.new(status, data.dig("error", "code") || "unknown") if status >= 400

  data
end

puts "credits_remaining: #{call('GET', '/v1/account').dig('plan', 'credits_remaining').inspect}"

job = call("POST", "/v1/jobs", {
  source: {
    id: 123,
    title: "חופשה במינכן",
    content_html: "<p>יש הרבה מלונות טובים במינכן ליד התחנה.</p>"
  },
  targets: [
    { id: 45, title: "מלונות במינכן", description: "המלצות על מלונות במינכן" }
  ],
  options: { max_links: 10 }
})

res = nil
deadline = Time.now + 300
while Time.now < deadline
  sleep 3
  res = call("GET", "/v1/jobs/#{job['job_id']}")
  break if %w[done failed].include?(res["status"])
end
call("POST", "/v1/jobs/#{job['job_id']}/ack", {})
(res["suggestions"] || []).each do |s|
  puts "#{s['target_id']} #{s['anchor_hint']} #{s['strength']}"
end
Output
credits_remaining: 87
45 מלונות טובים במינכן high
משאבים

יומן שינויים

שינויים ב־API שמשפיעים על מתכנתים. שדה חדש בתשובה לא נחשב שינוי שובר.

תאריךגרסהמה השתנה
9.10.20260.10.0פרסום ראשון של התיעוד למפתחים, עם דוגמאות ב־9 שפות.

שאלות על החיבור: info@siblinks.co.il