<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Royi Benyossef on Medium]]></title>
        <description><![CDATA[Stories by Royi Benyossef on Medium]]></description>
        <link>https://medium.com/@royiby?source=rss-6dc14cc222f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q0I3tg-ljA2AEZpbQFp1cQ.png</url>
            <title>Stories by Royi Benyossef on Medium</title>
            <link>https://medium.com/@royiby?source=rss-6dc14cc222f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:37:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@royiby/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Every payment lands on a booking]]></title>
            <link>https://medium.com/@royiby/every-payment-lands-on-a-booking-dba3b7f5c474?source=rss-6dc14cc222f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba3b7f5c474</guid>
            <dc:creator><![CDATA[Royi Benyossef]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 07:03:49 GMT</pubDate>
            <atom:updated>2026-10-28T07:03:49.696Z</atom:updated>
            <content:encoded><![CDATA[<p>My wife runs a small business: after-school programmes, craft kits, holiday camps. Until recently, every registration lived in a notebook. Payments, invoices, who’s coming on Tuesday: all of it depended on handwritten lists and her memory.</p><p>She isn’t technical. I am, even though I’ve spent the last several years in investing roles. So I decided to build her a registration system, and to use it as a reason to get my hands dirty again, building with Claude.</p><p>This is the long version. Most of it is about one property: a parent’s payment always arrives, is always tied to a booking, and is never counted twice. It’s a small system, and most of the work went into the parts nobody sees when they work.</p><h3>What it does</h3><p>Parents get one link. They pick individual days, watch the price update, fill in the child’s details and a health declaration, sign with a finger, and pay by card. The invoice and receipt arrive by themselves. No app, no account, no phone call.</p><p>She gets a small app on her phone’s home screen: one-off payment links, today’s attendance, who hasn’t paid, cancellations and refunds, and full control of prices, dates, capacity and the terms parents sign.</p><h3>Shape</h3><p>One Node process, three surfaces, and a webhook:</p><pre>/                         parent booking page: pick days, sign, pay<br>/app                      her PWA: links, today, unpaid, cancellations, settings<br>/contract/…               a client signing a standalone contract<br>/webhooks/morning/payment the only thing that confirms a payment</pre><ul><li>Node and Express, <strong>three dependencies</strong> (express, dotenv, googleapis), no front-end framework.</li><li><strong>Google Sheets as the datastore</strong>, so camp staff can read it without being taught anything.</li><li><strong>Morning</strong> for invoicing, with <strong>Grow</strong> handling card clearing. Morning is the Israeli invoicing platform she’s obliged to use anyway.</li><li><strong>Cloudflare R2</strong> for off-site copies of signed forms, <strong>Telegram and SMTP</strong> for alerts.</li><li>Roughly $7 a month to run, and 315 test cases.</li></ul><p>The app talks to <strong>one payment API</strong>. There are no direct calls to Grow. The app asks Morning for a hosted Grow checkout, identified by a plugin id. When the card is charged, Morning issues the tax invoice-receipt itself and calls back. Clearing, the document and the callback all come from one counterparty, so there’s exactly one system to reconcile against.</p><h3>The constraint that shaped it</h3><p>The obvious build was a WhatsApp bot. She works almost entirely in WhatsApp. But putting her number on the WhatsApp Business API means losing ordinary WhatsApp on that number, and her business runs on personal conversations with parents.</p><p>The conversational flow exists. It’s in the tree, unwired:</p><pre>/**<br> * The WhatsApp Cloud API is intentionally absent: she keeps her number as a<br> * normal WhatsApp and sends links herself. src/flow.js and src/whatsapp/ are<br> * left in the tree, unwired, in case that ever changes.<br> */</pre><p>So she sends links by hand from her normal WhatsApp, and everything heavy happens on the page the parent opens. The rest of this post is about what happens on that page, and after it.</p><h3>The payment chain</h3><h3>1. The signature exists before the payment link does</h3><pre>const orderId = newOrderId();<br>// Consent first, deliberately: she must never be able to take a payment<br>// for a registration that has no signed form behind it.<br>await archiveConsent({ camp, orderId, signer, children, answers, signature,<br>  meta: { ip: req.ip ?? &#39;&#39;, userAgent: req.get(&#39;user-agent&#39;) ?? &#39;&#39; } });</pre><pre>const booking = await createBooking({ camp, orderId, parent, cart: payload.children });<br>return res.json({ orderId, paymentUrl: booking.paymentUrl });</pre><p><em>(trimmed)</em></p><p>If archiving throws, there’s no order and no link. Taking money for a registration with no signed form behind it is structurally impossible.</p><h3>2. The order row exists before the link does</h3><p>Inside createBooking, the order is written to the sheet first, and only then is Morning asked for a checkout URL. A parent who pays can always be matched back to a row, and an order whose link failed is visible to her instead of silently lost:</p><pre>} catch (error) {<br>  // The order row already exists; mark it so an abandoned row is explainable<br>  // and does not silently hold seats until its TTL expires.<br>  await store.updateOrder(orderId, { status: store.STATUS.cancelled,<br>    notes: `payment-link-failed: ${error.message}`.slice(0, 400) }).catch(() =&gt; {});<br>  throw error;<br>}</pre><p>Unpaid orders hold their seats softly for the length of the payment window, so two parents checking out at once can’t both take the last place.</p><h3>3. One correlation handle, and only one</h3><p>The order id goes to Morning as custom:</p><pre>payment = await morning.createPaymentForm({<br>  amount: priced.total,<br>  income: cartToIncomeLines(camp, priced),<br>  custom: orderId, // comes back as external_data, the only correlation handle<br>  successUrl, failureUrl, notifyUrl,<br>});</pre><p><em>(trimmed)</em></p><p>Morning echoes it back on the callback as external_data. It can only have come from the payment form we created, which makes it the one match that isn&#39;t a guess. Everything else in the chain is built around that difference.</p><h3>4. The webhook, written for an API that doesn’t document it</h3><p>Three things about Morning’s callback aren’t in its documentation, and each shaped the handler.</p><p><strong>It isn’t signed.</strong> Without a check, anyone who guessed an order id could mark a registration paid. So the notifyUrl carries a secret, compared in constant time:</p><pre>function secretOk(provided) {<br>  const expected = config.paymentWebhookSecret ?? &#39;&#39;;<br>  if (!expected || !provided) return false;<br>  const a = Buffer.from(expected, &#39;utf8&#39;);<br>  const b = Buffer.from(String(provided), &#39;utf8&#39;);<br>  return a.length === b.length &amp;&amp; crypto.timingSafeEqual(a, b);<br>}</pre><p><strong>Its field names aren’t documented.</strong> The handler accepts the known variants and logs the keys Morning actually sent, so a silent mismatch shows up as a readable line in the deploy logs:</p><pre>log.info(&#39;morning.webhook_fields&#39;, {<br>  keys: Object.keys(body).sort(),<br>  correlationField: body.external_data !== undefined ? &#39;external_data&#39;<br>    : body.externalData !== undefined ? &#39;externalData&#39;<br>    : body.custom !== undefined ? &#39;custom&#39;<br>    : &#39;NONE: correlation will fail&#39;,<br>});</pre><p><strong>It retries at 10, 20 and 30 minutes on a non-2xx.</strong> So a transient failure (the spreadsheet briefly unreachable, say) returns 500 on purpose, and confirmation is idempotent so the retry can’t double-write attendance:</p><pre>if (order.status === store.STATUS.paid) {<br>  log.info(&#39;payment.already_confirmed&#39;, { orderId });<br>  return { ok: true, duplicate: true };<br>}</pre><h3>5. The webhook that never arrives</h3><p>A webhook that errors is loud: it retries, and it’s in the logs. The dangerous one never arrives. A wrong notifyUrl, a deploy during the thirty seconds Morning was calling, a callback swallowed by a proxy. From the inside that looks exactly like a quiet day. The money is in her account, the child isn&#39;t on the attendance list, and nobody finds out until a parent shows up at camp.</p><p>So every few hours the system asks Morning what it issued and compares that against the sheet. It looks for silence, not errors.</p><p>It <strong>reports and never heals</strong>. Auto-marking an order paid is one idempotent call away, and it’s tempting. But the reconciler can’t always see external_data. A document search row may carry only a description that has been through a third party&#39;s templating, and matching on amount and client name is a guess. A wrong heal puts a child on the attendance list whose parent never paid, and nobody re-checks a row that already says paid. A flagged mismatch costs her a minute.</p><p>What she gets instead is a one-tap confirm, offered only when the correlation came from our own order id. A person decides, and the same confirmPayment() the webhook uses runs.</p><p>Findings are fingerprinted, and an alert goes out only when the fingerprint changes:export function fingerprint(result) {<br> return result.findings<br> .filter((finding) =&gt; finding.severity !== SEVERITY.info)<br> .map((finding) =&gt; `${finding.kind}:${finding.orderId ?? finding.documentId}`)<br> .sort()<br> .join(&#39;|&#39;);<br>}</p><pre>// The whole rule: say it when it changes, and not otherwise.<br>if (current.streams[stream]?.fingerprint === fingerprint) return false;</pre><p>A mismatch still open tomorrow stays quiet. A new one alongside it sends. The state is written to disk atomically, so a redeploy doesn’t re-announce everything.</p><h3>6. Money going back</h3><p>Refunds taught the reconciler something. Crediting an invoice doesn’t remove it: Morning leaves the original alone and raises a credit note beside it. Once refunds shipped, every refunded booking showed up as an unrecorded payment on every pass, so the watchdog got noisier the more the feature was used. That’s the fastest way to teach someone to ignore an alert. The fix settles a payment by Morning’s own status on the original document first, then by netting credit notes against it.</p><p>The refund itself goes through an endpoint Morning doesn’t document. The only way to learn what it does was to use it, so I refunded one shekel on a real invoice and watched:</p><pre>POST /payments/transactions/{id}/refund   { &quot;amount&quot;: 1 }<br>→ 200<br>transaction status 20 → 30, cancellable true → false</pre><p>Two documents appeared that I hadn’t asked for: a credit note and a negative receipt. Morning raises both itself as part of the refund.</p><p>That set the design. Issuing a credit note through the API is possible, and I checked and documented the request for it. But if the app issued one as well, a single cancellation would carry two credits and the VAT she reports would be wrong. So the request stays in the notes, and the refund function never touches the documents endpoint:</p><pre>/**<br> * Morning issues the credit note (type 330) and the negative receipt (type<br> * 400) by itself as part of this call. Do NOT create a 330 alongside it, or<br> * the books carry two credits for one cancellation and the VAT she reports is<br> * wrong. That is the whole reason this function does not touch /documents.<br> */<br>export async function refundTransaction(transactionId, { amount } = {}) {<br>  const value = Number(amount);<br>  if (!Number.isFinite(value) || value &lt;= 0) throw new Error(/* … */);<br>  return api(`/payments/transactions/${encodeURIComponent(transactionId)}/refund`, {<br>    method: &#39;POST&#39;,<br>    body: { amount: Math.round(value * 100) / 100 },<br>  });<br>}</pre><p><em>(trimmed)</em></p><p>Around that call:</p><ul><li><strong>An explicit </strong><strong>confirm: true, checked in the function itself and not just the route.</strong> It&#39;s the one function that moves money out of her account, and a future caller shouldn&#39;t be able to do that by forgetting a flag.</li><li><strong>The transaction is read back afterwards.</strong> A 200 says the request was accepted, not that the charge was reversed.</li><li><strong>A failure isn’t fatal.</strong> The cancellation stands, the audit row stays pending, and she’s pointed at Morning to finish by hand. Losing the refund is recoverable. Losing the record of it isn’t.</li><li><strong>The amount is capped locally.</strong> In testing, Morning accepted a ₪999 credit note against a ₪1 invoice, and silently accepted a misspelled linkType that produced a credit note cancelling nothing. Neither is in its documentation.</li></ul><h3>Evidence that outlives the camp</h3><p>The signed form is what shows a parent declared their child fit. A few smaller decisions protect it.</p><p><strong>Write-once.</strong> One flag on writeFile is the whole mechanism that stops a document being signed twice:</p><pre>await writeFile(file, html, { encoding: &#39;utf8&#39;, flag: &#39;wx&#39; });<br>queueBackup(id);</pre><p><strong>Tied to a wording.</strong> Each form records a hash of the terms, so a signature maps to a specific version even after she edits the terms mid-season.</p><p><strong>Kept seven years, enforced at boot.</strong> The original instruction was to delete forms after a year. In Israel, a civil claim’s limitation period is seven years, and for a minor it doesn’t start until they turn 18, so a child injured at eight could claim until 25. A shorter period makes the server refuse to start unless an acknowledgement reads confirmed-with-a-lawyer: a value you have to read before you can copy it is one you can&#39;t set by accident.</p><p><strong>Two copies, and a restore that has been run.</strong> The server’s disk and European object storage, each object carrying its hash so a restore can prove it got back exactly what was stored.</p><h3>Where the work went</h3><p>Very little of it was the booking flow. It went into what’s invisible when it holds: an undocumented API whose behaviour had to be found by experiment, money that must not move twice, evidence that must not be lost or deleted early, and an operator who should never need to call anyone, including me, to change a price.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dba3b7f5c474" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>