Plugins
The Rebutdesk plugin SDK, how to add a payment channel or HTTP routes, how plugins are registered, and the host extension points.
Plugins add payment channels and HTTP routes to a Rebutdesk server. Stripe and PayPal are themselves plugins built on the same SDK (packages/payments). The SDK lives in packages/plugin-sdk as @rebutdesk/plugin-sdk.
The packages are not published to npm. You write a plugin inside the monorepo (the workspace already includes a plugins/ folder for this) and register it in the server entry files.
Compatibility
The plugin contract has a version, PLUGIN_API_VERSION, currently 1. Version 1 only changes additively: new optional fields and new event kinds keep the version, and only a breaking change raises it. definePlugin() stamps your plugin with the version it was built against. The server refuses to start with a plugin that requires a newer version than it supports, and with two plugins (or two payment channels) that share an id.
What a plugin can do
interface RebutdeskPlugin {
id: string;
name: string;
version: string;
apiVersion?: number;
paymentChannels?: PaymentChannelAdapter[];
inboundChannels?: InboundChannelAdapter[];
sidebarCards?: SidebarCard[];
actions?: CaseAction[];
/** Extra HTTP routes mounted under `/plugins/<id>`. */
routes?(app: Hono): void;
}
What the server does with each part today:
| Part | Status |
|---|---|
paymentChannels |
Fully used: shown on Payment accounts, webhooks, disputes, evidence, refunds and the payments sidebar. |
routes |
Mounted at /plugins/<plugin id>/.... These routes are public: no session, no database connection and no API key check is applied, so authenticate requests yourself. |
inboundChannels |
Collected and checked for duplicate ids, but nothing calls them yet. |
sidebarCards |
Collected, but the console does not show them yet. |
actions |
Collected, but the console and API do not run them yet. |
Write against the parts marked as used. The others are part of SDK v1 so that plugins can declare them now and keep working when the host starts using them.
Payment channel adapters
A PaymentChannelAdapter connects one processor. The required members are id, name, verifyWebhook and parseWebhook; the console can only connect a channel that also has connect.
| Member | What the host does with it |
|---|---|
id, name |
id is stored on connections, disputes and payments. name appears in the console, for example on the Connect |
credentialFields |
The fields the console asks for. Fields marked secret are password inputs. Required fields and options are checked by the server. An optional field whose key starts with webhook is hidden on connect and asked for only when the webhook could not be created. Keys starting with _ are reserved and stripped from what the merchant enters. |
connect(creds, webhookUrl) |
Called when the merchant connects. Check the credentials (throw to refuse them) and create a webhook pointing at webhookUrl if the processor allows it. Return webhook: { id, secret } when you created one, or webhook: null with webhookError explaining why not. A returned secret is saved as webhookSecret; an id is kept so disconnect can delete it. |
disconnect(creds, webhookId) |
Called when the connection is removed, to delete the webhook connect created. Errors are shown to the merchant and do not block the removal. |
verifyWebhook(req, rawBody, creds) |
Called for every delivery to /api/webhooks/payments/<connection id>. Return false and the delivery is answered 400. |
parseWebhook(rawBody, creds) |
Turns a verified delivery into PaymentEvents. Re-read the object from the processor when payloads can be partial or late. Throwing makes the request fail, so the processor retries. |
submitEvidence(input, creds) |
Sends evidence. input.fields holds rebuttal (the statement) and your evidenceFields values; input.files holds the evidence PDF; input.stage asks to save without submitting. |
supportsStaging |
Shows the Stage on |
evidenceFields |
Extra fields in the evidence form. |
acceptDispute(id, creds) |
Shows Accept dispute. |
refund(input, creds) |
Enables Refund on this channel’s payments. Pass idempotencyKey on to the processor. |
listPayments(query, creds) |
Fills the payments sidebar, looked up by the buyer’s processor customer id or email. |
Of the PaymentEvent kinds, the host currently records dispute events. payment and refund events are accepted by the type but ignored. A dispute event’s payment field is how a disputed payment gets onto the case.
The host also passes <ID>_API_BASE and <ID>_FILES_BASE environment variables (with <ID> the upper-cased channel id) to your adapter as creds._apiBase and creds._filesBase, for tests against mocks. Merchants cannot set these.
A minimal plugin
This plugin adds a payment channel for a made-up processor, AcmePay, that signs webhooks with an HMAC of the body, and a public GET /plugins/acmepay/ping route. It compiles against the SDK v1 types.
import { definePlugin, type PaymentChannelAdapter, type PaymentEvent } from "@rebutdesk/plugin-sdk";
async function hmacHex(secret: string, body: string): Promise<string> {
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)));
return [...sig].map((b) => b.toString(16).padStart(2, "0")).join("");
}
const acmepay: PaymentChannelAdapter = {
id: "acmepay",
name: "AcmePay",
credentialFields: [
{ key: "apiKey", label: "API key", secret: true },
{ key: "webhookSecret", label: "Webhook secret", secret: true, optional: true, help: "Only needed when the webhook could not be created for you." },
],
async connect(creds, webhookUrl) {
// Check the key against the processor here, and create the webhook pointing at webhookUrl if its API allows it.
if (!creds.apiKey) throw new Error("API key is missing");
return { accountName: "AcmePay account", webhook: null, webhookError: `add ${webhookUrl} in AcmePay by hand` };
},
async verifyWebhook(req, rawBody, creds) {
const header = req.headers.get("acmepay-signature") ?? "";
return Boolean(creds.webhookSecret) && header === (await hmacHex(creds.webhookSecret!, rawBody));
},
async parseWebhook(rawBody) {
const e = JSON.parse(rawBody) as { type: string; dispute: { id: string; payment_id: string; amount: number; currency: string; email?: string; due?: string } };
if (e.type !== "dispute.opened") return [];
const event: PaymentEvent = {
kind: "dispute",
externalId: e.dispute.id,
paymentExternalId: e.dispute.payment_id,
status: "needs_response",
money: { amountMinor: e.dispute.amount, currency: e.dispute.currency.toUpperCase() },
dueAt: e.dispute.due ? new Date(e.dispute.due) : null,
contact: { email: e.dispute.email ?? null },
raw: e,
};
return [event];
},
};
export function acmepayPlugin() {
return definePlugin({
id: "acmepay",
name: "AcmePay",
version: "0.1.0",
paymentChannels: [acmepay],
routes(app) {
app.get("/ping", (c) => c.json({ ok: true }));
},
});
}
With this adapter, connecting AcmePay saves the key and then shows the manual webhook step with the URL to add, and the Webhook secret field to paste the secret into. Disputes then open cases like Stripe and PayPal disputes do. Without submitEvidence, acceptDispute and refund, the console offers only saving and previewing evidence for these disputes.
Registering a plugin
- Create a package under
plugins/, for exampleplugins/acmepay, with apackage.jsonthat depends on"@rebutdesk/plugin-sdk": "workspace:*"and exports your entry file. - Add the package to the dependencies of
apps/apiand runpnpm install. - Pass the plugin next to the built-in ones in both server entries.
For Node and Docker, in apps/api/src/server.ts:
const server = serveNode({
plugins: [...builtinPaymentPlugins(), acmepayPlugin()],
publicDir: env.PUBLIC_DIR ?? fileURLToPath(new URL("../public", import.meta.url).href),
});
For Cloudflare Workers, in apps/api/src/worker.ts:
export default createRebutdesk({ plugins: [...builtinPaymentPlugins(), acmepayPlugin()] });
Then build and deploy as usual (Docker, Cloudflare). Leaving out builtinPaymentPlugins() removes Stripe and PayPal.
Host extensions
Besides plugins, the server entries accept extensions: hooks that the open-source build leaves empty and that hosting setups can fill in. They are typed as Extensions in the SDK.
| Extension | What it adds |
|---|---|
mailer |
Sends email: replies on email cases, sign-in codes and team invitations. With sendingDomain, replies come from the merchant’s verified domain. The stock servers already fill it from MAIL_SMTP_URL or the SES settings; see Email. |
ai |
Hosted model endpoints, embeddings and usage metering. When it provides endpoints, workspaces cannot set their own model. |
billing, meter |
Plan checks before creating cases and usage records. |
accounts |
Decides whether an account may create workspaces. |
license |
Feature flags. |
extensions is either an object or a function that receives the environment (on Workers, secrets live there). For example, a mailer that posts to your own mail API instead of SMTP or SES, registered in apps/api/src/server.ts:
import type { Extensions } from "@rebutdesk/plugin-sdk";
import type { Env } from "./env.ts";
function myExtensions(env: Env): Extensions {
const apiKey = String((env as Record<string, unknown>).MAIL_API_KEY ?? "");
return {
mailer: {
async send(msg) {
const res = await fetch("https://mail.example.com/send", {
method: "POST",
headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
body: JSON.stringify(msg),
});
if (!res.ok) throw new Error(`mail API answered ${res.status}`);
const { id } = (await res.json()) as { id: string };
return { messageId: id };
},
},
};
}
const server = serveNode({
plugins: builtinPaymentPlugins(),
auth: { emailOtp: true },
extensions: myExtensions,
publicDir: env.PUBLIC_DIR ?? fileURLToPath(new URL("../public", import.meta.url).href),
});
Email sign-in codes need both a mailer and auth: { emailOtp: true }, which the stock entries pass. Keep it when you replace extensions.
Next: Pro license