Crypto subscription renewals: a daily job in Node.js
A wallet cannot be charged without its owner, so crypto has no "card on file" and easyway has no automatic recurring billing. What a SaaS can do is what it already does for bank transfers: when a period is due, issue an invoice, send the link, and extend the plan when it is paid. This post is the job that does it, run once a day, with the three places where such a job usually bills twice or not at all. We ran it on Node 22.
Three rules the job follows
| Rule | Why |
|---|---|
One order_id per subscription period | The job asks the API what already exists with GET /v1/invoices?order_id=… instead of keeping its own copy, so a crash between "created" and "saved" loses nothing. |
| Re-send an open invoice, don't replace it | A customer who opened Monday's e-mail and pays on Tuesday pays the invoice they have. Only pending invoices expire; confirming and underpaid stay payable. |
| A new Idempotency-Key per attempt | A replayed key returns the first response, even when that invoice has since expired. So the key carries an attempt number: renew-sub_8812-2026-12-2. |
The renewal job
// renew.mjs: run once a day (cron, systemd timer, a queue job). Node 18+, no npm install.
const API = process.env.EASYWAY_API ?? "https://api.easyway.cash";
const OPEN = ["pending", "confirming", "underpaid"]; // still payable; only "pending" ever expires
async function api(method, path, body, idempotencyKey) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.EASYWAY_API_KEY}`,
"Content-Type": "application/json",
...(idempotencyKey && { "Idempotency-Key": idempotencyKey }),
},
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(15_000),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(`easyway ${res.status}: ${json.message ?? json.error}`);
return json;
}
// One subscription period → one order_id. Returns the invoice the customer should pay, or null if paid.
export async function renewalInvoice(sub, period) {
const orderId = `${sub.id}-${period}`; // e.g. "sub_8812-2026-12"
const { data } = await api("GET", `/v1/invoices?order_id=${encodeURIComponent(orderId)}&pageSize=100`);
if (data.some((i) => i.status === "paid")) return null;
const open = data.find((i) => OPEN.includes(i.status) && (i.status !== "pending" || new Date(i.expires_at) > new Date()));
if (open) return open; // remind with the same link
// None open: the previous ones expired or were cancelled. A new attempt needs a NEW key, because
// replaying an old key returns the old (expired) invoice.
const attempt = data.length + 1;
return api("POST", "/v1/invoices", {
amount: sub.price, // "49.00"
currency: "USD",
order_id: orderId,
description: `${sub.plan} plan, ${period}`,
customer_email: sub.email,
metadata: { account_id: sub.accountId, plan: sub.plan, period },
success_url: "https://app.example.com/billing?paid=1",
lifetime: 1440, // 24 hours, the maximum
allowed_assets: ["USDT_TRC20", "USDT_BEP20", "USDC_ERC20", "USDC_SOL"],
}, `renew-${orderId}-${attempt}`);
}
// Your part: the subscriptions due in the next 7 days, and your mailer.
export async function runRenewals(dueSubs, period, sendReminder) {
for (const sub of dueSubs) {
try {
const inv = await renewalInvoice(sub, period);
if (inv) await sendReminder(sub.email, inv.payment_url, inv.expires_at);
} catch (err) {
console.error(sub.id, err.message); // the next run tries again; the keys stop duplicates
}
}
}lifetime is in minutes, 5 to 1,440; a day suits a link sent by e-mail, and the next run re-sends or replaces it. A pending invoice whose expires_at has passed is treated as gone even if the API has not marked it expired yet. allowed_assets limits the checkout to dollar stablecoins, so a $49 plan arrives as about 49 USDT or USDC instead of a volatile coin (see limiting the checkout to some coins). metadata takes up to 20 keys and comes back in every webhook, which is how the handler below finds the account without a lookup table.
We ran the job against a local mock of the two endpoints: the first run created invoice 1; the second sent the same link again; after invoice 1 expired, the third run created invoice 2 under the key ending in -2; an underpaid or confirming invoice was re-sent even after its expires_at; a paid period returned nothing; a bad key logged easyway 401: invalid_api_key and sent no e-mail.
Extend the plan once per period
Extend the plan from the signed invoice.paid webhook, not from the job. Verify the signature first; the Node.js post has a dependency-free verify() and the raw-body handling. Then:
// Inside the verified webhook handler from the Node.js post (verify() + raw body):
export async function onEvent(event, db) {
if (event.type !== "invoice.paid") return;
const inv = event.data.invoice;
const { account_id, period } = inv.metadata ?? {};
if (!account_id || !period) return; // not a renewal invoice
// Extend once per period, whatever arrives twice: retries, or two invoices of one period both paid.
const first = await db.markPeriodPaid(account_id, period, inv.id); // INSERT … ON CONFLICT DO NOTHING
if (first) await db.extendPlan(account_id, period);
else console.warn("second payment for", account_id, period, inv.id, "- credit or refund it by hand");
}A delivery is retried until your server answers 2xx, so the same event can arrive twice; a unique row per account and period makes the second one a no-op (we sent the same event twice and the plan was extended once). Rarely, a customer pays two invoices of one period, for example an old link after a new one went out; the code keeps the first and flags the second, which you credit to the next period or refund from your own wallet (the money went straight there, and easyway cannot send it back for you).
What the other events mean here
| Event | Status | In a subscription |
|---|---|---|
invoice.confirming | confirming | The payment is on the chain, waiting for confirmations. Do nothing; the job will not replace it. |
invoice.underpaid | underpaid | Less than the price arrived (beyond your tolerance, 1 % by default). The customer tops up on the same page, so keep the period open. |
invoice.expired | expired | Nothing was paid within the lifetime. The next run creates attempt n + 1. |
invoice.paid | paid | Final and in your own wallet: extend the plan. |
Grace periods, dunning and downgrades stay in your billing code: when the period starts with no paid invoice, your app decides whether to keep the account active a few days longer. Late and short payments are covered in the underpaid and late payments guide.
Test it without money
Point the job at a test key (sk_test_…, scopes invoices:write and invoices:read), run it, open the payment_url and press Simulate payment: a real invoice.paid reaches your webhook and the next run returns nothing for that period. The sandbox guide shows the underpaid and expired cases. Before you switch to a live key, set your receiving wallet for each network in allowed_assets (Dashboard → Wallets); otherwise live invoice creation answers 409 no_wallets_configured or wallet_not_configured. There is no fee per payment; live invoices count against your plan (30 a month on the Free plan, more on the paid ones, see pricing), and over the allowance creation answers 402 plan_invoice_limit_reached. The job above just logs that and tries again the next day; do not retry a 402 in a tight loop, it will not succeed until the plan is upgraded or the month rolls over. Test mode is never limited. The bigger picture, including several products on one account, is on crypto payments for SaaS.