Voorbeeldbestanden
Werkende voorbeelden in PHP, Node.js, Python en de opdrachtregel.
Op deze pagina staan werkende voorbeelden in vier talen: de opdrachtregel (cURL), PHP, Node.js en Python. Elk bestand staat er helemaal — je hoeft er niets bij te bedenken. Kopiëren of downloaden, de omgevingsvariabelen zetten die bovenaan het bestand staan, uitvoeren.
De bestanden zijn bewust saai gehouden: geen framework, geen pakketten, geen slimmigheden. Wat je hier ziet is de kale werking. Zo kun je die in je eigen codebasis overnemen op de manier die daar past.
Wat je nodig hebt
| Taal | Nodig | Pakketten |
|---|---|---|
| cURL | bash en curl; base64 voor de bijlage, openssl voor de handtekening |
geen |
| PHP | PHP 8.1 of nieuwer met de curl-extensie |
geen |
| Node.js | Node.js 18 of nieuwer | geen — ingebouwde fetch, node:http en node:crypto |
| Python | Python 3.9 of nieuwer | geen — alleen de standaardbibliotheek |
De webhook-ontvangers gebruiken met opzet géén Express of Flask. Waar het bij een webhook om draait is de ruwe body. En dat is nu juist wat een framework van je afpakt. In de kop van beide bestanden staat wat je moet doen als je er wél een gebruikt.
De gegevens die je invult
Geen enkel voorbeeld heeft een sleutel in de tekst staan. Ze lezen alles uit omgevingsvariabelen, en dat is meteen het advies. Bewaar je sleutel daar of in een sleutelkluis. Zet hem nooit in je broncode en nooit ergens waar een browser bij kan.
| Variabele | Waar hij voor is |
|---|---|
SENDPIER_API_KEY |
de sp_live_…-sleutel van één geverifieerd domein |
SENDPIER_DOMAIN |
datzelfde domein; het gaat mee als kop X-Domain-Name |
SENDPIER_FROM |
een afzenderadres op dat domein |
SENDPIER_WEBHOOK_SECRET |
het whsec_…-geheim van één webhook-adres |
PORT |
de poort waarop een webhook-ontvanger luistert (standaard 8080) |
Zo zet je ze klaar en verstuur je één bericht:
export SENDPIER_API_KEY='sp_live_…'
export SENDPIER_DOMAIN='jouwdomein.nl'
export SENDPIER_FROM='noreply@jouwdomein.nl'
./send-message.sh ontvanger@voorbeeld.nl
Een bericht versturen
Het eenvoudigste geval: één ontvanger, een onderwerp en een tekst- en HTML-deel. Je krijgt HTTP 202 terug met een kenmerk per ontvanger. Zie Een bericht versturen voor alle velden.
cURL
#!/usr/bin/env bash
#
# SendPier Send API — send a single message.
#
# Requirements: bash and curl. Nothing else.
#
# Usage:
# export SENDPIER_API_KEY='sp_live_...' # the key of one verified domain
# export SENDPIER_DOMAIN='example.com' # that same domain
# export SENDPIER_FROM='noreply@example.com' # must live on that domain
# ./send-message.sh recipient@example.org
#
# A successful call answers 202 Accepted and returns one identifier per
# recipient. 202 means "accepted for delivery", not "delivered" -- ask
# get-message.sh later, or let a webhook tell you.
set -euo pipefail
API_BASE='https://api.sendpier.com'
: "${SENDPIER_API_KEY:?set SENDPIER_API_KEY to your Send API key}"
: "${SENDPIER_DOMAIN:?set SENDPIER_DOMAIN to the domain the key belongs to}"
: "${SENDPIER_FROM:?set SENDPIER_FROM to a sender address on that domain}"
recipient="${1:-}"
if [ -z "$recipient" ]; then
echo "usage: $0 <recipient@example.org>" >&2
exit 64
fi
# The body is built with a here-document so the quoting stays readable. Anything
# you interpolate here has to be valid JSON -- see send-with-template.sh for the
# safer route when the values come from your own users.
body=$(cat <<JSON
{
"from": { "email": "${SENDPIER_FROM}", "name": "Example" },
"to": [{ "email": "${recipient}" }],
"subject": "Hello from the Send API",
"text": "This message was sent with curl.",
"html": "<p>This message was sent with curl.</p>"
}
JSON
)
# -sS keeps curl quiet but still prints transport errors; -w writes the status
# code on its own last line so we can read it without parsing the JSON.
response=$(curl -sS -X POST "${API_BASE}/v1/messages" \
-H "Authorization: Bearer ${SENDPIER_API_KEY}" \
-H "X-Domain-Name: ${SENDPIER_DOMAIN}" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-w '\n%{http_code}' \
-d "$body")
status=$(printf '%s' "$response" | tail -n1)
payload=$(printf '%s' "$response" | sed '$d')
echo "$payload"
if [ "$status" != '202' ]; then
# Always log the status code *and* the body: the body carries the error code
# that says what to change. Retry 429 and 503 with a growing wait; a 422 will
# fail again in exactly the same way.
echo "request failed with HTTP ${status}" >&2
exit 1
fi
echo "accepted (HTTP 202)" >&2
PHP
<?php
/**
* SendPier Send API — send a single message.
*
* Requirements: PHP 8.1 or newer with the curl extension. No packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...' # the key of one verified domain
* export SENDPIER_DOMAIN='example.com' # that same domain
* export SENDPIER_FROM='noreply@example.com' # must live on that domain
* php send-message.php recipient@example.org
*
* A successful call answers 202 Accepted and returns one identifier per
* recipient. 202 means "accepted for delivery", not "delivered" -- ask
* get-message.php later, or let a webhook tell you.
*/
declare(strict_types=1);
const API_BASE = 'https://api.sendpier.com';
/**
* One request to the Send API.
*
* Keep the key in the environment or in a secrets store, never in your source
* and never anywhere a browser can read it: the Send API is meant for traffic
* from your own server.
*
* @param array<string, mixed>|null $body
* @return array{status: int, body: array<string, mixed>|null, raw: string}
*/
function sendpier_request(string $method, string $path, ?array $body = null): array
{
$key = getenv('SENDPIER_API_KEY');
$domain = getenv('SENDPIER_DOMAIN');
if ($key === false || $key === '' || $domain === false || $domain === '') {
fwrite(STDERR, "set SENDPIER_API_KEY and SENDPIER_DOMAIN first\n");
exit(78);
}
$headers = [
'Authorization: Bearer '.$key,
// Required on every request. The key belongs to one domain and this
// header has to name that same domain, or the answer is 403.
'X-Domain-Name: '.$domain,
'Accept: application/json',
];
$handle = curl_init(API_BASE.$path);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($handle, CURLOPT_TIMEOUT, 30);
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
$raw = curl_exec($handle);
if ($raw === false) {
$error = curl_error($handle);
curl_close($handle);
fwrite(STDERR, "connection failed: {$error}\n");
exit(1);
}
$status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$decoded = json_decode((string) $raw, true);
return [
'status' => $status,
'body' => is_array($decoded) ? $decoded : null,
'raw' => (string) $raw,
];
}
$recipient = $argv[1] ?? '';
$from = getenv('SENDPIER_FROM');
if ($recipient === '' || $from === false || $from === '') {
fwrite(STDERR, "usage: SENDPIER_FROM=noreply@example.com php send-message.php <recipient@example.org>\n");
exit(64);
}
$response = sendpier_request('POST', '/v1/messages', [
'from' => ['email' => $from, 'name' => 'Example'],
// Ten recipients fit in one request, but prefer one: then you know the
// status per email and one bad address cannot take the rest down with it.
'to' => [['email' => $recipient]],
'subject' => 'Hello from the Send API',
'text' => 'This message was sent from PHP.',
'html' => '<p>This message was sent from PHP.</p>',
]);
echo $response['raw'], "\n";
if ($response['status'] !== 202) {
// Log the status code *and* the body: the body carries the error code that
// says what to change. Retry 429 and 503 with a growing wait; a 422 will
// come back in exactly the same way.
fwrite(STDERR, "request failed with HTTP {$response['status']}\n");
exit(1);
}
foreach ($response['body']['data'] ?? [] as $message) {
// Store this identifier next to your own record: it is what you look the
// message up with, and what a webhook reports back to you.
fwrite(STDERR, sprintf("queued %s for %s\n", $message['id'] ?? '?', $message['to'] ?? '?'));
}
Node.js
/**
* SendPier Send API — send a single message.
*
* Requirements: Node.js 18 or newer. Built-in fetch only, no packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...' # the key of one verified domain
* export SENDPIER_DOMAIN='example.com' # that same domain
* export SENDPIER_FROM='noreply@example.com' # must live on that domain
* node send-message.mjs recipient@example.org
*
* A successful call answers 202 Accepted and returns one identifier per
* recipient. 202 means "accepted for delivery", not "delivered" -- ask
* get-message.mjs later, or let a webhook tell you.
*/
const API_BASE = 'https://api.sendpier.com';
/**
* One request to the Send API.
*
* Keep the key in the environment or in a secrets store, never in your source
* and never anywhere a browser can read it: the Send API is meant for traffic
* from your own server.
*/
async function sendpierRequest(method, path, body = null) {
const key = process.env.SENDPIER_API_KEY;
const domain = process.env.SENDPIER_DOMAIN;
if (!key || !domain) {
console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first');
process.exit(78);
}
const headers = {
Authorization: `Bearer ${key}`,
// Required on every request. The key belongs to one domain and this header
// has to name that same domain, or the answer is 403.
'X-Domain-Name': domain,
Accept: 'application/json',
};
if (body !== null) {
headers['Content-Type'] = 'application/json';
}
const response = await fetch(`${API_BASE}${path}`, {
method,
headers,
body: body === null ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
const raw = await response.text();
let parsed = null;
try {
parsed = JSON.parse(raw);
} catch {
// A gateway between us and you may answer HTML; keep the raw text so the
// status code and the body both end up in your log.
}
return { status: response.status, body: parsed, raw };
}
const recipient = process.argv[2];
const from = process.env.SENDPIER_FROM;
if (!recipient || !from) {
console.error('usage: SENDPIER_FROM=noreply@example.com node send-message.mjs <recipient@example.org>');
process.exit(64);
}
const response = await sendpierRequest('POST', '/v1/messages', {
from: { email: from, name: 'Example' },
// Ten recipients fit in one request, but prefer one: then you know the status
// per email and one bad address cannot take the rest down with it.
to: [{ email: recipient }],
subject: 'Hello from the Send API',
text: 'This message was sent from Node.js.',
html: '<p>This message was sent from Node.js.</p>',
});
console.log(response.raw);
if (response.status !== 202) {
// Log the status code *and* the body: the body carries the error code that
// says what to change. Retry 429 and 503 with a growing wait; a 422 will come
// back in exactly the same way.
console.error(`request failed with HTTP ${response.status}`);
process.exit(1);
}
for (const message of response.body?.data ?? []) {
// Store this identifier next to your own record: it is what you look the
// message up with, and what a webhook reports back to you.
console.error(`queued ${message.id} for ${message.to}`);
}
Python
#!/usr/bin/env python3
"""SendPier Send API — send a single message.
Requirements: Python 3.9 or newer. Standard library only, no packages -- so
this runs anywhere, including in a container without pip. Using `requests`?
Replace `sendpier_request` with a `requests.post(...)`; the headers and the body
stay exactly the same.
Usage:
export SENDPIER_API_KEY='sp_live_...' # the key of one verified domain
export SENDPIER_DOMAIN='example.com' # that same domain
export SENDPIER_FROM='noreply@example.com' # must live on that domain
python3 send_message.py recipient@example.org
A successful call answers 202 Accepted and returns one identifier per recipient.
202 means "accepted for delivery", not "delivered" -- ask get_message.py later,
or let a webhook tell you.
"""
import json
import os
import sys
import urllib.error
import urllib.request
API_BASE = "https://api.sendpier.com"
def sendpier_request(method, path, body=None, timeout=30):
"""One request to the Send API.
Keep the key in the environment or in a secrets store, never in your source
and never anywhere a browser can read it: the Send API is meant for traffic
from your own server.
Returns (status, parsed_body_or_None, raw_text).
"""
key = os.environ.get("SENDPIER_API_KEY", "")
domain = os.environ.get("SENDPIER_DOMAIN", "")
if not key or not domain:
sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first")
headers = {
"Authorization": "Bearer " + key,
# Required on every request. The key belongs to one domain and this
# header has to name that same domain, or the answer is 403.
"X-Domain-Name": domain,
"Accept": "application/json",
}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(API_BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.status
raw = response.read().decode("utf-8")
except urllib.error.HTTPError as error:
# A 4xx or 5xx is an answer, not a crash: the body carries the error
# code that says what to change.
status = error.code
raw = error.read().decode("utf-8", "replace")
except urllib.error.URLError as error:
sys.exit("connection failed: {}".format(error.reason))
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
return status, parsed, raw
def main():
recipient = sys.argv[1] if len(sys.argv) > 1 else ""
sender = os.environ.get("SENDPIER_FROM", "")
if not recipient or not sender:
sys.exit(
"usage: SENDPIER_FROM=noreply@example.com "
"python3 send_message.py <recipient@example.org>"
)
status, body, raw = sendpier_request(
"POST",
"/v1/messages",
{
"from": {"email": sender, "name": "Example"},
# Ten recipients fit in one request, but prefer one: then you know
# the status per email and one bad address cannot take the rest
# down with it.
"to": [{"email": recipient}],
"subject": "Hello from the Send API",
"text": "This message was sent from Python.",
"html": "<p>This message was sent from Python.</p>",
},
)
print(raw)
if status != 202:
# Log the status code *and* the body. Retry 429 and 503 with a growing
# wait; a 422 will come back in exactly the same way.
sys.exit("request failed with HTTP {}".format(status))
for message in (body or {}).get("data", []):
# Store this identifier next to your own record: it is what you look
# the message up with, and what a webhook reports back to you.
print("queued {} for {}".format(message.get("id"), message.get("to")), file=sys.stderr)
if __name__ == "__main__":
main()
Een bericht met een bijlage
Een bijlage gaat als base64 mee in het verzoek: een manier om een bestand als gewone tekst in het verzoek te zetten. Tekst, HTML en bijlagen samen mogen 25 MB zijn na het decoderen. Er passen maximaal twintig bijlagen in één bericht. Weigeren we één bijlage, dan weigeren we het hele bericht. We versturen nooit een half bericht.
cURL
#!/usr/bin/env bash
#
# SendPier Send API — send a message with a file attached.
#
# Requirements: bash, curl and base64 (part of GNU coreutils).
#
# Usage:
# export SENDPIER_API_KEY='sp_live_...'
# export SENDPIER_DOMAIN='example.com'
# export SENDPIER_FROM='invoices@example.com'
# ./send-with-attachment.sh recipient@example.org ./invoice.pdf
#
# Message text, HTML and attachments together may be 25 MB after decoding, and
# a message carries at most 20 attachments. Executable file types are refused.
set -euo pipefail
API_BASE='https://api.sendpier.com'
: "${SENDPIER_API_KEY:?set SENDPIER_API_KEY to your Send API key}"
: "${SENDPIER_DOMAIN:?set SENDPIER_DOMAIN to the domain the key belongs to}"
: "${SENDPIER_FROM:?set SENDPIER_FROM to a sender address on that domain}"
recipient="${1:-}"
file="${2:-}"
if [ -z "$recipient" ] || [ -z "$file" ]; then
echo "usage: $0 <recipient@example.org> <file>" >&2
exit 64
fi
if [ ! -r "$file" ]; then
echo "cannot read ${file}" >&2
exit 66
fi
# -w0 keeps the base64 on one line. Line breaks inside the value are allowed as
# well, so `base64 "$file"` works too -- this is only about readable output.
encoded=$(base64 -w0 "$file")
filename=$(basename "$file")
# content_type may be left out; it is then derived from the file name. Add a
# content_id to turn an attachment into an inline part you can point at from
# your HTML with <img src="cid:...">.
body=$(cat <<JSON
{
"from": { "email": "${SENDPIER_FROM}", "name": "Example" },
"to": [{ "email": "${recipient}" }],
"subject": "Your invoice",
"text": "Your invoice is attached.",
"html": "<p>Your invoice is attached.</p>",
"attachments": [
{
"filename": "${filename}",
"content": "${encoded}",
"content_type": "application/pdf"
}
]
}
JSON
)
response=$(curl -sS -X POST "${API_BASE}/v1/messages" \
-H "Authorization: Bearer ${SENDPIER_API_KEY}" \
-H "X-Domain-Name: ${SENDPIER_DOMAIN}" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-w '\n%{http_code}' \
-d "$body")
status=$(printf '%s' "$response" | tail -n1)
payload=$(printf '%s' "$response" | sed '$d')
echo "$payload"
if [ "$status" != '202' ]; then
# 413 message_too_large means the whole message exceeded 25 MB; send big
# files as a download link instead. 422 attachment_type_blocked means the
# file type never reaches an inbox anyway.
echo "request failed with HTTP ${status}" >&2
exit 1
fi
echo "accepted (HTTP 202)" >&2
PHP
<?php
/**
* SendPier Send API — send a message with a file attached.
*
* Requirements: PHP 8.1 or newer with the curl extension. No packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* export SENDPIER_FROM='invoices@example.com'
* php send-with-attachment.php recipient@example.org ./invoice.pdf
*
* Message text, HTML and attachments together may be 25 MB after decoding, and
* a message carries at most 20 attachments. If one attachment is refused the
* whole message is refused -- half a mail never goes out.
*/
declare(strict_types=1);
const API_BASE = 'https://api.sendpier.com';
/**
* One request to the Send API.
*
* @param array<string, mixed>|null $body
* @return array{status: int, body: array<string, mixed>|null, raw: string}
*/
function sendpier_request(string $method, string $path, ?array $body = null): array
{
$key = getenv('SENDPIER_API_KEY');
$domain = getenv('SENDPIER_DOMAIN');
if ($key === false || $key === '' || $domain === false || $domain === '') {
fwrite(STDERR, "set SENDPIER_API_KEY and SENDPIER_DOMAIN first\n");
exit(78);
}
$headers = [
'Authorization: Bearer '.$key,
'X-Domain-Name: '.$domain,
'Accept: application/json',
];
$handle = curl_init(API_BASE.$path);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
// An attachment makes the upload larger; give it room without waiting for
// ever on a stalled connection.
curl_setopt($handle, CURLOPT_TIMEOUT, 120);
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
$raw = curl_exec($handle);
if ($raw === false) {
$error = curl_error($handle);
curl_close($handle);
fwrite(STDERR, "connection failed: {$error}\n");
exit(1);
}
$status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$decoded = json_decode((string) $raw, true);
return [
'status' => $status,
'body' => is_array($decoded) ? $decoded : null,
'raw' => (string) $raw,
];
}
/**
* One entry of the attachments list.
*
* `content_type` may be left out; it is then derived from the file name. Add a
* `content_id` to turn the file into an inline part, and point at it from your
* HTML with `<img src="cid:logo">`.
*
* @return array<string, string>
*/
function sendpier_attachment(string $path, ?string $contentType = null, ?string $contentId = null): array
{
$contents = @file_get_contents($path);
if ($contents === false) {
fwrite(STDERR, "cannot read {$path}\n");
exit(66);
}
$attachment = [
// Only the file name travels; a path in front of it is cut off anyway.
'filename' => basename($path),
'content' => base64_encode($contents),
];
if ($contentType !== null) {
$attachment['content_type'] = $contentType;
}
if ($contentId !== null) {
$attachment['content_id'] = $contentId;
}
return $attachment;
}
$recipient = $argv[1] ?? '';
$file = $argv[2] ?? '';
$from = getenv('SENDPIER_FROM');
if ($recipient === '' || $file === '' || $from === false || $from === '') {
fwrite(STDERR, "usage: SENDPIER_FROM=invoices@example.com php send-with-attachment.php <recipient@example.org> <file>\n");
exit(64);
}
$response = sendpier_request('POST', '/v1/messages', [
'from' => ['email' => $from, 'name' => 'Example'],
'to' => [['email' => $recipient]],
'subject' => 'Your invoice',
'text' => 'Your invoice is attached.',
'html' => '<p>Your invoice is attached.</p>',
'attachments' => [
sendpier_attachment($file, 'application/pdf'),
],
]);
echo $response['raw'], "\n";
if ($response['status'] !== 202) {
// 413 message_too_large means the whole message went over 25 MB; send big
// files as a download link instead. 422 attachment_type_blocked means the
// file type would never reach an inbox anyway -- the last extension counts,
// so invoice.pdf.exe is an .exe.
fwrite(STDERR, "request failed with HTTP {$response['status']}\n");
exit(1);
}
foreach ($response['body']['data'] ?? [] as $message) {
fwrite(STDERR, sprintf("queued %s for %s\n", $message['id'] ?? '?', $message['to'] ?? '?'));
}
Node.js
/**
* SendPier Send API — send a message with a file attached.
*
* Requirements: Node.js 18 or newer. Built-in fetch and node:fs, no packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* export SENDPIER_FROM='invoices@example.com'
* node send-with-attachment.mjs recipient@example.org ./invoice.pdf
*
* Message text, HTML and attachments together may be 25 MB after decoding, and
* a message carries at most 20 attachments. If one attachment is refused the
* whole message is refused -- half a mail never goes out.
*/
import { readFileSync } from 'node:fs';
import { basename } from 'node:path';
const API_BASE = 'https://api.sendpier.com';
/** One request to the Send API. */
async function sendpierRequest(method, path, body = null) {
const key = process.env.SENDPIER_API_KEY;
const domain = process.env.SENDPIER_DOMAIN;
if (!key || !domain) {
console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first');
process.exit(78);
}
const headers = {
Authorization: `Bearer ${key}`,
'X-Domain-Name': domain,
Accept: 'application/json',
};
if (body !== null) {
headers['Content-Type'] = 'application/json';
}
const response = await fetch(`${API_BASE}${path}`, {
method,
headers,
body: body === null ? undefined : JSON.stringify(body),
// An attachment makes the upload larger; give it room without waiting for
// ever on a stalled connection.
signal: AbortSignal.timeout(120_000),
});
const raw = await response.text();
let parsed = null;
try {
parsed = JSON.parse(raw);
} catch {
// Keep the raw text: status code and body both belong in your log.
}
return { status: response.status, body: parsed, raw };
}
/**
* One entry of the attachments list.
*
* `content_type` may be left out; it is then derived from the file name. Add a
* `contentId` to turn the file into an inline part, and point at it from your
* HTML with `<img src="cid:logo">`.
*/
function sendpierAttachment(path, contentType = null, contentId = null) {
const attachment = {
// Only the file name travels; a path in front of it is cut off anyway.
filename: basename(path),
content: readFileSync(path).toString('base64'),
};
if (contentType !== null) {
attachment.content_type = contentType;
}
if (contentId !== null) {
attachment.content_id = contentId;
}
return attachment;
}
const recipient = process.argv[2];
const file = process.argv[3];
const from = process.env.SENDPIER_FROM;
if (!recipient || !file || !from) {
console.error('usage: SENDPIER_FROM=invoices@example.com node send-with-attachment.mjs <recipient@example.org> <file>');
process.exit(64);
}
const response = await sendpierRequest('POST', '/v1/messages', {
from: { email: from, name: 'Example' },
to: [{ email: recipient }],
subject: 'Your invoice',
text: 'Your invoice is attached.',
html: '<p>Your invoice is attached.</p>',
attachments: [sendpierAttachment(file, 'application/pdf')],
});
console.log(response.raw);
if (response.status !== 202) {
// 413 message_too_large means the whole message went over 25 MB; send big
// files as a download link instead. 422 attachment_type_blocked means the
// file type would never reach an inbox anyway -- the last extension counts,
// so invoice.pdf.exe is an .exe.
console.error(`request failed with HTTP ${response.status}`);
process.exit(1);
}
for (const message of response.body?.data ?? []) {
console.error(`queued ${message.id} for ${message.to}`);
}
Python
#!/usr/bin/env python3
"""SendPier Send API — send a message with a file attached.
Requirements: Python 3.9 or newer. Standard library only, no packages.
Usage:
export SENDPIER_API_KEY='sp_live_...'
export SENDPIER_DOMAIN='example.com'
export SENDPIER_FROM='invoices@example.com'
python3 send_with_attachment.py recipient@example.org ./invoice.pdf
Message text, HTML and attachments together may be 25 MB after decoding, and a
message carries at most 20 attachments. If one attachment is refused the whole
message is refused -- half a mail never goes out.
"""
import base64
import json
import os
import sys
import urllib.error
import urllib.request
API_BASE = "https://api.sendpier.com"
def sendpier_request(method, path, body=None, timeout=120):
"""One request to the Send API.
Returns (status, parsed_body_or_None, raw_text).
"""
key = os.environ.get("SENDPIER_API_KEY", "")
domain = os.environ.get("SENDPIER_DOMAIN", "")
if not key or not domain:
sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first")
headers = {
"Authorization": "Bearer " + key,
"X-Domain-Name": domain,
"Accept": "application/json",
}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(API_BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.status
raw = response.read().decode("utf-8")
except urllib.error.HTTPError as error:
status = error.code
raw = error.read().decode("utf-8", "replace")
except urllib.error.URLError as error:
sys.exit("connection failed: {}".format(error.reason))
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
return status, parsed, raw
def sendpier_attachment(path, content_type=None, content_id=None):
"""One entry of the attachments list.
`content_type` may be left out; it is then derived from the file name. Add a
`content_id` to turn the file into an inline part, and point at it from your
HTML with `<img src="cid:logo">`.
"""
with open(path, "rb") as handle:
contents = handle.read()
attachment = {
# Only the file name travels; a path in front of it is cut off anyway.
"filename": os.path.basename(path),
"content": base64.b64encode(contents).decode("ascii"),
}
if content_type is not None:
attachment["content_type"] = content_type
if content_id is not None:
attachment["content_id"] = content_id
return attachment
def main():
recipient = sys.argv[1] if len(sys.argv) > 1 else ""
path = sys.argv[2] if len(sys.argv) > 2 else ""
sender = os.environ.get("SENDPIER_FROM", "")
if not recipient or not path or not sender:
sys.exit(
"usage: SENDPIER_FROM=invoices@example.com "
"python3 send_with_attachment.py <recipient@example.org> <file>"
)
status, body, raw = sendpier_request(
"POST",
"/v1/messages",
{
"from": {"email": sender, "name": "Example"},
"to": [{"email": recipient}],
"subject": "Your invoice",
"text": "Your invoice is attached.",
"html": "<p>Your invoice is attached.</p>",
"attachments": [sendpier_attachment(path, "application/pdf")],
},
)
print(raw)
if status != 202:
# 413 message_too_large means the whole message went over 25 MB; send
# big files as a download link instead. 422 attachment_type_blocked
# means the file type would never reach an inbox anyway -- the last
# extension counts, so invoice.pdf.exe is an .exe.
sys.exit("request failed with HTTP {}".format(status))
for message in (body or {}).get("data", []):
print("queued {} for {}".format(message.get("id"), message.get("to")), file=sys.stderr)
if __name__ == "__main__":
main()
Een opgeslagen sjabloon versturen
Het sjabloon zelf maak je in het paneel; het verzoek draagt alleen het nummer en de variabelen. Dit is de veiligere weg zodra de waarden van je eigen gebruikers komen. In een sjabloon wordt een waarde als tekst ingevoegd. Zo kan die waarde je opmaak niet stukmaken.
cURL
#!/usr/bin/env bash
#
# SendPier Send API — send a stored template.
#
# Requirements: bash and curl.
#
# Usage:
# export SENDPIER_API_KEY='sp_live_...'
# export SENDPIER_DOMAIN='example.com'
# export SENDPIER_FROM='orders@example.com'
# ./send-with-template.sh recipient@example.org 7
#
# The template itself lives in the control panel; the request only carries its
# id and the variables. Sending a template is the safer route whenever the
# values come from your own users: template values are inserted as text, so
# they cannot break your HTML open.
set -euo pipefail
API_BASE='https://api.sendpier.com'
: "${SENDPIER_API_KEY:?set SENDPIER_API_KEY to your Send API key}"
: "${SENDPIER_DOMAIN:?set SENDPIER_DOMAIN to the domain the key belongs to}"
: "${SENDPIER_FROM:?set SENDPIER_FROM to a sender address on that domain}"
recipient="${1:-}"
template_id="${2:-}"
if [ -z "$recipient" ] || [ -z "$template_id" ]; then
echo "usage: $0 <recipient@example.org> <template_id>" >&2
exit 64
fi
# Send every variable the template uses. Miss one and the whole request is
# refused with 422 missing_template_variables, naming the fields you forgot --
# so nobody receives a half-filled message.
#
# "html" or "text" next to a template_id is refused (422 template_body_conflict);
# the body comes from the template. Your own "subject" is allowed and wins.
body=$(cat <<JSON
{
"from": { "email": "${SENDPIER_FROM}" },
"to": [{ "email": "${recipient}" }],
"template_id": ${template_id},
"variables": {
"voornaam": "Jan",
"ordernummer": "A-1024"
}
}
JSON
)
response=$(curl -sS -X POST "${API_BASE}/v1/messages" \
-H "Authorization: Bearer ${SENDPIER_API_KEY}" \
-H "X-Domain-Name: ${SENDPIER_DOMAIN}" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-w '\n%{http_code}' \
-d "$body")
status=$(printf '%s' "$response" | tail -n1)
payload=$(printf '%s' "$response" | sed '$d')
echo "$payload"
if [ "$status" != '202' ]; then
echo "request failed with HTTP ${status}" >&2
exit 1
fi
echo "accepted (HTTP 202)" >&2
PHP
<?php
/**
* SendPier Send API — send a stored template.
*
* Requirements: PHP 8.1 or newer with the curl extension. No packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* export SENDPIER_FROM='orders@example.com'
* php send-with-template.php recipient@example.org 7
*
* The template lives in the control panel; the request only carries its id and
* the variables. Prefer this over building HTML yourself whenever the values
* come from your own users: template values are inserted as text, so they
* cannot break your markup open.
*/
declare(strict_types=1);
const API_BASE = 'https://api.sendpier.com';
/**
* One request to the Send API.
*
* @param array<string, mixed>|null $body
* @return array{status: int, body: array<string, mixed>|null, raw: string}
*/
function sendpier_request(string $method, string $path, ?array $body = null): array
{
$key = getenv('SENDPIER_API_KEY');
$domain = getenv('SENDPIER_DOMAIN');
if ($key === false || $key === '' || $domain === false || $domain === '') {
fwrite(STDERR, "set SENDPIER_API_KEY and SENDPIER_DOMAIN first\n");
exit(78);
}
$headers = [
'Authorization: Bearer '.$key,
'X-Domain-Name: '.$domain,
'Accept: application/json',
];
$handle = curl_init(API_BASE.$path);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($handle, CURLOPT_TIMEOUT, 30);
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
$raw = curl_exec($handle);
if ($raw === false) {
$error = curl_error($handle);
curl_close($handle);
fwrite(STDERR, "connection failed: {$error}\n");
exit(1);
}
$status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$decoded = json_decode((string) $raw, true);
return [
'status' => $status,
'body' => is_array($decoded) ? $decoded : null,
'raw' => (string) $raw,
];
}
$recipient = $argv[1] ?? '';
$templateId = (int) ($argv[2] ?? 0);
$from = getenv('SENDPIER_FROM');
if ($recipient === '' || $templateId <= 0 || $from === false || $from === '') {
fwrite(STDERR, "usage: SENDPIER_FROM=orders@example.com php send-with-template.php <recipient@example.org> <template_id>\n");
exit(64);
}
$response = sendpier_request('POST', '/v1/messages', [
'from' => ['email' => $from],
'to' => [['email' => $recipient]],
'template_id' => $templateId,
// Send every variable the template uses. Miss one and the whole request is
// refused with 422 missing_template_variables, naming the fields you left
// out -- so nobody receives a half-filled message.
//
// Values under an email address apply to that recipient only and win from
// the general ones:
// 'variables' => ['ordernummer' => 'A-1', 'jan@example.org' => ['voornaam' => 'Jan']]
'variables' => [
'voornaam' => 'Jan',
'ordernummer' => 'A-1024',
],
// 'html' or 'text' next to a template_id is refused with 422
// template_body_conflict: the body comes from the template. Your own
// 'subject' is allowed and overrides the one of the template.
]);
echo $response['raw'], "\n";
if ($response['status'] !== 202) {
fwrite(STDERR, "request failed with HTTP {$response['status']}\n");
exit(1);
}
foreach ($response['body']['data'] ?? [] as $message) {
fwrite(STDERR, sprintf("queued %s for %s\n", $message['id'] ?? '?', $message['to'] ?? '?'));
}
Node.js
/**
* SendPier Send API — send a stored template.
*
* Requirements: Node.js 18 or newer. Built-in fetch only, no packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* export SENDPIER_FROM='orders@example.com'
* node send-with-template.mjs recipient@example.org 7
*
* The template lives in the control panel; the request only carries its id and
* the variables. Prefer this over building HTML yourself whenever the values
* come from your own users: template values are inserted as text, so they
* cannot break your markup open.
*/
const API_BASE = 'https://api.sendpier.com';
/** One request to the Send API. */
async function sendpierRequest(method, path, body = null) {
const key = process.env.SENDPIER_API_KEY;
const domain = process.env.SENDPIER_DOMAIN;
if (!key || !domain) {
console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first');
process.exit(78);
}
const headers = {
Authorization: `Bearer ${key}`,
'X-Domain-Name': domain,
Accept: 'application/json',
};
if (body !== null) {
headers['Content-Type'] = 'application/json';
}
const response = await fetch(`${API_BASE}${path}`, {
method,
headers,
body: body === null ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
const raw = await response.text();
let parsed = null;
try {
parsed = JSON.parse(raw);
} catch {
// Keep the raw text: status code and body both belong in your log.
}
return { status: response.status, body: parsed, raw };
}
const recipient = process.argv[2];
const templateId = Number.parseInt(process.argv[3] ?? '', 10);
const from = process.env.SENDPIER_FROM;
if (!recipient || !Number.isInteger(templateId) || templateId <= 0 || !from) {
console.error('usage: SENDPIER_FROM=orders@example.com node send-with-template.mjs <recipient@example.org> <template_id>');
process.exit(64);
}
const response = await sendpierRequest('POST', '/v1/messages', {
from: { email: from },
to: [{ email: recipient }],
template_id: templateId,
// Send every variable the template uses. Miss one and the whole request is
// refused with 422 missing_template_variables, naming the fields you left out
// -- so nobody receives a half-filled message.
//
// Values under an email address apply to that recipient only and win from the
// general ones:
// variables: { ordernummer: 'A-1', 'jan@example.org': { voornaam: 'Jan' } }
variables: {
voornaam: 'Jan',
ordernummer: 'A-1024',
},
// "html" or "text" next to a template_id is refused with 422
// template_body_conflict: the body comes from the template. Your own
// "subject" is allowed and overrides the one of the template.
});
console.log(response.raw);
if (response.status !== 202) {
console.error(`request failed with HTTP ${response.status}`);
process.exit(1);
}
for (const message of response.body?.data ?? []) {
console.error(`queued ${message.id} for ${message.to}`);
}
Python
#!/usr/bin/env python3
"""SendPier Send API — send a stored template.
Requirements: Python 3.9 or newer. Standard library only, no packages.
Usage:
export SENDPIER_API_KEY='sp_live_...'
export SENDPIER_DOMAIN='example.com'
export SENDPIER_FROM='orders@example.com'
python3 send_with_template.py recipient@example.org 7
The template lives in the control panel; the request only carries its id and the
variables. Prefer this over building HTML yourself whenever the values come from
your own users: template values are inserted as text, so they cannot break your
markup open.
"""
import json
import os
import sys
import urllib.error
import urllib.request
API_BASE = "https://api.sendpier.com"
def sendpier_request(method, path, body=None, timeout=30):
"""One request to the Send API.
Returns (status, parsed_body_or_None, raw_text).
"""
key = os.environ.get("SENDPIER_API_KEY", "")
domain = os.environ.get("SENDPIER_DOMAIN", "")
if not key or not domain:
sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first")
headers = {
"Authorization": "Bearer " + key,
"X-Domain-Name": domain,
"Accept": "application/json",
}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(API_BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.status
raw = response.read().decode("utf-8")
except urllib.error.HTTPError as error:
status = error.code
raw = error.read().decode("utf-8", "replace")
except urllib.error.URLError as error:
sys.exit("connection failed: {}".format(error.reason))
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
return status, parsed, raw
def main():
recipient = sys.argv[1] if len(sys.argv) > 1 else ""
template_id = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 0
sender = os.environ.get("SENDPIER_FROM", "")
if not recipient or template_id <= 0 or not sender:
sys.exit(
"usage: SENDPIER_FROM=orders@example.com "
"python3 send_with_template.py <recipient@example.org> <template_id>"
)
status, body, raw = sendpier_request(
"POST",
"/v1/messages",
{
"from": {"email": sender},
"to": [{"email": recipient}],
"template_id": template_id,
# Send every variable the template uses. Miss one and the whole
# request is refused with 422 missing_template_variables, naming the
# fields you left out -- so nobody receives a half-filled message.
#
# Values under an email address apply to that recipient only and win
# from the general ones:
# {"ordernummer": "A-1", "jan@example.org": {"voornaam": "Jan"}}
"variables": {
"voornaam": "Jan",
"ordernummer": "A-1024",
},
# "html" or "text" next to a template_id is refused with 422
# template_body_conflict: the body comes from the template. Your own
# "subject" is allowed and overrides the one of the template.
},
)
print(raw)
if status != 202:
sys.exit("request failed with HTTP {}".format(status))
for message in (body or {}).get("data", []):
print("queued {} for {}".format(message.get("id"), message.get("to")), file=sys.stderr)
if __name__ == "__main__":
main()
Berichten opvragen
Eén bestand doet allebei. Zonder argument haalt het de recentste berichten op;
met een msg_-kenmerk zoekt het dat ene bericht op. Let op het verschil tussen
de twee antwoorden. De lijst geeft de interne stand van een bericht terug, de
enkelvoudige opvraag de publieke. Zie Berichten opvragen en
Eén bericht opvragen.
cURL
#!/usr/bin/env bash
#
# SendPier Send API — look up one message, or list the most recent ones.
#
# Requirements: bash and curl.
#
# Usage:
# export SENDPIER_API_KEY='sp_live_...'
# export SENDPIER_DOMAIN='example.com'
# ./get-message.sh # the five most recent messages
# ./get-message.sh 20 # the twenty most recent messages
# ./get-message.sh msg_5f1c9a... # one message by its identifier
#
# Mind the difference between the two answers: the list returns the internal
# status of a message, the single lookup returns the public one (queued,
# delivered, bounced, complained, failed). Compare like with like, or -- better
# -- let a webhook tell you and stop asking.
set -euo pipefail
API_BASE='https://api.sendpier.com'
: "${SENDPIER_API_KEY:?set SENDPIER_API_KEY to your Send API key}"
: "${SENDPIER_DOMAIN:?set SENDPIER_DOMAIN to the domain the key belongs to}"
argument="${1:-5}"
if [ "${argument#msg_}" != "$argument" ]; then
# An identifier: ask for exactly that message.
url="${API_BASE}/v1/messages/${argument}"
else
# A number: the list endpoint. limit is clamped to 1..20, and defaults to 5.
url="${API_BASE}/v1/messages?limit=${argument}"
fi
response=$(curl -sS "$url" \
-H "Authorization: Bearer ${SENDPIER_API_KEY}" \
-H "X-Domain-Name: ${SENDPIER_DOMAIN}" \
-H 'Accept: application/json' \
-w '\n%{http_code}')
status=$(printf '%s' "$response" | tail -n1)
payload=$(printf '%s' "$response" | sed '$d')
echo "$payload"
if [ "$status" != '200' ]; then
# 404 message_not_found also covers "this identifier belongs to another
# domain" -- the key only ever sees its own domain.
echo "request failed with HTTP ${status}" >&2
exit 1
fi
PHP
<?php
/**
* SendPier Send API — look up one message, or list the most recent ones.
*
* Requirements: PHP 8.1 or newer with the curl extension. No packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* php get-message.php # the five most recent messages
* php get-message.php 20 # the twenty most recent messages
* php get-message.php msg_5f1c9a... # one message by its identifier
*
* Mind the difference between the two answers: the list returns the internal
* status of a message, the single lookup returns the public one (queued,
* delivered, bounced, complained, failed). Compare like with like, or -- better
* -- let a webhook tell you and stop asking.
*/
declare(strict_types=1);
const API_BASE = 'https://api.sendpier.com';
/**
* One request to the Send API.
*
* @return array{status: int, body: array<string, mixed>|null, raw: string}
*/
function sendpier_get(string $path): array
{
$key = getenv('SENDPIER_API_KEY');
$domain = getenv('SENDPIER_DOMAIN');
if ($key === false || $key === '' || $domain === false || $domain === '') {
fwrite(STDERR, "set SENDPIER_API_KEY and SENDPIER_DOMAIN first\n");
exit(78);
}
$handle = curl_init(API_BASE.$path);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_TIMEOUT, 30);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$key,
'X-Domain-Name: '.$domain,
'Accept: application/json',
]);
$raw = curl_exec($handle);
if ($raw === false) {
$error = curl_error($handle);
curl_close($handle);
fwrite(STDERR, "connection failed: {$error}\n");
exit(1);
}
$status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$decoded = json_decode((string) $raw, true);
return [
'status' => $status,
'body' => is_array($decoded) ? $decoded : null,
'raw' => (string) $raw,
];
}
$argument = $argv[1] ?? '5';
if (str_starts_with($argument, 'msg_')) {
// An identifier: ask for exactly that message. The path segment is an
// identifier we handed out ourselves, so urlencode is belt and braces.
$response = sendpier_get('/v1/messages/'.rawurlencode($argument));
} else {
// A number: the list endpoint. limit is clamped to 1..20 and defaults to 5.
$response = sendpier_get('/v1/messages?limit='.max(1, min(20, (int) $argument)));
}
echo $response['raw'], "\n";
if ($response['status'] !== 200) {
// 404 message_not_found also covers "this identifier belongs to another
// domain" -- a key only ever sees its own.
fwrite(STDERR, "request failed with HTTP {$response['status']}\n");
exit(1);
}
// The single lookup answers one message object, the list answers a "messages"
// array. Wrapping the first in an array lets one loop print both.
$messages = $response['body']['messages'] ?? [$response['body']];
foreach ($messages as $message) {
if (! is_array($message)) {
continue;
}
fwrite(STDERR, sprintf(
"%s %-28s %s\n",
$message['status'] ?? '?',
// The single lookup names the recipient "to", the list "to_email".
$message['to'] ?? $message['to_email'] ?? '?',
$message['subject'] ?? ''
));
}
Node.js
/**
* SendPier Send API — look up one message, or list the most recent ones.
*
* Requirements: Node.js 18 or newer. Built-in fetch only, no packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* node get-message.mjs # the five most recent messages
* node get-message.mjs 20 # the twenty most recent messages
* node get-message.mjs msg_5f1c9a... # one message by its identifier
*
* Mind the difference between the two answers: the list returns the internal
* status of a message, the single lookup returns the public one (queued,
* delivered, bounced, complained, failed). Compare like with like, or -- better
* -- let a webhook tell you and stop asking.
*/
const API_BASE = 'https://api.sendpier.com';
/** One GET to the Send API. */
async function sendpierGet(path) {
const key = process.env.SENDPIER_API_KEY;
const domain = process.env.SENDPIER_DOMAIN;
if (!key || !domain) {
console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first');
process.exit(78);
}
const response = await fetch(`${API_BASE}${path}`, {
headers: {
Authorization: `Bearer ${key}`,
'X-Domain-Name': domain,
Accept: 'application/json',
},
signal: AbortSignal.timeout(30_000),
});
const raw = await response.text();
let parsed = null;
try {
parsed = JSON.parse(raw);
} catch {
// Keep the raw text: status code and body both belong in your log.
}
return { status: response.status, body: parsed, raw };
}
const argument = process.argv[2] ?? '5';
const response = argument.startsWith('msg_')
// An identifier: ask for exactly that message.
? await sendpierGet(`/v1/messages/${encodeURIComponent(argument)}`)
// A number: the list endpoint. limit is clamped to 1..20 and defaults to 5.
: await sendpierGet(`/v1/messages?limit=${Math.min(20, Math.max(1, Number.parseInt(argument, 10) || 5))}`);
console.log(response.raw);
if (response.status !== 200) {
// 404 message_not_found also covers "this identifier belongs to another
// domain" -- a key only ever sees its own.
console.error(`request failed with HTTP ${response.status}`);
process.exit(1);
}
// The single lookup answers one message object, the list answers a "messages"
// array. Wrapping the first in an array lets one loop print both.
const messages = response.body?.messages ?? [response.body];
for (const message of messages) {
if (!message) {
continue;
}
console.error([
message.status ?? '?',
// The single lookup names the recipient "to", the list "to_email".
(message.to ?? message.to_email ?? '?').padEnd(28),
message.subject ?? '',
].join(' '));
}
Python
#!/usr/bin/env python3
"""SendPier Send API — look up one message, or list the most recent ones.
Requirements: Python 3.9 or newer. Standard library only, no packages.
Usage:
export SENDPIER_API_KEY='sp_live_...'
export SENDPIER_DOMAIN='example.com'
python3 get_message.py # the five most recent messages
python3 get_message.py 20 # the twenty most recent messages
python3 get_message.py msg_5f1c9a... # one message by its identifier
Mind the difference between the two answers: the list returns the internal
status of a message, the single lookup returns the public one (queued,
delivered, bounced, complained, failed). Compare like with like, or -- better --
let a webhook tell you and stop asking.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
API_BASE = "https://api.sendpier.com"
def sendpier_get(path, timeout=30):
"""One GET to the Send API.
Returns (status, parsed_body_or_None, raw_text).
"""
key = os.environ.get("SENDPIER_API_KEY", "")
domain = os.environ.get("SENDPIER_DOMAIN", "")
if not key or not domain:
sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first")
request = urllib.request.Request(
API_BASE + path,
headers={
"Authorization": "Bearer " + key,
"X-Domain-Name": domain,
"Accept": "application/json",
},
method="GET",
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.status
raw = response.read().decode("utf-8")
except urllib.error.HTTPError as error:
status = error.code
raw = error.read().decode("utf-8", "replace")
except urllib.error.URLError as error:
sys.exit("connection failed: {}".format(error.reason))
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
return status, parsed, raw
def main():
argument = sys.argv[1] if len(sys.argv) > 1 else "5"
if argument.startswith("msg_"):
# An identifier: ask for exactly that message.
status, body, raw = sendpier_get("/v1/messages/" + urllib.parse.quote(argument))
else:
# A number: the list endpoint. limit is clamped to 1..20, default 5.
limit = int(argument) if argument.isdigit() else 5
status, body, raw = sendpier_get("/v1/messages?limit={}".format(max(1, min(20, limit))))
print(raw)
if status != 200:
# 404 message_not_found also covers "this identifier belongs to another
# domain" -- a key only ever sees its own.
sys.exit("request failed with HTTP {}".format(status))
# The single lookup answers one message object, the list answers a
# "messages" array. Wrapping the first in a list lets one loop print both.
messages = (body or {}).get("messages", [body])
for message in messages:
if not isinstance(message, dict):
continue
print(
"{} {:<28} {}".format(
message.get("status", "?"),
# The single lookup names the recipient "to", the list
# "to_email".
message.get("to") or message.get("to_email") or "?",
message.get("subject", ""),
),
file=sys.stderr,
)
if __name__ == "__main__":
main()
Je verbruik opvragen
Vraag je verbruik op vóór een grote verzending, niet erna. Is je tegoed op, dan weigeren we elk volgend bericht. Dat blijft zo tot je nieuwe periode begint of tot je credits bijkoopt.
cURL
#!/usr/bin/env bash
#
# SendPier Send API — read how much of your allowance is left.
#
# Requirements: bash and curl.
#
# Usage:
# export SENDPIER_API_KEY='sp_live_...'
# export SENDPIER_DOMAIN='example.com'
# ./get-quota.sh
#
# The answer holds domain, monthly_limit, used_this_month and remaining. The
# figures are those of the running period of this one domain -- a key never
# sees another domain.
#
# Check this before a large batch rather than after a 429: once the allowance
# is spent, every further message is refused with quota_exceeded until the
# period rolls over or you add credits.
set -euo pipefail
API_BASE='https://api.sendpier.com'
: "${SENDPIER_API_KEY:?set SENDPIER_API_KEY to your Send API key}"
: "${SENDPIER_DOMAIN:?set SENDPIER_DOMAIN to the domain the key belongs to}"
response=$(curl -sS "${API_BASE}/v1/quota" \
-H "Authorization: Bearer ${SENDPIER_API_KEY}" \
-H "X-Domain-Name: ${SENDPIER_DOMAIN}" \
-H 'Accept: application/json' \
-w '\n%{http_code}')
status=$(printf '%s' "$response" | tail -n1)
payload=$(printf '%s' "$response" | sed '$d')
echo "$payload"
if [ "$status" != '200' ]; then
echo "request failed with HTTP ${status}" >&2
exit 1
fi
PHP
<?php
/**
* SendPier Send API — read how much of your allowance is left.
*
* Requirements: PHP 8.1 or newer with the curl extension. No packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* php get-quota.php
*
* Check this before a large batch rather than after a 429: once the allowance
* is spent, every further message is refused with quota_exceeded until the
* period rolls over or you add credits.
*/
declare(strict_types=1);
const API_BASE = 'https://api.sendpier.com';
/**
* One request to the Send API.
*
* @return array{status: int, body: array<string, mixed>|null, raw: string}
*/
function sendpier_get(string $path): array
{
$key = getenv('SENDPIER_API_KEY');
$domain = getenv('SENDPIER_DOMAIN');
if ($key === false || $key === '' || $domain === false || $domain === '') {
fwrite(STDERR, "set SENDPIER_API_KEY and SENDPIER_DOMAIN first\n");
exit(78);
}
$handle = curl_init(API_BASE.$path);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_TIMEOUT, 30);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$key,
'X-Domain-Name: '.$domain,
'Accept: application/json',
]);
$raw = curl_exec($handle);
if ($raw === false) {
$error = curl_error($handle);
curl_close($handle);
fwrite(STDERR, "connection failed: {$error}\n");
exit(1);
}
$status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$decoded = json_decode((string) $raw, true);
return [
'status' => $status,
'body' => is_array($decoded) ? $decoded : null,
'raw' => (string) $raw,
];
}
$response = sendpier_get('/v1/quota');
echo $response['raw'], "\n";
if ($response['status'] !== 200) {
fwrite(STDERR, "request failed with HTTP {$response['status']}\n");
exit(1);
}
$quota = $response['body'] ?? [];
fwrite(STDERR, sprintf(
"%s: %d of %d used, %d left this period\n",
(string) ($quota['domain'] ?? '?'),
(int) ($quota['used_this_month'] ?? 0),
(int) ($quota['monthly_limit'] ?? 0),
(int) ($quota['remaining'] ?? 0)
));
// A pause before you run out is cheaper than a batch that dies halfway.
if ((int) ($quota['remaining'] ?? 0) < 100) {
fwrite(STDERR, "warning: fewer than 100 messages left\n");
}
Node.js
/**
* SendPier Send API — read how much of your allowance is left.
*
* Requirements: Node.js 18 or newer. Built-in fetch only, no packages.
*
* Usage:
* export SENDPIER_API_KEY='sp_live_...'
* export SENDPIER_DOMAIN='example.com'
* node get-quota.mjs
*
* Check this before a large batch rather than after a 429: once the allowance
* is spent, every further message is refused with quota_exceeded until the
* period rolls over or you add credits.
*/
const API_BASE = 'https://api.sendpier.com';
/** One GET to the Send API. */
async function sendpierGet(path) {
const key = process.env.SENDPIER_API_KEY;
const domain = process.env.SENDPIER_DOMAIN;
if (!key || !domain) {
console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first');
process.exit(78);
}
const response = await fetch(`${API_BASE}${path}`, {
headers: {
Authorization: `Bearer ${key}`,
'X-Domain-Name': domain,
Accept: 'application/json',
},
signal: AbortSignal.timeout(30_000),
});
const raw = await response.text();
let parsed = null;
try {
parsed = JSON.parse(raw);
} catch {
// Keep the raw text: status code and body both belong in your log.
}
return { status: response.status, body: parsed, raw };
}
const response = await sendpierGet('/v1/quota');
console.log(response.raw);
if (response.status !== 200) {
console.error(`request failed with HTTP ${response.status}`);
process.exit(1);
}
const quota = response.body ?? {};
console.error(
`${quota.domain}: ${quota.used_this_month} of ${quota.monthly_limit} used, ${quota.remaining} left this period`
);
// A pause before you run out is cheaper than a batch that dies halfway.
if ((quota.remaining ?? 0) < 100) {
console.error('warning: fewer than 100 messages left');
}
Python
#!/usr/bin/env python3
"""SendPier Send API — read how much of your allowance is left.
Requirements: Python 3.9 or newer. Standard library only, no packages.
Usage:
export SENDPIER_API_KEY='sp_live_...'
export SENDPIER_DOMAIN='example.com'
python3 get_quota.py
Check this before a large batch rather than after a 429: once the allowance is
spent, every further message is refused with quota_exceeded until the period
rolls over or you add credits.
"""
import json
import os
import sys
import urllib.error
import urllib.request
API_BASE = "https://api.sendpier.com"
def sendpier_get(path, timeout=30):
"""One GET to the Send API.
Returns (status, parsed_body_or_None, raw_text).
"""
key = os.environ.get("SENDPIER_API_KEY", "")
domain = os.environ.get("SENDPIER_DOMAIN", "")
if not key or not domain:
sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first")
request = urllib.request.Request(
API_BASE + path,
headers={
"Authorization": "Bearer " + key,
"X-Domain-Name": domain,
"Accept": "application/json",
},
method="GET",
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.status
raw = response.read().decode("utf-8")
except urllib.error.HTTPError as error:
status = error.code
raw = error.read().decode("utf-8", "replace")
except urllib.error.URLError as error:
sys.exit("connection failed: {}".format(error.reason))
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
return status, parsed, raw
def main():
status, body, raw = sendpier_get("/v1/quota")
print(raw)
if status != 200:
sys.exit("request failed with HTTP {}".format(status))
quota = body or {}
print(
"{}: {} of {} used, {} left this period".format(
quota.get("domain"),
quota.get("used_this_month"),
quota.get("monthly_limit"),
quota.get("remaining"),
),
file=sys.stderr,
)
# A pause before you run out is cheaper than a batch that dies halfway.
if (quota.get("remaining") or 0) < 100:
print("warning: fewer than 100 messages left", file=sys.stderr)
if __name__ == "__main__":
main()
Een webhook ontvangen
Een goede ontvanger doet vier dingen. Hij bekijkt elke v1-waarde in de header:
na het vernieuwen van een geheim staan er 24 uur lang twee handtekeningen in, en
één die klopt is genoeg. Hij tekent over de ruwe body: de bytes
zoals ze binnenkwamen, niet over een object dat je zelf opnieuw hebt opgebouwd.
Hij vergelijkt de handtekening in constante tijd — met een functie die er altijd
even lang over doet, zodat de duur van de vergelijking niets over de handtekening
verraadt. En hij kijkt naar de tijdstempel, zodat een onderschept verzoek niet
uren later opnieuw kan worden afgespeeld. Alle vier zitten in deze bestanden.
Elk voorbeeld is direct te starten en luistert op poort 8080. Zet er in
productie je eigen webserver voor; wij versturen uitsluitend naar een
https-adres. De volledige uitleg staat in Webhooks: technische referentie.
PHP
<?php
/**
* SendPier webhooks — a receiver that verifies the signature.
*
* Requirements: PHP 8.1 or newer. No extensions, no packages.
*
* Try it out:
* export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page
* php -S 127.0.0.1:8080 webhook-receiver.php
*
* In production this file sits behind your own web server on an https address;
* we refuse a plain http address when you enter it.
*
* THE ORDER MATTERS
* 1. read the RAW body, before any framework turns it into an object;
* 2. verify the signature -- if it does not match: 400, and process nothing;
* 3. check whether you already know this id; if so: 200 and stop;
* 4. put the event on your own queue;
* 5. answer 200;
* 6. process it afterwards, outside the request.
*
* Step 5 before step 6 is the whole point: the timeout is ten seconds, and
* every timeout earns you the same event again.
*/
declare(strict_types=1);
/** How far the timestamp may be off, in seconds. */
const TOLERANCE_SECONDS = 300;
/**
* Is this request really ours?
*
* The `X-SendPier-Signature` header reads `t=<unixtime>,v1=<hex>`. The hex is
* HMAC-SHA256 over the literal text "<unixtime>.<body>", keyed with the secret
* of that endpoint. PHP hands that header over as HTTP_X_SENDPIER_SIGNATURE.
*
* For 24 hours after you renew the secret the header carries TWO signatures:
* `t=<unixtime>,v1=<hex with the new secret>,v1=<hex with the old secret>`.
* Collect every `v1` and accept the request if any one of them matches. This
* is what lets you switch to the new secret at your own pace.
*/
function sendpier_signature_is_valid(string $secret, string $header, string $body, int $tolerance = TOLERANCE_SECONDS): bool
{
$timestamp = null;
$candidates = [];
foreach (explode(',', $header) as $part) {
if (str_contains($part, '=')) {
[$name, $value] = explode('=', trim($part), 2);
if ($name === 't') {
$timestamp = $value;
} elseif ($name === 'v1' && $value !== '') {
$candidates[] = $value;
}
}
}
if ($timestamp === null || $timestamp === '' || $candidates === []) {
return false;
}
// Without the age check an intercepted request stays replayable for as long
// as the secret lives: the signature itself never expires.
if (abs(time() - (int) $timestamp) > $tolerance) {
return false;
}
$expected = hash_hmac('sha256', $timestamp.'.'.$body, $secret);
// Constant time, and for every value: a plain === leaks, through its own
// running time, how many leading characters of a guess were right. Do not
// stop at the first match, so the running time does not tell which of the
// two signatures was the right one.
$valid = false;
foreach ($candidates as $candidate) {
if (hash_equals($expected, $candidate)) {
$valid = true;
}
}
return $valid;
}
$secret = getenv('SENDPIER_WEBHOOK_SECRET');
if ($secret === false || $secret === '') {
http_response_code(500);
error_log('SENDPIER_WEBHOOK_SECRET is not set');
exit;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit;
}
// The raw bytes we sent. Re-serialising an object shifts a space or a key
// order, and then the signature no longer matches.
$body = (string) file_get_contents('php://input');
$header = (string) ($_SERVER['HTTP_X_SENDPIER_SIGNATURE'] ?? '');
if (! sendpier_signature_is_valid($secret, $header, $body)) {
http_response_code(400);
error_log('refused a webhook delivery with an invalid signature');
exit;
}
$event = json_decode($body, true);
if (! is_array($event) || ! isset($event['id'], $event['event'])) {
http_response_code(400);
exit;
}
/*
| Deduplicate on `id` (the same number as the X-SendPier-Delivery header) and
| order on `occurred_at`. We queue every event once, but a delivery that
| answers too late gets it again, and a retry from yesterday can arrive after a
| fresh event. Process an event you already know silently and answer 200.
|
| if ($store->hasEvent($event['id'])) { http_response_code(200); exit; }
| $store->queue($event);
*/
http_response_code(200);
// Everything below runs after the answer is on its way. In a real application
// this is where you hand the event to your queue worker instead.
error_log(sprintf(
'webhook %s: %s for %s',
(string) $event['id'],
(string) $event['event'],
(string) ($event['data']['to'] ?? $event['data']['domain'] ?? 'unknown')
));
Node.js
/**
* SendPier webhooks — a receiver that verifies the signature.
*
* Requirements: Node.js 18 or newer. Built-in node:http and node:crypto, no
* packages -- so no Express either; the interesting part is the raw body, and
* that is what a framework tends to take away from you.
*
* Try it out:
* export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page
* node webhook-receiver.mjs
*
* In production this listens behind your own https address; we refuse a plain
* http address when you enter it.
*
* USING EXPRESS INSTEAD? Ask for the raw body on this one route:
* app.post('/hooks/sendpier', express.raw({ type: 'application/json' }), handler)
* and verify over `req.body.toString('utf8')`. A JSON parser hands you an
* object, and re-serialising that object shifts a space or a key order -- after
* which the signature no longer matches.
*
* THE ORDER MATTERS
* 1. read the RAW body;
* 2. verify the signature -- if it does not match: 400, and process nothing;
* 3. check whether you already know this id; if so: 200 and stop;
* 4. put the event on your own queue;
* 5. answer 200;
* 6. process it afterwards, outside the request.
*
* Step 5 before step 6 is the whole point: the timeout is ten seconds, and
* every timeout earns you the same event again.
*/
import { createHmac, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
/** How far the timestamp may be off, in seconds. */
const TOLERANCE_SECONDS = 300;
const PORT = Number.parseInt(process.env.PORT ?? '8080', 10);
/**
* Is this request really ours?
*
* The `X-SendPier-Signature` header reads `t=<unixtime>,v1=<hex>`. The hex is
* HMAC-SHA256 over the literal text "<unixtime>.<body>", keyed with the secret
* of that endpoint. Node lowercases header names, hence the lookup below.
*
* For 24 hours after you renew the secret the header carries TWO signatures:
* `t=<unixtime>,v1=<hex with the new secret>,v1=<hex with the old secret>`.
* Collect every `v1` and accept the request if any one of them matches. This
* is what lets you switch to the new secret at your own pace.
*/
function signatureIsValid(secret, header, body, tolerance = TOLERANCE_SECONDS) {
let timestamp = null;
const candidates = [];
for (const part of header.split(',')) {
const index = part.indexOf('=');
if (index === -1) {
continue;
}
const key = part.slice(0, index).trim();
const value = part.slice(index + 1);
if (key === 't') {
timestamp = value;
} else if (key === 'v1') {
candidates.push(value);
}
}
if (!timestamp || candidates.length === 0) {
return false;
}
// Without the age check an intercepted request stays replayable for as long
// as the secret lives: the signature itself never expires.
if (!(Math.abs(Date.now() / 1000 - Number(timestamp)) <= tolerance)) {
return false;
}
const expected = Buffer.from(
createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex'),
'utf8'
);
// timingSafeEqual throws on a length mismatch, so compare the lengths first.
// A plain === would leak, through its own running time, how many leading
// characters of a guess were right. Check every value and do not stop at the
// first match, so the running time does not tell which signature was right.
let valid = false;
for (const candidate of candidates) {
const given = Buffer.from(candidate, 'utf8');
if (given.length === expected.length && timingSafeEqual(expected, given)) {
valid = true;
}
}
return valid;
}
const secret = process.env.SENDPIER_WEBHOOK_SECRET;
if (!secret) {
console.error('SENDPIER_WEBHOOK_SECRET is not set');
process.exit(78);
}
createServer((request, response) => {
if (request.method !== 'POST') {
response.writeHead(405).end();
return;
}
// Collect the bytes ourselves: this is the body we signed.
const chunks = [];
request.on('data', (chunk) => chunks.push(chunk));
request.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
const header = request.headers['x-sendpier-signature'] ?? '';
if (!signatureIsValid(secret, String(header), body)) {
console.error('refused a webhook delivery with an invalid signature');
response.writeHead(400).end();
return;
}
let event;
try {
event = JSON.parse(body);
} catch {
response.writeHead(400).end();
return;
}
if (!event?.id || !event?.event) {
response.writeHead(400).end();
return;
}
/*
| Deduplicate on `id` (the same number as the X-SendPier-Delivery header)
| and order on `occurred_at`. We queue every event once, but a delivery
| that answers too late gets it again, and a retry from yesterday can
| arrive after a fresh event. Process an event you already know silently
| and answer 200:
|
| if (await store.hasEvent(event.id)) { response.writeHead(200).end(); return; }
| await store.queue(event);
*/
response.writeHead(200).end();
// Everything below runs after the answer is on its way. In a real
// application this is where you hand the event to your queue worker.
console.log(`webhook ${event.id}: ${event.event} for ${event.data?.to ?? event.data?.domain ?? 'unknown'}`);
});
}).listen(PORT, () => console.error(`listening for SendPier webhooks on port ${PORT}`));
Python
#!/usr/bin/env python3
"""SendPier webhooks — a receiver that verifies the signature.
Requirements: Python 3.9 or newer. Standard library only, no packages -- so no
Flask either; the interesting part is the raw body, and that is what a framework
tends to take away from you.
Try it out:
export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page
python3 webhook_receiver.py
In production this listens behind your own https address; we refuse a plain http
address when you enter it.
USING FLASK INSTEAD? Read the raw body with `request.get_data(as_text=True)` and
verify over that, not over `request.json`. A JSON parser hands you an object, and
re-serialising that object shifts a space or a key order -- after which the
signature no longer matches.
THE ORDER MATTERS
1. read the RAW body;
2. verify the signature -- if it does not match: 400, and process nothing;
3. check whether you already know this id; if so: 200 and stop;
4. put the event on your own queue;
5. answer 200;
6. process it afterwards, outside the request.
Step 5 before step 6 is the whole point: the timeout is ten seconds, and every
timeout earns you the same event again.
"""
import hashlib
import hmac
import json
import os
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# How far the timestamp may be off, in seconds.
TOLERANCE_SECONDS = 300
PORT = int(os.environ.get("PORT", "8080"))
def signature_is_valid(secret, header, body, tolerance=TOLERANCE_SECONDS):
"""Is this request really ours?
The header reads `t=<unixtime>,v1=<hex>`. The hex is HMAC-SHA256 over the
literal text "<unixtime>.<body>", keyed with the secret of that endpoint.
For 24 hours after you renew the secret the header carries TWO signatures:
`t=<unixtime>,v1=<hex with the new secret>,v1=<hex with the old secret>`.
Collect every `v1` and accept the request if any one of them matches. This
is what lets you switch to the new secret at your own pace.
"""
timestamp_text = None
candidates = []
for part in header.split(","):
if "=" not in part:
continue
key, value = part.split("=", 1)
key = key.strip()
if key == "t":
timestamp_text = value
elif key == "v1":
candidates.append(value)
if timestamp_text is None or not candidates:
return False
try:
timestamp = int(timestamp_text)
except ValueError:
return False
# Without the age check an intercepted request stays replayable for as long
# as the secret lives: the signature itself never expires.
if abs(time.time() - timestamp) > tolerance:
return False
expected = hmac.new(
secret.encode("utf-8"),
"{}.{}".format(timestamp_text, body).encode("utf-8"),
hashlib.sha256,
).hexdigest()
# Constant time, and for every value: a plain == leaks, through its own
# running time, how many leading characters of a guess were right. Do not
# stop at the first match, so the running time does not tell which of the
# two signatures was the right one.
valid = False
for candidate in candidates:
if hmac.compare_digest(expected.encode(), candidate.encode()):
valid = True
return valid
class WebhookHandler(BaseHTTPRequestHandler):
"""One SendPier delivery."""
# The default logger writes a line per request to stderr; keep it quiet so
# our own lines stand out.
def log_message(self, format, *args): # noqa: A002 - signature is fixed
pass
def do_POST(self): # noqa: N802 - the base class dictates the name
secret = os.environ["SENDPIER_WEBHOOK_SECRET"]
length = int(self.headers.get("Content-Length") or 0)
# The raw bytes we sent, read before anything turns them into an object.
body = self.rfile.read(length).decode("utf-8", "replace")
header = self.headers.get("X-SendPier-Signature", "")
if not signature_is_valid(secret, header, body):
print("refused a webhook delivery with an invalid signature", file=sys.stderr)
self.send_response(400)
self.end_headers()
return
try:
event = json.loads(body)
except ValueError:
self.send_response(400)
self.end_headers()
return
if not isinstance(event, dict) or "id" not in event or "event" not in event:
self.send_response(400)
self.end_headers()
return
# Deduplicate on `id` (the same number as the X-SendPier-Delivery
# header) and order on `occurred_at`. We queue every event once, but a
# delivery that answers too late gets it again, and a retry from
# yesterday can arrive after a fresh event. Process an event you already
# know silently and answer 200:
#
# if store.has_event(event["id"]):
# self.send_response(200); self.end_headers(); return
# store.queue(event)
self.send_response(200)
self.end_headers()
# Everything below runs after the answer is on its way. In a real
# application this is where you hand the event to your queue worker.
data = event.get("data") or {}
print(
"webhook {}: {} for {}".format(
event["id"], event["event"], data.get("to") or data.get("domain") or "unknown"
),
file=sys.stderr,
)
def main():
if not os.environ.get("SENDPIER_WEBHOOK_SECRET"):
sys.exit("SENDPIER_WEBHOOK_SECRET is not set")
print("listening for SendPier webhooks on port {}".format(PORT), file=sys.stderr)
ThreadingHTTPServer(("127.0.0.1", PORT), WebhookHandler).serve_forever()
if __name__ == "__main__":
main()
Eén handtekening met de hand nakijken
Blijkt in het bezorglogboek dat jouw systeem een bezorging weigerde? Dan wil je weten of het aan de handtekening lag of aan je eigen code. Bewaar de body in een bestand, plak de header erbij en reken hem na:
#!/usr/bin/env bash
#
# SendPier webhooks — check an X-SendPier-Signature by hand.
#
# Requirements: bash, openssl.
#
# Usage:
# export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page
# ./verify-webhook-signature.sh 't=1755172800,v1=1f3a...' ./payload.json
#
# This is a debugging aid, not a receiver: it is what you run when a delivery
# in the log was refused and you want to know whether the signature or your own
# code was at fault. Real receivers belong in your application -- see
# webhook-receiver.php, webhook-receiver.mjs or webhook_receiver.py, which also
# compare in constant time.
#
# After you renew a secret, the header carries two signatures for 24 hours:
# 't=1755172800,v1=<new secret>,v1=<old secret>'
# The script collects every v1 and reports the request as valid if any one of
# them matches the secret you set.
#
# The signature is HMAC-SHA256 over the literal text "<unixtime>.<body>", keyed
# with the secret of that endpoint. The body must be the bytes we sent: a
# re-serialised object shifts a space or a key order and the signature no longer
# matches.
set -euo pipefail
TOLERANCE_SECONDS=300
: "${SENDPIER_WEBHOOK_SECRET:?set SENDPIER_WEBHOOK_SECRET to the secret of this endpoint}"
header="${1:-}"
file="${2:-}"
if [ -z "$header" ] || [ -z "$file" ]; then
echo "usage: $0 't=<unixtime>,v1=<hex>' <body-file>" >&2
exit 64
fi
if [ ! -r "$file" ]; then
echo "cannot read ${file}" >&2
exit 66
fi
timestamp=''
signatures=()
# The header is a comma separated list of key=value pairs. Reading it this way
# keeps working when a renewed secret adds a second v1 value.
IFS=',' read -ra parts <<<"$header"
for part in "${parts[@]}"; do
case "$part" in
t=*) timestamp="${part#t=}" ;;
v1=*) signatures+=("${part#v1=}") ;;
esac
done
if [ -z "$timestamp" ] || [ "${#signatures[@]}" -eq 0 ]; then
echo 'header does not carry both t and v1' >&2
exit 1
fi
age=$(( $(date +%s) - timestamp ))
[ "$age" -lt 0 ] && age=$(( -age ))
if [ "$age" -gt "$TOLERANCE_SECONDS" ]; then
# Without this check an intercepted request stays replayable for as long as
# the secret lives: the signature itself never expires.
echo "signature is ${age}s old, over the ${TOLERANCE_SECONDS}s tolerance" >&2
exit 1
fi
expected=$(
{ printf '%s.' "$timestamp"; cat "$file"; } \
| openssl dgst -sha256 -hmac "$SENDPIER_WEBHOOK_SECRET" -r \
| cut -d' ' -f1
)
# Check every v1 value; one match is enough. This is a debugging aid, so a
# plain comparison is fine here -- the receivers compare in constant time.
matched=0
for signature in "${signatures[@]}"; do
if [ "$expected" = "$signature" ]; then
matched=1
fi
done
if [ "$matched" -ne 1 ]; then
echo 'signature does not match' >&2
echo "expected ${expected}" >&2
exit 1
fi
echo 'signature is valid'
Wat er níet in deze bestanden zit
- Herhalen bij een fout. De voorbeelden stoppen bij een foutcode en tonen
hem. In je eigen systeem herhaal je alleen bij
429en503, met een oplopende wachttijd. Zie Verzoeklimieten. - Een wachtrij. De webhook-ontvangers antwoorden meteen en loggen daarna. In productie zet je de gebeurtenis op je eigen wachtrij en verwerk je hem buiten het verzoek om.
- Ontdubbelen. Waar dat hoort te gebeuren staat als commentaar in de ontvangers aangegeven. Welke sleutel je daarvoor gebruikt, staat in Webhooks: technische referentie.
Alle drie zijn ze weggelaten omdat ze afhangen van jouw omgeving. Ze zouden het voorbeeld vastzetten op keuzes die jij zelf maakt.