<?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 Explorejeeva on Medium]]></title>
        <description><![CDATA[Stories by Explorejeeva on Medium]]></description>
        <link>https://medium.com/@explorejeeva?source=rss-d7a24d619a84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jj_gXgcF_CS5rOEE</url>
            <title>Stories by Explorejeeva on Medium</title>
            <link>https://medium.com/@explorejeeva?source=rss-d7a24d619a84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:22:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@explorejeeva/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[How We Used Low-Level Design While Building Hyperswitch Prism]]></title>
            <link>https://medium.com/@explorejeeva/how-we-used-low-level-design-while-building-hyperswitch-prism-c88835ebeea2?source=rss-d7a24d619a84------2</link>
            <guid isPermaLink="false">https://medium.com/p/c88835ebeea2</guid>
            <category><![CDATA[hyperswitch]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[juspay]]></category>
            <category><![CDATA[prism]]></category>
            <dc:creator><![CDATA[Explorejeeva]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 05:37:07 GMT</pubDate>
            <atom:updated>2026-09-27T05:37:07.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ls6dmSPpcjYx3L-ddEHeOQ.png" /></figure><p>Adding your first payment connector is fun. Adding your second is where you find out whether you designed anything at all.</p><p>Every processor wants something different: a different URL, a different HTTP method, a different JSON shape, a different idea of what a “card” looks like. If each connector is a pile of one-off code, connector #2 is a copy-paste of connector #1, and connector #50 is a maintenance nightmare.</p><p>Hyperswitch Prism talks to 100+ connectors today. To keep that manageable, we used a handful of well-known design patterns. This post walks through them.</p><h3>Meet Hyperswitch Prism</h3><p>Hyperswitch Prism is a stateless Rust library that takes one unified payment request and turns it into the right API call for 100+ processors. The codebase is large, so the snippets in this post come from a condensed reference version of it (<a href="https://github.com/juspay/hyperswitch-prism/blob/main/docs/blogs/code/prism-lld-reference.rs">prism-lld-reference.rs</a>). It has the same structure, with the details removed.</p><p>Here’s the whole journey of one payment, and the map for the rest of this post:</p><pre>Singleton (Creational Patterns)<br>    |<br>    |<br> Request<br>    |<br>    |<br>Factory Method (Creational Patterns)<br>    |<br>    |<br>Strategy Pattern (Behavioral Patterns)<br>    |<br>    |<br>Adapter Pattern - Request (Structural Patterns)<br>    |<br>    |<br>Template Method (Behavioral Patterns)<br>    |<br>    |<br>Builder Method (Creational Patterns)<br>    |<br>    |<br> HTTP Call<br>    |<br>    |<br>Adapter Pattern - Response (Structural Patterns)</pre><p>Let’s walk it top to bottom.</p><h3>1. Singleton: set the config once, read it anywhere</h3><p>Every part of the service needs config, but it should be loaded exactly once. We don’t want to pass it through twenty function signatures, and we don’t want a mutable global either.</p><pre>static CONFIG: OnceLock&lt;Arc&lt;Config&gt;&gt; = OnceLock::new();</pre><pre>impl Config {<br>    pub fn init(host: String, port: u16) {<br>        let config = Config {<br>            server: Server { host, port },<br>        };</pre><pre>        CONFIG<br>            .set(Arc::new(config))<br>            .expect(&quot;Config already initialized&quot;);<br>    }</pre><pre>    pub fn instance() -&gt; Arc&lt;Config&gt; {<br>        CONFIG<br>            .get()<br>            .expect(&quot;Config has not been initialized&quot;)<br>            .clone()<br>    }<br>}</pre><p>OnceLock gives us &quot;write once, read forever&quot; with thread safety for free, and Arc makes handing it out cheap. If someone calls init twice, or reads the config before it&#39;s set, the program fails loudly instead of quietly running with the wrong settings.</p><h3>2. Request: one shape for every payment</h3><p>The merchant never speaks Adyen or Stripe. They send one unified request:</p><pre>#[derive(Debug, Clone)]<br>pub struct PaymentRequest {<br>    pub amount: i64,<br>    pub currency: String,<br>    pub card_number: String,<br>}</pre><pre>let payload = PaymentRequest {<br>    amount: 1000,<br>    currency: &quot;EUR&quot;.to_string(),<br>    card_number: &quot;4111111111111111&quot;.to_string(),<br>};</pre><p>Everything after this point is about turning that one shape into whatever the chosen connector wants.</p><h3>3. Factory Method: from a name to a connector</h3><p>Which connector to use is decided at runtime: it arrives as data, not as code. The factory turns that value into a real object:</p><pre>impl ConnectorData {<br>    // Factory (Creational)<br>    // Here the factory is deciding which object to create based on the runtime value of connector<br>    fn get_connector_by_name(connector: ConnectorEnum) -&gt; ConnectorData {<br>        match connector {<br>            ConnectorEnum::Adyen =&gt; Self {<br>                connector: Box::new(Adyen::new()),<br>                connector_name: connector,<br>            },<br>        }<br>    }<br>}</pre><p><em>(Purists will point out that this is technically a “simple factory”. The GoF Factory Method relies on subclasses overriding a creation method. The idea is the same: callers ask for a connector, and one place decides how to make it.)</em></p><p>Rust’s match is exhaustive, so a new ConnectorEnum variant without a match arm doesn&#39;t compile.</p><h3>4. Strategy: one contract, many connectors</h3><p>Every connector implements the same trait, so the core doesn’t need to know which one it’s talking to:</p><pre>// Strategy (Behavioral)<br>// Strategy interface<br>/*<br>                 ConnectorIntegrationV2<br>                       Strategy<br>                          |<br>              +-----------+-----------+<br>              |                       |<br>           Adyen                    Stripe<br>      Concrete Strategy        Concrete Strategy<br>*/<br>pub trait ConnectorIntegrationV2&lt;Req&gt;: ConnectorIntegrationAnyV2&lt;Req&gt; {<br>    fn get_http_method(&amp;self) -&gt; Method;</pre><pre>    fn get_url(https://medium.com/&amp;self) -&gt; String;</pre><p>And here’s Adyen, one concrete strategy:</p><pre>// concrete strategy<br>impl ConnectorIntegrationV2&lt;PaymentRequest&gt; for Adyen {<br>    fn get_http_method(&amp;self) -&gt; Method {<br>        Method::POST<br>    }</pre><pre>    fn get_url(https://medium.com/&amp;self) -&gt; String {<br>        &quot;https://api.adyen.io&quot;.to_string()<br>    }<br>}</pre><p>Adyen supplies only two things: the HTTP method and the URL.</p><h3>5. Adapter (request): speaking each connector’s language</h3><p>We know <em>who</em> we’re talking to. Now we need to speak their language. Our unified PaymentRequest has to become the exact shape Adyen expects:</p><pre>// Adapter (Structural) - Request<br>// Convert the unified request into the shape Adyen&#39;s API expects<br>impl TryFrom&lt;&amp;PaymentRequest&gt; for AdyenPaymentRequest {<br>    type Error = String;<br>    fn try_from(req: &amp;PaymentRequest) -&gt; Result&lt;Self, Self::Error&gt; {<br>        if req.amount &lt;= 0 {<br>            return Err(&quot;Amount must be positive&quot;.into());<br>        }<br>        Ok(Self {<br>            amount: AdyenAmount {<br>                value: req.amount,<br>                currency: req.currency.clone(),<br>            },<br>            merchant_account: &quot;MyMerchantAccount&quot;.into(),<br>            payment_method: AdyenPaymentMethod {<br>                method_type: &quot;scheme&quot;.into(),<br>                number: req.card_number.clone(),<br>            },<br>        })<br>    }<br>}</pre><p>Adyen’s quirks, like &quot;scheme&quot; for cards and a merchant_account field, live here and nowhere else. Validation lives here too, so bad input is rejected before we ever build an HTTP request. In the real codebase, these are the transformers.rs files that sit next to every connector.</p><h3>6. Template Method: we own the steps, connectors fill the blanks</h3><p>Who actually puts the request together? The trait does, through a default method:</p><pre>// Template Method (Behavioral)<br>// Fixed skeleton; each connector fills in get_http_method and get_url<br>fn build_requestv2(&amp;self) -&gt; Option&lt;Request&gt; {<br>    Some(<br>        // Builder (Creational)<br>        // Build a complex object step-by-step<br>        RequestBuilder::new()<br>            .method(self.get_http_method())<br>            .url(https://medium.com/self.get_url())<br>            .build(),<br>    )<br>}</pre><p>The order of steps is written once and shared by every connector. Connectors only supply their own values. Changing how every request is built means changing one method, not 100 connectors.</p><h3>7. Builder: assembling the request step by step</h3><p>Rather than one constructor with a long list of arguments, the request is built one step at a time:</p><pre>impl RequestBuilder {<br>    fn new() -&gt; RequestBuilder {<br>        Self {<br>            method: Method::POST,<br>            url: String::new(),<br>        }<br>    }</pre><pre>    pub fn method(mut self, method: Method) -&gt; Self {<br>        self.method = method;<br>        self<br>    }</pre><pre>    pub fn url(https://medium.com/mut%20self,%20url:%20String) -&gt; Self {<br>        self.url = url;<br>        self<br>    }</pre><pre>    fn build(self) -&gt; Request {<br>        Request {<br>            method: self.method,<br>            url: self.url,<br>        }<br>    }<br>}</pre><p>Each step is named, and unset values fall back to defaults (POST). In Prism, the same builder also sets headers, bodies and certificates.</p><h3>8. Adapter (response): bringing the answer home</h3><p>The request goes out, and Adyen replies in its own format. Before that reaches the merchant, we translate it back. It’s the same Adapter, just running the other way.</p><p>Every connector’s reply lands in one unified shape:</p><pre>#[derive(Debug)]<br>pub enum PaymentStatus {<br>    Authorized,<br>    Failed,<br>}</pre><pre>#[derive(Debug)]<br>pub struct PaymentResponse {<br>    pub status: PaymentStatus,<br>    pub connector_transaction_id: String,<br>}</pre><p>And Adyen’s version of “it worked” gets mapped into it:</p><pre>// Adyen-specific response (the shape Adyen&#39;s API returns)<br>#[derive(Debug)]<br>pub struct AdyenPaymentResponse {<br>    pub psp_reference: String,<br>    pub result_code: String,<br>}</pre><pre>// Adapter (Structural) - Response<br>// Convert Adyen&#39;s response back into the unified shape<br>impl TryFrom&lt;AdyenPaymentResponse&gt; for PaymentResponse {<br>    type Error = String;<br>    fn try_from(res: AdyenPaymentResponse) -&gt; Result&lt;Self, Self::Error&gt; {<br>        let status = match res.result_code.as_str() {<br>            &quot;Authorised&quot; =&gt; PaymentStatus::Authorized,<br>            &quot;Refused&quot; =&gt; PaymentStatus::Failed,<br>            other =&gt; return Err(format!(&quot;Unknown resultCode: {other}&quot;)),<br>        };<br>        Ok(Self {<br>            status,<br>            connector_transaction_id: res.psp_reference,<br>        })<br>    }<br>}</pre><p>Adyen says &quot;Authorised&quot;, another processor says &quot;succeeded&quot;, a third says &quot;APPROVED&quot;, and the merchant sees Authorized in each case. Every connector has two adapters, one for the request and one for the response.</p><h3>The small bit of Rust glue</h3><p>A blanket impl gives every connector a way to return itself as a strategy object, with no extra code per connector:</p><pre>impl&lt;S, Req&gt; ConnectorIntegrationAnyV2&lt;Req&gt; for S<br>where<br>    S: ConnectorIntegrationV2&lt;Req&gt;,<br>{<br>    fn get_connector_integrationv2(&amp;self) -&gt; BoxedConnectorIntegration&lt;&#39;_, Req&gt; {<br>        Box::new(self)<br>    }<br>}</pre><p>And supertraits let us describe a connector’s capabilities as a stack:</p><pre>pub trait ConnectorServiceTrait: PaymentAuthorizeV2 {}</pre><pre>pub trait PaymentAuthorizeV2: ConnectorIntegrationV2&lt;PaymentRequest&gt; {}</pre><p>Want capture, refund or void? Add another trait to the stack. The compiler then checks that every connector implements all of them.</p><h3>Putting it together</h3><p>Here’s the whole diagram as code:</p><pre>pub fn process_internal_authorization(<br>    connector: ConnectorEnum,<br>    payload: PaymentRequest,<br>    config: Arc&lt;Config&gt;,<br>) -&gt; Result&lt;PaymentResponse, String&gt; {<br>    println!(<br>        &quot;Server running on {}:{}&quot;,<br>        config.server.host, config.server.port<br>    );</pre><pre>    // Selecting the strategy</pre><pre>    let connector_data = ConnectorData::get_connector_by_name(connector);</pre><pre>    // Strategy (Behavioral)</pre><pre>    let connector_integration_v2: BoxedConnectorIntegration&lt;&#39;_, PaymentRequest&gt; =<br>        connector_data.connector.get_connector_integrationv2();</pre><pre>    // Adapter (Structural) - Request<br>    let connector_request =      AdyenPaymentRequest::try_from(&amp;payload)?;<br>    println!(&quot;{:?}&quot;, connector_request);</pre><pre>    // Template Method (Behavioral) + Builder (Creational)<br>    let request = connector_integration_v2.build_requestv2();<br>    println!(&quot;{:?}&quot;, request);</pre><pre>    // HTTP Call (mocked): pretend Adyen replied<br>    let connector_response = AdyenPaymentResponse {<br>        psp_reference: &quot;8515131751004933&quot;.to_string(),<br>        result_code: &quot;Authorised&quot;.to_string(),<br>    };</pre><pre>    // Adapter (Structural) - Response<br>    PaymentResponse::try_from(connector_response)<br>}</pre><pre>fn main() {<br>    // Singleton (Creational)<br>    Config::init(&quot;http://localhost&quot;.to_string(), 8080);<br>    let config = Config::instance();</pre><pre>    let payload = PaymentRequest {<br>        amount: 1000,<br>        currency: &quot;EUR&quot;.to_string(),<br>        card_number: &quot;4111111111111111&quot;.to_string(),<br>    };</pre><pre>    let response = process_internal_authorization(ConnectorEnum::Adyen, payload, config);<br>    println!(&quot;{:?}&quot;, response);<br>}</pre><p>Run it, and each output line comes from a different step:</p><pre>Server running on http://localhost:8080<br>AdyenPaymentRequest { amount: AdyenAmount { value: 1000, currency: &quot;EUR&quot; }, merchant_account: &quot;MyMerchantAccount&quot;, payment_method: AdyenPaymentMethod { method_type: &quot;scheme&quot;, number: &quot;4111111111111111&quot; } }<br>Some(Request { method: POST, url: &quot;https://api.adyen.io&quot; })<br>Ok(PaymentResponse { status: Authorized, connector_transaction_id: &quot;8515131751004933&quot; })</pre><p>Singleton, then the request Adapter, then Template Method + Builder, then the response Adapter.</p><p><em>(Two simplifications: to keep the snippet short, this calls Adyen’s adapters directly, and the HTTP call is mocked. In Prism, each connector owns its own transformations, so the core never names a specific connector, and the request really goes over the wire.)</em></p><h3>The real test: connector #2</h3><p>Here’s Stripe’s strategy:</p><pre>pub struct Stripe;</pre><pre>// concrete strategy<br>impl ConnectorIntegrationV2&lt;PaymentRequest&gt; for Stripe {<br>    fn get_http_method(&amp;self) -&gt; Method {<br>        Method::POST<br>    }</pre><pre>    fn get_url(https://medium.com/&amp;self) -&gt; String {<br>        &quot;https://api.stripe.com&quot;.to_string()<br>    }<br>}</pre><p>That’s the whole strategy: two answers, same as Adyen. To finish the job, we’d add Stripe’s two adapters (request and response), plus one variant and one match arm in the factory.</p><p>What we wouldn’t touch: the Singleton, the unified Request, the Template Method, the Builder, or the orchestration function. On the diagram, only the Strategy and the two Adapter boxes get a new entry. Everything else stays exactly the same.</p><p>A new connector only adds code for what is specific to that processor.</p><p>Prism is open source, built in Rust, with SDKs across languages.</p><ul><li>GitHub: <a href="https://github.com/juspay/hyperswitch-prism">github.com/juspay/hyperswitch-prism</a></li><li>Node.js: npm install hyperswitch-prism</li><li>Python: pip install hyperswitch-prism</li><li>Java: io.hyperswitch:prism on Maven Central</li><li>Docs: <a href="https://docs.hyperswitch.io/integrations/prism/prism/installation">docs.hyperswitch.io/integrations/prism/prism/installation</a></li></ul><p><em>If this was useful, a ⭐ on GitHub goes a long way. And if you’ve used a different pattern to tame connector sprawl, we’d love to hear about it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c88835ebeea2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Authorization to Settlement: A Payment Is a Lifecycle]]></title>
            <link>https://medium.com/@explorejeeva/from-authorization-to-settlement-a-payment-is-a-lifecycle-b30021b5c92d?source=rss-d7a24d619a84------2</link>
            <guid isPermaLink="false">https://medium.com/p/b30021b5c92d</guid>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[hyperswitch-prism]]></category>
            <category><![CDATA[prism]]></category>
            <dc:creator><![CDATA[Explorejeeva]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 18:43:36 GMT</pubDate>
            <atom:updated>2026-06-29T18:43:36.863Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>A payment isn’t a thing you fetch. It’s a thing that happens.</em></strong></blockquote><p>A card gets authorized in one request. The money gets captured in another, maybe the next morning when the warehouse confirms stock. A refund shows up a week later. A 3DS challenge parks the whole thing in a “waiting on the customer” limbo that resolves in a browser tab your server never sees. Confirmations trickle in by webhook, out of order, sometimes twice.</p><p>Most SDKs flatten all of that into a Payment object with a single status field. That shape is convenient, and it&#39;s exactly where things start to go wrong:</p><pre>const payment = await sdk.payments.get(id)</pre><pre>if (payment.status === &quot;succeeded&quot;) {<br>  await fulfillOrder(payment.order_id)   // looks fine, ships a bug<br>}</pre><p>Here’s the catch: &quot;succeeded&quot; isn&#39;t one thing. A succeeded authorization and a succeeded capture are different events, and a success you polled for is different again from one that turned up in a settlement webhook.</p><p>Authorizing reserves the money.</p><p>Capturing actually moves it.</p><p>So if you fulfill on the authorization, you’ve shipped goods against a hold that can still be declined later, or just quietly expire.</p><p>And the code passes review.</p><p>The test card authorizes and captures in one go, so the demo is green and everyone moves on.</p><p>Then a real customer pays with a 3DS card, the else branch fires on a payment that actually went through, and you&#39;re debugging it in production.</p><p>Good SDKs hand you the whole lifecycle. The ones that don’t give you a noun with a status field, and let you write code that reads correctly and behaves wrong.</p><h3>How Hyperswitch Prism Models It</h3><p><a href="https://github.com/juspay/hyperswitch-prism">Prism</a> doesn’t hand you one mutable Payment to poke at. A payment has a position in a state machine, with named flows instead of a single status. Its PaymentStatus enum carries thirty-odd states, and they&#39;re grouped on purpose:</p><pre>STARTED → AUTHENTICATION_PENDING → AUTHORIZED → CHARGED → (refund sub-process)<br>                  │                     │           │<br>            (3DS / SCA)          (money reserved)  (money moved)</pre><p>The API mirrors that machine.</p><p>There’s no status setter sitting on an object.</p><p>The lifecycle shows up as verbs spread across a few clients, and every call tells you where the payment ended up:</p><pre>import {<br>  PaymentClient,                 // get / capture / refund / void<br>  MerchantAuthenticationClient,  // open the session, mint client token<br>  EventClient,                   // parse + verify asynchronous webhooks<br>  types,<br>} from &quot;hyperswitch-prism&quot;</pre><pre>await paymentClient.capture({ connectorTransactionId, /* ... */ })</pre><p>Notice capture is its own method, not update({ status: &quot;captured&quot; }).</p><p>You can’t fat-finger a capture onto a payment that was never authorized and have it pass as a harmless-looking status string.</p><p>The methods you can call are the transitions you’re actually allowed to make.</p><h3>One Word, Three Enums</h3><p>A flat status field is a trap because &quot;succeeded&quot; turns up in three different places that mean three different things. <a href="https://github.com/juspay/hyperswitch-prism">Prism</a> gives each one its own type:</p><ul><li>PaymentStatus.AUTHORIZED vs PaymentStatus.CHARGED — reserved vs moved.</li><li>Webhook events are a separate enum:<br>PAYMENT_INTENT_AUTHORIZATION_SUCCESS vs PAYMENT_INTENT_CAPTURE_SUCCESS.</li><li>Both say “success.” Only one means you got paid.</li><li>Refunds get their own enum again:<br>RefundStatus.REFUND_SUCCESS, with its own pending and failure states, because a refund is its own sub-process.</li></ul><p>Cram all three into one status field and you&#39;re overloading it, and the overloading is where the bug lives.</p><p>Keep the flows apart and you read the one you actually meant.</p><h3>Two Non-PCI Flows, Two Shapes</h3><p>“Non-PCI” means the sensitive part (the card number, the PayPal login) gets entered in the connector’s own client-side SDK and never reaches your server.</p><p>Your backend only ever holds tokens and ids.</p><p><a href="https://github.com/juspay/hyperswitch-prism">Prism</a> supports this, but the lifecycle looks different from one connector to the next, which is another reason a flat status falls short.</p><p>Take Adyen and PayPal:</p><pre>NON-PCI: the card / login is entered in the connector&#39;s client SDK.<br>Your server only holds tokens and ids — never raw card data.</pre><p>With <strong>Adyen</strong>, the card is authorized inside the Drop-in, and the result only reaches your server by webhook.</p><p>So authorizePayment can&#39;t just read a status.</p><p>It waits for the verified event, then picks up the pspReference from that webhook as the transaction id, which it needs for the capture you run separately:</p><pre>// initiate: hand the browser a client token; the card stays client-side<br>const session = await authClient.createClientAuthenticationToken({ /* amount */ })<br>// → { clientToken, publishableKey }  — server never sees the card</pre><pre>// authorize: the outcome only exists once the verified webhook lands<br>const outcome = getWebhookOutcome(sessionId)   // recorded by EventClient<br>// → AUTHORIZED + pspReference   (capture is a later, separate call)</pre><p><strong>PayPal</strong> works the other way around.</p><p>The order is created up front, the buyer approves it in the popup, and your server captures the approved order in one shot with AUTOMATIC capture:</p><pre>// initiate: create the order server-side, hand the browser its id<br>const orderId = await createPaypalOrder({ /* amount, currency */ })<br>// → buyer approves orderId in the PayPal popup; no card on your server</pre><pre>// authorize: capture the approved order using the JS-SDK token<br>const res = await paymentClient.authorize({<br>  paymentMethod: { paypalSdk: { token: { value: orderId } } },<br>  captureMethod: types.CaptureMethod.AUTOMATIC,<br>})<br>// → CHARGED   (already captured; only refunds remain)</pre><p>Same vocabulary, two real paths.</p><p>Adyen ends on AUTHORIZED with a capture still owed.</p><p>PayPal ends on CHARGED right away.</p><p>A plain status field would call both of those &quot;succeeded&quot; and hide the fact that one of them still needs a capture.</p><p>The named states won’t let that slip.</p><h3>Truth That Isn’t Synchronous</h3><p>Sometimes the answer isn’t there yet when you ask for it.</p><p>In client-side flows the authorization decision lands later, over a webhook, so a synchronous read is really just a guess.</p><p><a href="https://github.com/juspay/hyperswitch-prism">Prism</a> treats it as a guess rather than pretending otherwise:</p><ul><li>A status read with nothing behind it yet comes back PENDING, not ERROR.</li><li>Unknown means “check again in a bit,” not “decline someone who already paid.”</li><li>An async event has to prove itself before it can move state.</li><li>EventClient parses the webhook, checks the source, and only then maps it.</li><li>A webhook it can’t verify is just a forged transition, so it gets rejected, and there’s no dev-mode shortcut around that.</li><li>Even the amount isn’t a plain number.</li><li>It’s a currency-scaled minor unit, so 1000 is ¥1000 in one currency and $10.00 in another.</li></ul><h3>The Takeaway</h3><p>Treat a payment as a lifecycle and a few habits follow:</p><ul><li><strong>Don’t branch on one </strong><strong>status.</strong> Ask the specific question: authorized, captured, or refunded? They&#39;re different flows.</li><li><strong>Treat a sync read as provisional.</strong> Default unknowns to pending and let the verified event settle it.</li><li><strong>Never fulfill on authorization.</strong> Only a capture means you’ve been paid.</li><li><strong>Money is a currency-scaled integer</strong>, not a number.</li></ul><p>A payment runs from authorization to settlement, and treating it as a lifecycle rather than a single status is the gap between code that works and code that only looks like it does.</p><p><a href="https://github.com/juspay/hyperswitch-prism">Prism</a> puts the lifecycle in front of you, with separate verbs, separate flows, and events it actually verifies, so the obvious thing to write tends to be the right thing too.</p><h3>Reference</h3><ul><li><strong>Hyperswitch Prism on GitHub</strong><br><a href="https://github.com/juspay/hyperswitch-prism">https://github.com/juspay/hyperswitch-prism</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b30021b5c92d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Built Multi-Language SDKs for Prism, a Payment Library, Using FFI]]></title>
            <link>https://medium.com/@explorejeeva/how-we-built-multi-language-sdks-for-prism-a-payment-library-using-ffi-a5dd06f2c9c6?source=rss-d7a24d619a84------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5dd06f2c9c6</guid>
            <category><![CDATA[payment-library]]></category>
            <category><![CDATA[hyperswitch]]></category>
            <category><![CDATA[prism]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Explorejeeva]]></dc:creator>
            <pubDate>Sun, 03 May 2026 14:01:14 GMT</pubDate>
            <atom:updated>2026-05-03T14:05:00.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="workflow" src="https://cdn-images-1.medium.com/max/1024/1*FTYPgJG-FTXx5KwMPs2prA.png" /></figure><p>Prism is a payment library designed to handle the full payment lifecycle — <strong>authorize</strong>, <strong>capture</strong>, <strong>refund</strong>, and <strong>void</strong> — across multiple connectors like <strong>Stripe</strong>, <strong>Adyen</strong>, and others.</p><p>While the core is written in Rust, we needed SDKs that work seamlessly in Node.js, Python, and Java. The challenge was straightforward: how do we share business logic across languages without rewriting it multiple times?</p><h3>The Design Choice: gRPC vs FFI</h3><p>We initially evaluated two approaches:</p><ul><li>HTTP/gRPC-based communication</li><li>Foreign Function Interface (FFI)</li></ul><p>gRPC worked, but it came with trade-offs:</p><ul><li>Running a sidecar service</li><li>Additional network hops</li><li>Extra operational overhead</li></ul><p>For something running on the same machine, this felt unnecessary.</p><p>FFI, on the other hand, allowed:</p><ul><li>In-process execution</li><li>Zero network overhead</li><li>No additional runtime to manage</li></ul><p>That made it the clear choice.</p><h3>A Simple Pattern Behind Every Handler</h3><p>Before exposing anything over FFI, we broke down how Prism handlers actually work.</p><p>Every operation — whether authorize, capture, refund, or void — follows the same structure:</p><pre>fn authorize(req) {<br>    // 1. Transform input → connector-specific request<br>    // 2. Make HTTP call → send to connector<br>    // 3. Transform response → normalize output<br>}</pre><p>In essence:<br><strong>transform → call → transform</strong></p><p>This realization was key.</p><p>Instead of exposing entire handlers over FFI, we only needed to expose the transformation logic:</p><ul><li>Request transformation</li><li>Response transformation</li></ul><p>The HTTP call stays within the SDK, written in the target language.</p><p>This keeps:</p><ul><li>The FFI surface minimal</li><li>Responsibilities cleanly separated</li><li>Future extensions predictable</li></ul><h3>Using UniFFI</h3><p>To expose Rust functions across languages, we used UniFFI.</p><p>With simple annotations, UniFFI generates bindings and compiles platform-specific binaries (.so, .dylib, .dll) that can be loaded from other languages.</p><p>Example:</p><pre>#[derive(uniffi)]<br>fn authorize_req_transformer(...) { ... }</pre><pre>#[derive(uniffi)]<br>fn authorize_res_transformer(...) { ... }</pre><p>These same functions are reused across:</p><ul><li>HTTP handlers</li><li>gRPC handlers</li><li>FFI-based SDKs</li></ul><p>One implementation, multiple entry points.</p><h3>How the SDK Uses FFI</h3><p>Each SDK client corresponds to a service — for example, PaymentClient for payment operations.</p><p>The compiled Rust binary is loaded once, and FFI calls are made as part of each request:</p><pre>export class PaymentClient {<br>    async authorize(msg) {<br>        const req = ffi.authorize_req_transformer(msg);<br>        const result = await fetch(req);<br>        const res = ffi.authorize_res_transformer(result);<br>        return res;<br>    }<br>}</pre><p>Loading the binary is straightforward:</p><pre>const ffi = require(&#39;./libprism_ffi.so&#39;); // .dylib on macOS, .dll on Windows</pre><p>From the SDK’s perspective, these functions behave like local calls.</p><h3>Crossing the Language Boundary</h3><p>One challenge with FFI is data transfer — JSON doesn’t map cleanly across language boundaries.</p><p>We solved this using Protobuf as the interchange format.</p><p>Flow:</p><pre>User          SDK              FFI            Rust<br> │             │                │              │<br> │  JSON       │                │              │<br> │────────────▶│                │              │<br> │             │  Protobuf      │              │<br> │             │  Bytes         │              │<br> │             │───────────────▶│              │<br> │             │                │    Bytes     │<br> │             │                │─────────────▶│<br> │             │                │    Process   │<br> │             │                │◀─────────────│<br> │             │◀───────────────│              │<br> │◀────────────│                │              │</pre><p>Why Protobuf?</p><ul><li>Efficient binary format</li><li>Strong typing across languages</li><li>Shared schema via .proto files</li></ul><p>This ensures type safety in Node, Python, and Java — all from a single source of truth.</p><h3>What the Developer Sees</h3><p>All of this complexity is hidden from the end user.</p><p>After installing the SDK:</p><pre>import { PaymentClient, types } from &#39;hyperswitch-prism&#39;;</pre><pre>const paymentClient = new PaymentClient(connectorConfig);<br>const response = await paymentClient.authorize(authorizeRequest);</pre><pre>if (response.status === types.PaymentStatus.CHARGED) {<br>    console.log(&quot;Payment successful&quot;);<br>}</pre><p>That’s it.</p><p>No awareness of:</p><ul><li>Rust internals</li><li>FFI boundaries</li><li>Binary loading</li><li>Serialization formats</li></ul><p>Just a clean, simple API.</p><h3>Final Thoughts</h3><p>By narrowing the FFI surface to just transformation logic, we achieved:</p><ul><li>Maximum code reuse</li><li>Minimal overhead</li><li>Clean separation of concerns</li></ul><p>Rust handles business logic.<br>SDKs handle I/O.<br>Protobuf ensures consistency.</p><p>The result is a scalable, multi-language SDK architecture without duplication or unnecessary complexity.</p><p>The full implementation is available here:</p><p><a href="https://github.com/juspay/hyperswitch-prism">https://github.com/juspay/hyperswitch-prism</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5dd06f2c9c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>