<?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 Vladimír Jarabica on Medium]]></title>
        <description><![CDATA[Stories by Vladimír Jarabica on Medium]]></description>
        <link>https://medium.com/@vladojarabica?source=rss-f04ed3700407------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2F6Zrt9ov2yGMlmLICc2ZA@2x.jpeg</url>
            <title>Stories by Vladimír Jarabica on Medium</title>
            <link>https://medium.com/@vladojarabica?source=rss-f04ed3700407------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:14:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vladojarabica/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[Implementing stripe subscription using a state machine]]></title>
            <link>https://medium.com/@vladojarabica/implementing-stripe-subscription-using-a-state-machine-9034cf32ba4f?source=rss-f04ed3700407------2</link>
            <guid isPermaLink="false">https://medium.com/p/9034cf32ba4f</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[xstate]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[state-machine]]></category>
            <dc:creator><![CDATA[Vladimír Jarabica]]></dc:creator>
            <pubDate>Sat, 02 May 2020 16:31:43 GMT</pubDate>
            <atom:updated>2020-05-02T16:31:43.022Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you heard of state machines?<br>I guess if you are a frontend developer, you probably have not.<br>That sounds like one of those fancy academically smelling concepts you never use in your real coding career.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7TKtEyH1uhgrkYw0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7TKtEyH1uhgrkYw0%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o7TKtEyH1uhgrkYw0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38bda6f9a882d3cf9321654b77c94a5/href">https://medium.com/media/b38bda6f9a882d3cf9321654b77c94a5/href</a></iframe><p>I used to have the same opinion. And that is why I was thrilled when I was introduced to the library xstate and found it to be extremely fitting into some of my problems.<br>Today I’d like to model a stripe subscription checkout form. At least its frontend part.</p><p>Most tutorials tell you that state machines in FE are good for user interactions or app state predictability. But I like to use it also for flows, which does not require (almost) any user touch.</p><p><em>I figured out this approach while coding the payment flow for </em><a href="https://dividend.watch/"><em>dividend.watch</em></a><em>💰.<br>So if you go there and decide to try premium, trust me, that you are in good hands of a loving state machine 🤖.</em></p><h4>Which scenarios are valid for state machines</h4><p>If your app (or part of it) should consist of:<br>- a finite amount of <strong>states </strong>✅<br>- with clearly defined <strong>transitions</strong> (changes between them) ✅<br>- predictable <strong>context</strong> (stuff stored in the memory of your machine) ✅<br>- and <strong>actions</strong> (changes between the stuff in memory) ✅<br>you can freely call it a good candidate 🎉.</p><h4>What are we building</h4><p>We will implement a <a href="https://stripe.com/">stripe</a> subscription model that allows you to charge your customer on a regular base. Once per month, year, or similar.</p><p>Other used technologies worth noticing are of course state machines by xstate and React . I assume you have basic knowledge of these technologies. If no, please go through some docs — for xstate they can be found <a href="https://xstate.js.org/docs/">here</a>.</p><p><em>tl;dr: </em>full implementation can be found in this repository on github.</p><p><a href="https://github.com/VladimirJarabica/stripe-xstate">VladimirJarabica/stripe-xstate</a></p><p>Let’s take a look at our problem and identify steps/states required for implementing stripe subscription. At the end of each paragraph, there is also <strong>name</strong> that we&#39;ll use in actual implementation:</p><ul><li>0. user enters card details and hit pay (yes this is user interaction) - idle</li><li>1. create customer object by calling our API -obtainCustomerId</li><li>2. create a payment method using stripe and attaching it to the particular customer using our API - createPaymentMethod</li><li>3. create a subscription using our API - createSubscription</li><li>4. check status of created subscription - checkSubscriptionStatus</li><li>5. if needed confirm card payment (3D secure) with stripe - confirmCardPayment</li><li>6. final success state - paymentSuccess</li><li>7. possible error state - error</li></ul><p>In this article, I assume, that there is already implemented BE API. It should be calling stripe methods like creating customers, attaching payment methods, and creating subscriptions on the server side.<br>I know you probably don&#39;t have. 😱 Do not panic. I have created a fake API service which returns mocked data. Full implementation is on <a href="https://github.com/VladimirJarabica/stripe-xstate/blob/master/src/paymentMachine/services/api.ts">Github</a>.</p><pre>const MOCK_RESPONSES = {<br>  &quot;/customer-id&quot;: &quot;123Customer&quot;,<br>  &quot;/attach-payment-method&quot;: null,<br>  &quot;/subscription&quot;: {<br>    latest_invoice: {<br>      payment_intent: {<br>        client_secret: &quot;321secret&quot;,<br>        status: &quot;requires_capture&quot;,<br>      },<br>    },<br>    // Change this if you want to test different scenarios<br>    status: &quot;trialing&quot;,<br>  },<br>};</pre><h3>Implementation</h3><p>Time to end the preface and let&#39;s get to real work!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FpVl9AZ4Xywb2o%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FpVl9AZ4Xywb2o%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FpVl9AZ4Xywb2o%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="273" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0326ae722bac1896fc2c26c8a5d2ea7/href">https://medium.com/media/e0326ae722bac1896fc2c26c8a5d2ea7/href</a></iframe><h4>Entering card details</h4><p>We need our form elements in React (file <a href="https://github.com/VladimirJarabica/stripe-xstate/blob/master/src/App.tsx">App.tsx</a>).<br>The actual state machine is resting in idle state, waiting for start. So no big deal there. 🤷‍♂</p><pre>function App() {<br>  const stripe = useStripe();<br>  const elements = useElements();</pre><pre>  const [state, send] = useMachine(paymentMachine);</pre><pre>  const handleSubmit = () =&gt; {<br>    // Stripe.js has not yet loaded.<br>    if (!stripe || !elements) return;<br>    send({ type: &quot;START&quot;, stripe, elements });<br>  };</pre><pre>  const handleReset = () =&gt; {<br>    send({ type: &quot;RESET&quot; });<br>  };</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Current state: &quot;{state.value}&quot;&lt;/h3&gt;<br>      &lt;CardElement options={CARD_ELEMENT_OPTIONS} /&gt;<br>      &lt;button onClick={handleSubmit}&gt;Pay&lt;/button&gt;<br>      {state.matches(&quot;error&quot;) &amp;&amp;<br>        &lt;button onClick={handleReset}&gt;Reset&lt;/button&gt;}<br>      {state.context.error &amp;&amp; &lt;small&gt;{state.context.error}&lt;/small&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We got 3 hooks being called in render function:<br>useStripe and useElements provided by @stripe/react-stripe-js library to interact with stripe and rendered iframe for card details.<br>useMachine by @xstate/react managing our machine (smartly called payment machine)</p><p>Then 2 handle functions passed to the buttons. One for starting the payment flow. And other for resetting in the case of an error state.</p><p>The actual JSX is I believe self-explanatory. Worth mentioning is CardElemet component comming from stripe.</p><h4>State machine</h4><p>The bare minimum of our state machine configuration will look like this.</p><pre>import { Machine} from &quot;xstate&quot;;</pre><pre>// State machine named `paymentMachine` with initial state `idle`</pre><pre>const INITIAL_CONTEXT = {<br>  stripe: null,<br>  elements: null,<br>  paymentMethodId: null,<br>  customerId: null,<br>  subscription: null,<br>  error: null<br>}</pre><pre>const paymentMachine = Machine(<br>  {<br>    id: &quot;paymentMachine&quot;,<br>    initial: &quot;idle&quot;,<br>    context: INITIAL_CONTEXT,<br>    states: {<br>      idle: {}<br>    }<br>  },<br>  {<br>    actions: {},<br>    guards: {}<br>  }<br>)</pre><p><em>xstate has a wonderful visualizer 👏 using which we can watch our state machine growing. This is how our current configuration looks like now:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*P9FESEbF-8IUq9Lxm6M7fQ.png" /></figure><p>Once the user will hit pay button, the START event is passed to the machine. Since we are in idle state, we need to define, which transition and action/s should happen after that.</p><pre>import { Machine, <strong>assign</strong> } from &quot;xstate</pre><pre>...</pre><pre>idle: {<br>  <strong>on: {<br>    START: { target: &quot;obtainCustomerId&quot;, actions: &quot;initialize&quot; }<br>  }</strong><br>}</pre><pre>...</pre><pre>actions: {<br>  <strong>initialize: assign({<br>    stripe: (_, event) =&gt; event.stripe,<br>    elements: (_, event) =&gt; event.elements<br>  })</strong><br>}</pre><p>Translated to human language, this is what happens:<br>If the machine is in idle state, by receiving event START it will transition to state obtainCustomerId and trigger action initialize which sets variables stripe and elements into a particular place in context.</p><p>So after this transition, our machine will be in obtainCustomerId state with stripe and elements variables available in context.</p><h4>Obtaining customer id</h4><p>Now we take a look at the second state:</p><pre><strong>import { obtainCustomerIdService } from &quot;./services&quot;</strong><br>...<br>states: {<br>...<br>  <strong>obtainCustomerId: {<br>    invoke: {<br>      src: obtainCustomerIdService,<br>      onDone: {<br>        target: &quot;createPaymentMethod&quot;,<br>        actions: assign({ customerId: (_, event) =&gt; event.data })<br>      },<br>      onError: { target: &quot;error&quot; }<br>    }<br>  }</strong><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWtnrqJP4xcEB60JSLhvPQ.png" /></figure><p>This is it! Our first state which does not require any user interaction!<br>What it does instead, is immediately <strong>invoking</strong> a obtainCustomerIdService.<br>It is supposed to be some promise resolving with a string value (customerId) or rejecting in case of error.</p><p>Once this promise resolved, the state machine will proceed to onDone transition, ending in createPaymentMethod state and calling in place defined action for setting the value into context.<br>onError is targeting theerror state which we&#39;ll be implementing at the end.</p><p><em>Note: </em><a href="https://xstate.js.org/docs/guides/communication.html#invoking-services"><em>services</em></a><em> can also be callbacks, observables, or even other state machines.</em></p><p>This is the actual implementation of such service using our mocked API:</p><pre>import { callApi } from &quot;./api&quot;;</pre><pre>// TODO: handle your errors in actual implementation<br>export const obtainCustomerIdService = () =&gt;<br>  new Promise(async (resolve) =&gt; {<br>    const customerId = await callApi(&quot;/customer-id&quot;);<br>    resolve(customerId);<br>  });</pre><p>Once this service resolves, as stated in onDone.target we move to another state — createPaymentMethod.</p><h4>Creating payment method</h4><p>Next state to handle is createPaymentMethod. Let&#39;s start with machine part:</p><pre>import {<br>  obtainCustomerIdService,<br>  <strong>createPaymentMethodService</strong><br>} from &quot;./services&quot;</pre><pre>...</pre><pre>states: {</pre><pre>...<br>  <br>  <strong>createPaymentMethod: {<br>    invoke: {<br>      src: </strong><strong>createPaymentMethodService,<br>      onDone: {<br>        target: &quot;createSubscription&quot;,<br>        actions: assign({<br>          paymentMethodId: (_, event) =&gt; event.data<br>        })<br>      },<br>      onError: { target: &quot;error&quot; }<br>    }<br>  }</strong><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ttCNJ5s4Qvma5hUUDGMFA.png" /></figure><p>This looks pretty similar to our previous state. Just invoking different service and setting a different piece of context.</p><p>But the actual service is a bit more complex. Mainly because actual stripe flow is there longer:</p><pre>import { CardElement } from &quot;@stripe/react-stripe-js&quot;;</pre><pre>import { callApi } from &quot;./api&quot;;</pre><pre>export const createPaymentMethodService = ({<br>  stripe,<br>  elements,<br>  customerId,<br>}) =&gt;<br>  new Promise(async (resolve, reject) =&gt; {<br>    const card = elements.getElement(CardElement)</pre><pre>    // Stripe checks if card is filled correctly<br>    if (!card) {<br>      reject()<br>      return<br>    }</pre><pre>    const paymentMethodResult = await stripe.createPaymentMethod({ <br>      type: &quot;card&quot;,<br>      card<br>    })<br>    const paymentMethodId = paymentMethodResult.paymentMethod?.id;</pre><pre>    // Check if payment method was created properly    <br>    if (!paymentMethodId) {<br>      reject()<br>      return<br>    }</pre><pre>    // BE will sync previously created customer with payment method    <br>    await callApi(&quot;/attach-payment-method&quot;, {<br>      id: paymentMethodId<br>      customerId<br>    });</pre><pre>    resolve(paymentMethodId)<br>});</pre><p>Firstly we need to get card object, which represents payment info provided by the user.<br>Then using the stripe method convert it to a valid payment method.<br>And lastly synchronized it with the customer we have created before.</p><h4>Creating subscription</h4><p>The following step is about creating a subscription. The state machine configuration again looks similar to the previous ones:</p><pre>import {<br>  obtainCustomerIdService,<br>  createPaymentMethodService,<br>  <strong>createSubscriptionService</strong><br>} from &quot;./services&quot;</pre><pre>...<br>states: {<br>...<br>  <strong>createSubscription: {<br>    invoke: {<br>      src: createSubscriptionService,<br>      onDone: {<br>        target: &quot;checkSubscriptionStatus&quot;,<br>        actions: assign({<br>          subscription: (_, event) =&gt; event.data<br>        })<br>      },<br>      onError: { target: &quot;error&quot; }<br>    }<br>  }</strong><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccxtrkPGDGSrtS5AtG-lOQ.png" /></figure><p>And the service itself is once again fairly easy:</p><pre>import { callApi } from &quot;./api&quot;;</pre><pre>export const createSubscriptionService = () =&gt;<br>  new Promise(async (resolve) =&gt; {<br>    const subscription = await callApi(&quot;/subscription&quot;)<br>    resolve(subscription)<br>})</pre><p>So far we have all stuff we need. The customer written, payment method created and subscription set up. But now we need to validate the subscription status. 🔍</p><h4>Checking subscription status</h4><p>This state is not about invoking any services. All data we need are already stored in context. But how to check which way our state machine should go now?</p><p>The answer is quards 🐶. They are simple functions capable of checking context (and events) and return boolean values.<br>By using so-called <a href="https://xstate.js.org/docs/guides/guards.html#guarded-transitions"><em>guarded transitions</em></a> we are able to design the paths our machine should take.</p><p>In this case, we have 4 options:</p><ol><li>Subscription is a trial one, there is no need to check payment and we continue to the success state 👌</li><li>Subscription is invalid, and error is the destination state ⚠️</li><li>Subscription requires additional action, we need to proceed to a confirmation 💸</li><li>None of the above means the all have succeeded 🎉</li></ol><p>Using the state machine language, it looks like this:</p><pre>{<br>  id: &quot;paymentMachine,<br>  initial: &quot;idle&quot;,<br>  context: INITIAL_CONTEXT,<br>  states: {<br>  <strong>  ...</strong><br>    <strong>checkSubscriptionStatus: {<br>      on: {<br>        &quot;&quot;: [<br>          {<br>            target: &quot;paymentSuccess&quot;,<br>            cond: &quot;isTrialSubscription&quot;<br>          },<br>          {<br>            target: &quot;error&quot;,<br>            cond: &quot;isSubscriptionInvalid&quot;<br>          },<br>          {<br>            target: &quot;confirmCardPayment&quot;,<br>            cond: &quot;subscriptionRequiresAction&quot;<br>          },<br>          { target: &quot;paymentSuccess&quot; }<br>        ]<br>      }<br>    }</strong><br>  }<br>},<br>{<br>  actions: {},<br>  guards: {<br>    <strong>isTrialSubscription: context =&gt;<br>      context.subscription?.status === &quot;trialing&quot; || false,</strong></pre><pre><strong>    </strong>// Missing payment intent status means invalid subscription<strong><br>    isSubscriptionInvalid: context =&gt;<br>      !context.subscription?.latest_invoice.payment_intent.status,</strong></pre><pre><strong>    subscriptinoRequiresAction: context =&gt; <br>      context.subscription?.latest_invoice.payment_intent.status ===    <br>        &quot;requires_action&quot;</strong><br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goWBx8vP2sQVh72fIUphpQ.png" /></figure><h4>Confirming card payment</h4><p>If this is not a trialing subscription, but regular payment and the user has some tricky card, it might require some additional check. The common use case is 3D secure, which pops up some dialog for user to enter a second step verification.<br>Luckily stripe is giving us helping hand also in this case. All we need to do is call its confirmCardPayment method.</p><p>So one more time, this is a simple service invoking state.</p><pre>import {<br>  obtainCustomerIdService,<br>  createPaymentMethodService,<br>  createSubscriptionService,<br>  <strong>confirmCardPaymentService</strong><br>} from &quot;./services&quot;</pre><pre>...<br>states: {<br>...<br>  <strong>confirmCardPayment: {<br>    invoke: {<br>      src: confirmCardPaymentService,<br>      onDone: { target: &quot;paymentSuccess&quot; },<br>      onError: { target: &quot;error&quot; }<br>    }<br>  }</strong><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rv_c2d1eOALLkd0Dn5Zvtg.png" /></figure><p>But now there is nothing to set into the context. All relevant info is impersonated in entering the paymentSuccess state.</p><p>Take a look at our last service:</p><pre>export const confirmCardPaymentService = context =&gt;<br>  new Promise(async (resolve, reject) =&gt; {<br>  const { stripe, subscription } = context</pre><pre>  const clientSecret =<br>    subscription.latest_invoice.payment_intent.client_secret</pre><pre>  const result = await stripe.confirmCardPayment(clientSecret)</pre><pre>  if (result.error) {<br>    reject()<br>    return<br>  }<br>  resolve()<br>})</pre><p><strong>Payment success or error</strong></p><p>Finally, we should implement the last two states which are possible to our state machine to enter.</p><pre>states: {<br>...<br>  <strong>paymentSuccess: {<br>    type: &quot;final&quot;<br>  },<br>  error: {<br>    on: {<br>      RESET: { target: &quot;idle&quot; }<br>    }<br>  }<br></strong>}</pre><p>Final state machine visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDo04OvEUFsnvnHuuuStLg.png" /></figure><p>I know it feels bit crowded, but it is much cleaner that just staring at your code. Give it a try, and play with it by yourself!</p><p><a href="https://xstate.js.org/viz/?gist=f32dbc4b577189d11e98c536747372c3">XState Visualizer</a></p><p>Now back to our very last states.</p><p>paymentSuccess is a <em>final</em> state. It means there is no way back once you enter it. We consider our flow to be done here.</p><p>error state is representing some obstacle that appeared along the way. It can be returned back to idle state by receiving RESET event.<br>And whole this 🔼 journey can start again.</p><p>And this is it, our payment flow is ready to accept payment with stripe (at least if you also have your backend. But it is a story for another day).</p><h4>Conclusion</h4><p>If you came all the way here, let me thank you in the first place.<br>And once again do not forget to check the <a href="https://github.com/VladimirJarabica/stripe-xstate">full implementation repository</a>.<br>Surprise, it is in typescript! ❤️</p><p>I hope you can see now that state machines are not just academic concepts for torturing students 👩‍🎓. But that they can be extremely useful for our day to day frontend programming (yes I dare to name this kind of endeavors real programming 💪).</p><p>👋 Have a good day and enjoy your predictable programs! ⏳</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FiQjaL4dN1Uem4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FiQjaL4dN1Uem4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FiQjaL4dN1Uem4%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="295" frameborder="0" scrolling="no"><a href="https://medium.com/media/74ea7226a424ea329b78592b85ff07a4/href">https://medium.com/media/74ea7226a424ea329b78592b85ff07a4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9034cf32ba4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>