Each call carries an API key, and a new key also wants each call signed. The signature shows that the caller holds the secret, so a key alone that leaked is not enough to write to your customers.
Make a key
Open API Management in WizMessage and choose Connect your software. Give the key the name of the system that will use it. The last step shows the key (pk_live_…) and the secret (sk_live_…) once; if you lose the secret, make a new one with Rotate Secret, and the old one stops working at that moment.
A key belongs to one WhatsApp number. Its page is also where you set an end date, change its limits, switch it off, or stop asking for signatures.
Headers of a request
| Header | Value |
|---|---|
X-API-Key | The full key. Authorization: Bearer with the same key works as well |
X-Timestamp | The time in Unix seconds. It may be 5 minutes off at most |
X-API-Signature | The signature, see below |
Permissions
A call without the permission it needs is answered with 403 and PERMISSION_DENIED. A new key has all five; take away what your system does not use.
| Permission | What it allows |
|---|---|
send_text | Text, reply buttons, lists, contact cards and reactions |
send_media | Documents, images, video and audio |
send_template | Approved templates |
view_templates | Reading the templates of the account |
view_messages | Downloading files that customers sent |
Uploading a file and looking up a message of the same key need none of them.
Sign a request
- Take the body exactly as you send it. A GET has none, so its text is empty. An upload signs only its text fields, as JSON; without text fields that text is empty too.
- Put the timestamp and a dot in front of it:
timestamp.body. - The key of the signature is the lowercase hex SHA-256 of your secret, as text.
- The signature is the lowercase hex HMAC-SHA256 of that text.
Sign the bytes that go over the wire. If a library writes the JSON again after you signed it, with other spaces or another order, the signature no longer fits.
Check your code
With these values your code must give this result. The secret is made up.
| Part | Value |
|---|---|
| Secret | sk_live_EXAMPLE |
| Key of the signature | edc352292a316877f82d4e7dddc0d64e5e9c026e5d293b5612062bb32517c03d |
| Timestamp | 1764064800 |
| Body | {"to":"+447700900123","message":"Hello"} |
| Signature | 73d39ae5d146e7c86f32234c179111106d4e622ed4fcd40c377bef36cc159c3c |
| Signature of a GET at the same time | 7d529df740b2f980a30fa519cd7e2ebc34a602d1274474c885355d80a2c9afa7 |
A client for your language
These files need nothing but the standard library of the language. The other pages use them. Every send method takes the JSON body that its call takes.
#!/usr/bin/env bash
# bash curl/wizmessage.sh <command> <to>. Run it without a command to see the list.
# Needs curl and openssl. The key and the secret come from the environment.
set -euo pipefail
BASE="${WIZMESSAGE_BASE_URL:-https://wizmessage.com/api/v1/external}"
SIGNATURE=()
# The signature covers the timestamp and the exact text of the body. For a GET and for an upload
# without text fields, that text is empty.
sign() {
SIGNATURE=()
[ -n "${WIZMESSAGE_API_SECRET:-}" ] || return 0
local timestamp key value
timestamp=$(date +%s)
key=$(printf '%s' "$WIZMESSAGE_API_SECRET" | openssl dgst -sha256 -r | cut -d' ' -f1)
value=$(printf '%s' "$timestamp.$1" | openssl dgst -sha256 -hmac "$key" -r | cut -d' ' -f1)
SIGNATURE=(-H "X-Timestamp: $timestamp" -H "X-API-Signature: $value")
}
# A call can wait its turn for 30 seconds before WhatsApp answers, hence the long timeout.
call() {
curl -sS --max-time 70 -H "X-API-Key: ${WIZMESSAGE_API_KEY:?is not set}" "${SIGNATURE[@]}" "$@"
}
post() {
sign "$2"
printf '%s' "$2" | call -X POST "$BASE$1" -H 'Content-Type: application/json' --data-binary @-
echo
}
get() {
sign ''
call "$BASE$1" "${@:2}"
}
TO="${2:-}"
EXTRA="${3:-}"
VARIABLES="${4:-}"
case "${1:-}" in
text)
post /messages/text '{"to":"'"$TO"'","message":"Your parcel is ready to collect.","reference":"order-1042"}'
;;
media)
post /messages/media '{"to":"'"$TO"'","type":"document","link":"'"$EXTRA"'","filename":"Invoice 1042.pdf","caption":"Your invoice"}'
;;
template)
[ -n "$VARIABLES" ] || VARIABLES='{}'
post /messages/template/send '{"to":"'"$TO"'","template_name":"'"$EXTRA"'","language":"en","variables":'"$VARIABLES"'}'
;;
list)
post /messages/interactive/list '{"to":"'"$TO"'","body":"When shall we deliver?","button":"Choose a time","sections":[{"title":"Tomorrow","rows":[{"id":"slot-am","title":"9:00 to 12:00"},{"id":"slot-pm","title":"13:00 to 17:00","description":"Ring the bell"}]}]}'
;;
buttons)
post /messages/interactive/button '{"to":"'"$TO"'","body":"Shall we confirm your visit?","buttons":[{"id":"yes","title":"Yes"},{"id":"no","title":"No"}]}'
;;
contacts)
post /messages/contacts '{"to":"'"$TO"'","contacts":[{"name":{"formatted_name":"Riya Example"},"phones":[{"phone":"+447700900456","type":"WORK"}]}]}'
;;
reaction)
post /messages/reaction '{"to":"'"$TO"'","message_id":"'"$EXTRA"'","emoji":"👍"}'
;;
status)
get "/messages/$TO"
echo
;;
templates)
get '/templates?limit=50'
echo
;;
upload)
sign ''
call -X POST "$BASE/media/upload" -F "file=@$TO;type=$EXTRA"
echo
;;
download)
get "/media/$TO" -o "$EXTRA" -w '%{http_code} %{content_type} %{size_download}\n'
;;
*)
cat <<'TEXT'
Commands:
text|list|buttons|contacts <to>
media <to> <link>
template <to> <name> '{"customer_name":"Riya"}'
reaction <to> <whatsapp message id>
status <message id> templates upload <file> <type> download <media id> <file>
TEXT
;;
esac// A small client for the WizMessage API. Node.js 20 or newer, no packages.
import { createHash, createHmac } from 'node:crypto'
const sha256 = (text) => createHash('sha256').update(text).digest('hex')
export class WizMessageError extends Error {
constructor(status, body) {
super(body?.error?.message ?? `HTTP ${status}`)
this.status = status
this.code = body?.error?.code
this.details = body?.error?.details
this.requestId = body?.meta?.request_id
}
}
export class WizMessage {
constructor({ apiKey, apiSecret, baseUrl = 'https://wizmessage.com/api/v1/external' }) {
this.apiKey = apiKey
this.apiSecret = apiSecret
this.baseUrl = baseUrl
}
// The signature covers the timestamp and the exact text of the body. For a GET and for an upload
// without text fields, that text is empty.
#headers(signedText) {
const headers = { 'X-API-Key': this.apiKey }
if (this.apiSecret) {
const timestamp = Math.floor(Date.now() / 1000).toString()
headers['X-Timestamp'] = timestamp
headers['X-API-Signature'] = createHmac('sha256', sha256(this.apiSecret))
.update(`${timestamp}.${signedText}`)
.digest('hex')
}
return headers
}
async #call(method, path, { body, signedText = '', headers = {} } = {}) {
const response = await fetch(this.baseUrl + path, {
method,
body,
headers: { ...this.#headers(signedText), ...headers },
// A call can wait its turn for 30 seconds before WhatsApp answers. After a timeout the message may
// be out: wait for the webhook with your reference before you send it again.
signal: AbortSignal.timeout(70_000),
})
if (!response.ok) throw new WizMessageError(response.status, await response.json().catch(() => null))
return response
}
async #post(path, data) {
const body = JSON.stringify(data)
const response = await this.#call('POST', path, {
body,
signedText: body,
headers: { 'Content-Type': 'application/json' },
})
return (await response.json()).data
}
async #get(path) {
return (await (await this.#call('GET', path)).json()).data
}
sendText(data) {
return this.#post('/messages/text', data)
}
sendMedia(data) {
return this.#post('/messages/media', data)
}
sendTemplate(data) {
return this.#post('/messages/template/send', data)
}
sendList(data) {
return this.#post('/messages/interactive/list', data)
}
sendButtons(data) {
return this.#post('/messages/interactive/button', data)
}
sendContacts(data) {
return this.#post('/messages/contacts', data)
}
sendReaction(data) {
return this.#post('/messages/reaction', data)
}
getMessage(messageId) {
return this.#get(`/messages/${encodeURIComponent(messageId)}`)
}
async listTemplates(limit = 50) {
return (await this.#get(`/templates?limit=${limit}`)).templates
}
async uploadMedia(file, filename) {
const form = new FormData()
form.append('file', file, filename)
return (await (await this.#call('POST', '/media/upload', { body: form })).json()).data
}
async downloadMedia(mediaId) {
const response = await this.#call('GET', `/media/${encodeURIComponent(mediaId)}`)
return { type: response.headers.get('content-type'), bytes: Buffer.from(await response.arrayBuffer()) }
}
}"""A small client for the WizMessage API. Python 3.10 or newer, no packages."""
import hashlib
import hmac
import json
import mimetypes
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
BASE_URL = "https://wizmessage.com/api/v1/external"
class WizMessageError(Exception):
def __init__(self, status, body):
error = (body or {}).get("error") or {}
super().__init__(error.get("message") or f"HTTP {status}")
self.status = status
self.code = error.get("code")
self.details = error.get("details")
self.request_id = ((body or {}).get("meta") or {}).get("request_id")
class WizMessage:
def __init__(self, api_key, api_secret="", base_url=None):
self.api_key = api_key
self.api_secret = api_secret
self.base_url = base_url or BASE_URL
def _headers(self, signed_bytes):
# The signature covers the timestamp and the exact bytes of the body. For a GET and for an
# upload without text fields, those bytes are empty.
headers: dict[str, str] = {"X-API-Key": self.api_key}
if self.api_secret:
timestamp = str(int(time.time()))
key = hashlib.sha256(self.api_secret.encode()).hexdigest().encode()
text = timestamp.encode() + b"." + signed_bytes
headers["X-Timestamp"] = timestamp
headers["X-API-Signature"] = hmac.new(key, text, hashlib.sha256).hexdigest()
return headers
def _call(self, method, path, body=None, signed_bytes=b"", content_type=None):
headers = self._headers(signed_bytes)
if content_type:
headers["Content-Type"] = content_type
request = urllib.request.Request(self.base_url + path, data=body, headers=headers, method=method)
try:
# A call can wait its turn for 30 seconds before WhatsApp answers. After a timeout the
# message may be out: wait for the webhook with your reference before you send it again.
return urllib.request.urlopen(request, timeout=70)
except urllib.error.HTTPError as error:
try:
answer = json.load(error)
except ValueError:
answer = None
raise WizMessageError(error.code, answer) from None
def _post(self, path, data):
body = json.dumps(data, ensure_ascii=False).encode()
with self._call("POST", path, body, body, "application/json") as response:
return json.load(response)["data"]
def _get(self, path):
with self._call("GET", path) as response:
return json.load(response)["data"]
def send_text(self, **data):
return self._post("/messages/text", data)
def send_media(self, **data):
return self._post("/messages/media", data)
def send_template(self, **data):
return self._post("/messages/template/send", data)
def send_list(self, **data):
return self._post("/messages/interactive/list", data)
def send_buttons(self, **data):
return self._post("/messages/interactive/button", data)
def send_contacts(self, **data):
return self._post("/messages/contacts", data)
def send_reaction(self, **data):
return self._post("/messages/reaction", data)
def get_message(self, message_id):
return self._get("/messages/" + urllib.parse.quote(message_id, safe=""))
def list_templates(self, limit=50):
return self._get(f"/templates?limit={limit}")["templates"]
def upload_media(self, path):
path = Path(path)
kind = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
boundary = uuid.uuid4().hex
name = path.name.replace('"', "")
head = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{name}"\r\n'
f"Content-Type: {kind}\r\n\r\n"
)
body = head.encode() + path.read_bytes() + f"\r\n--{boundary}--\r\n".encode()
with self._call(
"POST", "/media/upload", body, b"", f"multipart/form-data; boundary={boundary}"
) as response:
return json.load(response)["data"]
def download_media(self, media_id):
with self._call("GET", "/media/" + urllib.parse.quote(media_id, safe="")) as response:
return response.headers.get("Content-Type"), response.read()<?php
declare(strict_types=1);
final class WizMessageError extends RuntimeException
{
public function __construct(
public readonly int $status,
public readonly string|int|null $errorCode,
string $message,
public readonly ?string $requestId,
public readonly mixed $details = null,
) {
parent::__construct($message);
}
}
/** A small client for the WizMessage API. PHP 8.1 or newer with the curl extension, no packages. */
final class WizMessage
{
public const BASE_URL = 'https://wizmessage.com/api/v1/external';
public function __construct(
private readonly string $apiKey,
private readonly string $apiSecret = '',
private readonly string $baseUrl = self::BASE_URL,
) {
}
public function sendText(array $data): array
{
return $this->post('/messages/text', $data);
}
public function sendMedia(array $data): array
{
return $this->post('/messages/media', $data);
}
public function sendTemplate(array $data): array
{
return $this->post('/messages/template/send', $data);
}
public function sendList(array $data): array
{
return $this->post('/messages/interactive/list', $data);
}
public function sendButtons(array $data): array
{
return $this->post('/messages/interactive/button', $data);
}
public function sendContacts(array $data): array
{
return $this->post('/messages/contacts', $data);
}
public function sendReaction(array $data): array
{
return $this->post('/messages/reaction', $data);
}
public function getMessage(string $messageId): array
{
return $this->get('/messages/' . rawurlencode($messageId));
}
public function listTemplates(int $limit = 50): array
{
return $this->get('/templates?limit=' . $limit)['templates'];
}
public function uploadMedia(string $file, string $type): array
{
$form = ['file' => new CURLFile($file, $type, basename($file))];
[$answer] = $this->call('POST', '/media/upload', $form);
return json_decode($answer, true, flags: JSON_THROW_ON_ERROR)['data'];
}
/** @return array{0: string, 1: ?string} the bytes and their type */
public function downloadMedia(string $mediaId): array
{
return $this->call('GET', '/media/' . rawurlencode($mediaId));
}
/**
* The signature covers the timestamp and the exact text of the body. For a GET and for an upload
* without text fields, that text is empty.
*/
private function headers(string $signedText): array
{
$headers = ['X-API-Key: ' . $this->apiKey];
if ($this->apiSecret !== '') {
$timestamp = (string) time();
$key = hash('sha256', $this->apiSecret);
$headers[] = 'X-Timestamp: ' . $timestamp;
$headers[] = 'X-API-Signature: ' . hash_hmac('sha256', $timestamp . '.' . $signedText, $key);
}
return $headers;
}
private function call(
string $method,
string $path,
mixed $body = null,
string $signedText = '',
array $headers = [],
): array {
$curl = curl_init($this->baseUrl . $path);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
// A call can wait its turn for 30 seconds before WhatsApp answers. After a timeout the message
// may be out: wait for the webhook with your reference before you send it again.
CURLOPT_TIMEOUT => 70,
CURLOPT_HTTPHEADER => [...$this->headers($signedText), ...$headers],
]);
if ($body !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}
$answer = curl_exec($curl);
$reason = curl_error($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
curl_close($curl);
if ($answer === false) {
throw new RuntimeException($reason);
}
if ($status >= 400) {
$json = json_decode($answer, true);
throw new WizMessageError(
$status,
$json['error']['code'] ?? null,
$json['error']['message'] ?? "HTTP $status",
$json['meta']['request_id'] ?? null,
$json['error']['details'] ?? null,
);
}
return [$answer, $type];
}
private function post(string $path, array $data): array
{
$body = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
[$answer] = $this->call('POST', $path, $body, $body, ['Content-Type: application/json']);
return json_decode($answer, true, flags: JSON_THROW_ON_ERROR)['data'];
}
private function get(string $path): array
{
[$answer] = $this->call('GET', $path);
return json_decode($answer, true, flags: JSON_THROW_ON_ERROR)['data'];
}
}Keep it safe
- Only on your server. Whoever holds the key and the secret can write to your customers in your name.
- Only over https. The signature covers the time and the body, not the address of the call. Somebody who records a signed call can repeat it for 5 minutes.
- One key for each system. You can then switch one off without stopping the others.
- Rotate the secret when somebody who knew it leaves.
When a call is refused
| Status | Code | Meaning |
|---|---|---|
| 401 | INVALID_API_KEY | The key is missing or unknown. |
| 401 | INVALID_SIGNATURE | The signature does not fit the body, or is missing on a key that needs it. |
| 401 | TIMESTAMP_EXPIRED | The timestamp is more than 5 minutes off. |
| 401 | EXPIRED_API_KEY | The key has passed its end date. |
| 401 | REVOKED_API_KEY | The key was revoked. |
| 401 | SUSPENDED_API_KEY | The key is switched off. |
| 403 | IP_NOT_ALLOWED | The key has an address list and this address is not on it. |
| 403 | PERMISSION_DENIED | The key lacks this permission. AI agent keys are always refused here. |
| 403 | SUBSCRIPTION_REQUIRED | No active Wiz Bot or Wiz Pro plan, and the 7 days of grace are over. |
| 403 | ACCOUNT_NOT_ACTIVE | The WhatsApp number of the key is not active. |