Wallgone API docs

Sign links in your own code

The link format, the signature, and tested examples in Node.js, Python and PHP.

Updated Five minutes to read

Sign links when your own code makes them without calling the API, for example a newsletter template that renders every link of an issue. A signed link works like one from the API, and it appears in Dashboard → Links after its first view. Links from the dashboard or POST /v1/links carry your link name instead and need no signature.

At a glance

When
Links made in your own code, with no request to Wallgone
Plan
Starter, Pro and Premium
You need
The translator origin, the key ID and the secret, from Dashboard → Developers
Signature
HMAC-SHA256 of the page address, first 8 bytes as hex
Signed
The page address only, not the language or the country
Examples
Node.js, Python, PHP

Keep the secret on your server

Anyone who has it can make links that use your translated pages.

Link format
{translator-origin}/{lang}/{page-url}?sig={key-id}.{mac}
{translator-origin}/{lang}/{country}/{page-url}?sig={key-id}.{mac}

When the page address already has a query, join the signature with & instead of ?:

Address with a query
https://wallgone.link/en/https://example.com/?x=1&sig=k7x2m9qa.85c519043df74f4b
  • {translator-origin} is the translator origin shown in Dashboard → Developers, such as https://wallgone.link.
  • {page-url} is the canonical address, written into the link as it is, without encoding it again.
  • {lang} and {country} are described under language and country.
  • Query parameters after sig are dropped when the link opens, so the tracking parameters that newsletter tools add to links (utm_source and the like) don’t break it.
  • A sig parameter in the page’s own address is fine. The translator takes the last sig in the format above as the signature, and the rest belongs to the page.

The signature

  1. Take the canonical form of the page address. It never has a fragment.
  2. Compute HMAC-SHA256 of the canonical address, as UTF-8, with the secret as the key. The key is the secret’s 64 characters as text, exactly as the dashboard shows them. Don’t decode them from hex.
  3. Keep the first 8 bytes of the result as 16 lowercase hex characters. This is {mac}.
  4. The sig value is {key-id}.{mac}.

The signature covers the page address only. The language and the country aren’t signed, so one signature serves every language: the language menu in the bar uses it, and anyone who has a link can change its language. Each language counts as its own translated page.

If you rotate the signing key, links signed with the old one stop working within 30 seconds. See rotating the signing key.

Language and country

{lang} is a BCP 47 code: two or three letters, optionally followed by one script or region subtag of two to four letters, such as en, pt-BR or zh-Hant. In a link you sign, the first part must be lowercase. Every plan includes every language. The signature doesn’t cover the language, so a reader can change it: a page counts in your bar’s languages without limit, and in up to three others a day; past that, readers get the original page. Codes with digits (es-419) or with two subtags (zh-Hant-TW) don’t fit the link format: /v1/links refuses them, and a link you sign with one answers 404.

{country} is optional: two lowercase letters such as jp. When the site refuses a direct load, the translator loads the page through a connection in that country, which helps with sites that block foreign visitors. Pro and Premium include these local connections. In a link you sign, an uppercase country (JP) makes the link answer 404.

Canonical address

