Add an approval step to your own code
Ask a person to approve a refund from TypeScript or Python with the official SDKs, receive the signed decision, and pay only when a person approved.
What you build#
A refund that your code pays only after a person approves it. Your code creates a task with the order details, a person approves or rejects it from an email, and your code gets the decision: first by waiting for it, then as a signed callback, which is how it runs in production.
At the end, you have a script that asks and waits, and a small receiver that verifies the callback and acts only on a person's approval.
Before you start#
- A TaskToHuman account.
- Node.js 22 or later, or Python 3.10 or newer.
- For the callback in step 6: a server reachable at a public
httpsaddress on port 443 or 8443, with a valid certificate. See Callback URL rules.
1. Create a task type#
In the app, open Task types and choose New task type. This is the refund approval the rest of these docs use:
- Name
Refund approval, Keyapprove_refund. - What should the human do? Approval.
- Fields:
order_id(text, required),amount(number, required),reason(long text) andcustomer_email(email, marked sensitive, so it appears only on the task page, never in emails or logs). - Escalation chain: add yourself as the human asked first.
- If nobody answers: Expire, so that an unanswered refund is never paid.
More in Task types and fields.
2. Create a test API key#
Open API & webhooks, then API keys, and create a key in test mode. It starts with tth_test_ and is shown once:
export TTH_API_KEY="tth_test_…"Test tasks notify only you and never count toward your usage. See Test mode.
3. Install the SDK#
npm install @tasktohuman/sdkpip install tasktohuman4. Ask and wait#
Create the task, wait for the decision, and act only on a person's approval:
import { TaskToHuman } from "@tasktohuman/sdk";
const tth = new TaskToHuman({ apiKey: process.env.TTH_API_KEY! });
const task = await tth.createTask(
{
task_type: "approve_refund",
title: "Refund €249 to order #4821?",
payload: { order_id: "4821", amount: 249, reason: "Arrived damaged", customer_email: "marta@example.com" },
deadline_minutes: 120,
},
// Names the real-world request: sending it again returns the same task instead of asking twice.
{ idempotencyKey: "refund-4821" },
);
const done = await tth.waitForDecision(task.id, { timeoutMs: 15 * 60_000 });
const decision = done.decision;
if (decision && !decision.automatic && ["approved", "edited"].includes(decision.action)) {
console.log("Refund approved by", decision.by?.name);
} else {
console.log("No refund:", decision?.action);
}import os
from tasktohuman import TaskToHuman
tth = TaskToHuman(os.environ["TTH_API_KEY"])
order_id = "4821"
task = tth.create_task(
"approve_refund",
title=f"Refund €249 to order #{order_id}?",
payload={"order_id": order_id, "amount": 249, "reason": "Arrived damaged", "customer_email": "marta@example.com"},
deadline_minutes=120,
idempotency_key=f"refund-{order_id}", # names the real-world request
)
task = tth.wait_for_decision(task["id"], timeout=900)
decision = task["decision"]
if decision and not decision["automatic"] and decision["action"] in ("approved", "edited"):
print("Refund approved by", decision["by"]["name"])
else:
print("No refund:", decision and decision["action"])Run it. You get an email; open the link and approve. The script prints that the refund was approved. Run it again with the same order: it returns the same task, because the idempotency key names the request, and you are not asked twice.
Waiting checks the task at once, then after 5 seconds, doubling up to 60 seconds, and raises a WaitTimeoutError (import it from @tasktohuman/sdk or tasktohuman; its task holds the last task read) when the time is up. It suits scripts and tests. If the field amount were editable, an edited decision would carry the changed values in decision.payload.
5. Act on the decision#
Pay the refund only when decision.action is approved or edited and decision.automatic is false. A task type's default action can finish an unanswered task as approved, with the state expired and automatic true: nobody decided then. Treat rejected, expired and cancelled as "do not pay". See the decision.
6. Receive the decision as a callback#
In production, don't keep a process waiting: let TaskToHuman post the finished task to your server. The decision arrives within seconds, survives restarts and doesn't use your rate limit.
- In the app, open API & webhooks, then Signing secrets, and choose Show secret to see the workspace's signing secret (
whsec_…). It is shown once. Keep it inTTH_SIGNING_SECRET. - Open the task type, then After the answer, and set the Callback URL to your receiver, such as
https://example.com/hooks/tasktohuman. - Run this receiver at that address:
import express from "express";
import { SignatureVerificationError, verifyCallback } from "@tasktohuman/sdk";
const app = express();
// express.raw keeps the exact bytes that were signed.
app.post("/hooks/tasktohuman", express.raw({ type: "application/json" }), async (req, res) => {
let task;
try {
task = await verifyCallback({ body: req.body, headers: req.headers, secret: process.env.TTH_SIGNING_SECRET! });
} catch (error) {
if (error instanceof SignatureVerificationError) return res.sendStatus(400);
throw error;
}
// Skip a TTH-Event-Id you already handled (a delivery can arrive twice), answer within 10 seconds,
// and pay only on a person's approval.
const decision = task.decision;
if (decision && !decision.automatic && ["approved", "edited"].includes(decision.action)) {
// Queue the refund for this task.id; do the slow work after answering.
}
res.sendStatus(204);
});
app.listen(3000);import os
from flask import Flask, abort, request
from tasktohuman import SignatureVerificationError, verify_callback
app = Flask(__name__)
@app.post("/hooks/tasktohuman")
def tasktohuman_callback():
try:
task = verify_callback(
request.get_data(), # the exact bytes that were signed
request.headers.get("TTH-Signature"),
os.environ["TTH_SIGNING_SECRET"],
)
except SignatureVerificationError:
abort(400)
# Skip a TTH-Event-Id you have already handled, and answer within 10 seconds.
decision = task["decision"]
if decision and not decision["automatic"] and decision["action"] in ("approved", "edited"):
... # queue the refund for task["id"]; do the slow work after answering
return "", 204The callback is signed with the workspace secret for test and live tasks alike, so this code needs no special case. A refused signature raises SignatureVerificationError; a missing or empty secret raises a TypeError, so an unset variable can't turn the check off.
Check it works#
Send a task again for another order, with its own idempotency key such as refund-4822 (the same key returns the task you already answered, and no new callback), and approve it. Step 4 without the waiting part is enough. Your receiver gets a POST with the finished task, "test": true and a valid TTH-Signature. Answer with any 2xx within 10 seconds. If the receiver fails, open the task in the app: it shows why the attempt failed, such as timeout or certificate_invalid, and retries follow for 24 hours.
Going live#
- Switch to a live key (
tth_live_…). Tasks then go to the humans the task type's chain names; add a backup step so a refund doesn't wait on one person (Escalation chains). - Use a real idempotency key per refund, such as the order number, on every create.
- Keep the API key and the signing secret on your server only, never in a web page or an app you ship.
- When you rotate the signing secret, pass both secrets while they overlap:
secret: [newSecret, oldSecret]in TypeScript, a list in Python.
Where next#
- SDKs: every method, error and option.
- Callbacks and signatures: the body, the retries and the rules for callback URLs.
- Approve a release from GitHub Actions: the same approval inside a workflow.