When a link opens, the translator rebuilds the page address from it with the WHATWG URL parser, the same parser as the URL class in Node.js, and checks the signature against what that parser prints. You have to sign the same string, which is new URL(address).href with the fragment removed. Compared with the address you start from, the parser:

  • lowercases the scheme and the host (HTTPS://Example.COM/News becomes https://example.com/News), while the path and the query keep their case;
  • adds a slash after a bare host: https://example.com becomes https://example.com/, and https://example.com?x=1 becomes https://example.com/?x=1;
  • removes the fragment and a default port (:443 for https, :80 for http);
  • percent-encodes spaces, ", <, > and every non-ASCII character as UTF-8, and also ^, `, { and } in the path and ' in the query, with uppercase hex;
  • keeps %XX sequences already in the address exactly as written;
  • converts a non-ASCII host name to punycode: пример.рф becomes xn--e1afmkfd.xn--p1ai;
  • resolves . and .. path segments, turns \ in the path into /, and removes tabs and line breaks.

If you aren’t sure your code prints the same, make one link with POST /v1/links and compare. The address inside its link is the canonical form.

Some addresses are never loaded, and a link to one answers 404 instead of opening the page: an IP address, a port other than the default, a user name or password in the address, localhost, a host name without a dot, and host names ending in .local, .localhost, .internal, .lan, .home or .corp.

Check your code

With the key ID k7x2m9qa and the example secret below, which belongs to no account, your code should print these values:

Example secret
8396bdb622072d3719237d98d0a2611b14f3e925015fc9ac66b82d2bf43524b7
Expected values
address    https://example.com
canonical  https://example.com/
sig        k7x2m9qa.bf6818d89699d72b

address    https://Example.COM/News/Article?id=42#comments
canonical  https://example.com/News/Article?id=42
sig        k7x2m9qa.5c768adbad681f51

address    https://example.com?x=1
canonical  https://example.com/?x=1
sig        k7x2m9qa.85c519043df74f4b

address    https://www.example.jp/ニュース/記事?q=東京 都
canonical  https://www.example.jp/%E3%83%8B%E3%83%A5%E3%83%BC%E3%82%B9/%E8%A8%98%E4%BA%8B?q=%E6%9D%B1%E4%BA%AC%20%E9%83%BD
sig        k7x2m9qa.9ce78b9febe69b81

Node.js

The URL class in Node.js is the WHATWG parser, so this gives the translator’s result for every address. wallgoneLink(address, lang, country) returns the link; leave out country for a link without one.

wallgone.mjs
import { createHmac } from "node:crypto";

// From Dashboard → Developers
const ORIGIN = process.env.WALLGONE_ORIGIN; // the translator origin
const KEY_ID = process.env.WALLGONE_KEY_ID;
const SECRET = process.env.WALLGONE_SECRET;

export function wallgoneLink(pageUrl, lang, country) {
  const u = new URL(pageUrl.trim());
  u.hash = "";
  const url = u.href;
  const mac = createHmac("sha256", SECRET).update(url).digest("hex").slice(0, 16);
  const route = country ? `${lang}/${country}` : lang;
  return `${ORIGIN}/${route}/${url}${url.includes("?") ? "&" : "?"}sig=${KEY_ID}.${mac}`;
}

Python

Python’s standard library has no WHATWG parser, so this example builds the canonical form itself. It gives the translator’s result for the addresses described above, with these exceptions: it leaves . and .. segments and \ in the path as they are, and it drops a ? with nothing after it. Its idna codec follows the older IDNA 2003, which writes a few host names differently: straße.de becomes strasse.de instead of xn--strae-oqa.de. For such hosts, the idna package from PyPI gives the browser’s result with idna.encode(host, uts46=True, transitional=False).decode().

wallgone.py
import hashlib
import hmac
import os
from urllib.parse import quote, urlsplit, urlunsplit

# From Dashboard → Developers
ORIGIN = os.environ["WALLGONE_ORIGIN"]  # the translator origin
KEY_ID = os.environ["WALLGONE_KEY_ID"]
SECRET = os.environ["WALLGONE_SECRET"]

# Characters a browser leaves as they are in a path and in a query
PATH_SAFE = "!$%&'()*+,/:;=@[]|"
QUERY_SAFE = "!$%&()*+,/:;=?@[\\]^`{|}"
DEFAULT_PORT = {"http": 80, "https": 443}


def canonical(page_url):
    p = urlsplit(page_url.strip())
    host = p.hostname.encode("idna").decode("ascii")
    if p.port and p.port != DEFAULT_PORT.get(p.scheme):
        host += f":{p.port}"
    path = quote(p.path or "/", safe=PATH_SAFE)
    query = quote(p.query, safe=QUERY_SAFE)
    return urlunsplit((p.scheme, host, path, query, ""))


def wallgone_link(page_url, lang, country=None):
    url = canonical(page_url)
    mac = hmac.new(SECRET.encode(), url.encode(), hashlib.sha256).hexdigest()[:16]
    route = f"{lang}/{country}" if country else lang
    sep = "&" if "?" in url else "?"
    return f"{ORIGIN}/{route}/{url}{sep}sig={KEY_ID}.{mac}"

PHP

PHP has no WHATWG parser either, and parse_url() replaces some bytes of non-ASCII addresses, so this example splits the address with a regular expression. It gives the translator’s result for the addresses described above, except that it leaves . and .. segments, \ in the path, and tabs or line breaks inside the address as they are. Non-ASCII host names need idn_to_ascii() from the intl extension; without it, links to them don’t verify. It needs PHP 8 or later.

wallgone.php
<?php

// Bytes outside printable ASCII, and the characters in $also, as %XX
function wallgone_escape(string $s, string $also): string
{
    return preg_replace_callback(
        '/[^\x21-\x7E]|[' . preg_quote($also, '/') . ']/',
        fn ($m) => sprintf('%%%02X', ord($m[0])),
        $s
    );
}

function wallgone_canonical(string $pageUrl): string
{
    // parse_url() mangles non-ASCII bytes, so split the address by hand
    preg_match('~^([a-z][a-z0-9+.-]*)://([^/?#:]+)(?::(\d+))?([^?#]*)(\?[^#]*)?~i', trim($pageUrl), $m);
    $scheme = strtolower($m[1]);
    // idn_to_ascii() comes with the intl extension
    $host = function_exists('idn_to_ascii')
        ? idn_to_ascii($m[2], IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46)
        : strtolower($m[2]);
    $port = ($m[3] ?? '') !== '' && (int) $m[3] !== ['http' => 80, 'https' => 443][$scheme] ? ':' . (int) $m[3] : '';
    $path = wallgone_escape(($m[4] ?? '') ?: '/', '"<>^`{}');
    $query = isset($m[5]) ? wallgone_escape($m[5], "\"<>'") : '';
    return "$scheme://$host$port$path$query";
}

function wallgone_link(string $pageUrl, string $lang, ?string $country = null): string
{
    // From Dashboard → Developers
    $origin = getenv('WALLGONE_ORIGIN'); // the translator origin
    $keyId = getenv('WALLGONE_KEY_ID');
    $secret = getenv('WALLGONE_SECRET');

    $url = wallgone_canonical($pageUrl);
    $mac = substr(hash_hmac('sha256', $url, $secret), 0, 16);
    $route = $country ? "$lang/$country" : $lang;
    $sep = str_contains($url, '?') ? '&' : '?';
    return "$origin/$route/$url{$sep}sig=$keyId.$mac";
}

These examples were checked against the translator’s own code with Node.js 24, Python 3.12 and PHP 8.4.

Was this page useful?