<?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 Amy Sitwala on Medium]]></title>
        <description><![CDATA[Stories by Amy Sitwala on Medium]]></description>
        <link>https://medium.com/@asitwala?source=rss-457a07a72479------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*71XUHBbS4mYSB_WpRqQnyQ.jpeg</url>
            <title>Stories by Amy Sitwala on Medium</title>
            <link>https://medium.com/@asitwala?source=rss-457a07a72479------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:37:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asitwala/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[Automatically Generate Chart Colors with Chart.js & D3’s Color Scales]]></title>
            <link>https://medium.com/code-nebula/automatically-generate-chart-colors-with-chart-js-d3s-color-scales-f62e282b2b41?source=rss-457a07a72479------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62e282b2b41</guid>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amy Sitwala]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 21:55:58 GMT</pubDate>
            <atom:updated>2019-11-20T03:18:06.324Z</atom:updated>
            <content:encoded><![CDATA[<p>For a fully-formatted version, you can view this tutorial on our site at:</p><p><a href="https://codenebula.io/javascript/frontend/dataviz/2019/04/18/automatically-generate-chart-colors-with-chart-js-d3s-color-scales/">Automatically Generate Chart Colors with Chart.js &amp; D3&#39;s Color Scales</a></p><h4>Who is this for?</h4><p>This tutorial is for Javascript developers who want to create beautiful charts but don’t want to manually pick the chart’s colors.</p><h4>What do I need before I start?</h4><p>You will need a basic understanding of HTML, CSS, and Javascript. Some data visualization knowledge can help.</p><h4>What will I learn?</h4><p>You will learn to create functions that, given an array of data points, will automatically create an array of colors. This technique can be used for a series of charts, including pie charts, bar charts, etc.</p><p>You can find all of the code posted here at:</p><p><a href="https://github.com/code-nebula/chart-color-generator">code-nebula/chart-color-generator</a></p><p>In this tutorial, we’ll be showing you how to use Chart.js and D3’s color scales to create a series of pie charts whose colors are computed automatically.</p><p>Generating colors automatically can be tremendously useful for the following cases:</p><p>You might have</p><ul><li><strong>A ton of data points</strong> — Manually selecting colors for this data can be an absolute pain. (Think of a pie chart with 12 colors)</li><li><strong>Data that is subject to change</strong> — Imagine hardcoding 6 color values because your dataset has 6 data points. Now an additional data point is introduced, and you have 7 data points. You’ll have to manually add a color for the new data point.</li><li><strong>A desire to distribute your colors in a “visually equidistant” manner</strong> — <a href="https://learnui.design/tools/data-color-picker.html#palette">This palette generator site</a> explains that “visually equidistant” values tend to have different base hues. Often times, you’ll find yourself using a completely different set of colors depending on the number of data points you have. If you don’t know how to create those values, you typically go on a generator site like the one mentioned and copy the values into your code.</li></ul><p>Or, like me, you just suck at color theory (what, red, green, and purple don’t go together?)</p><p>So I ended up being affected by all the cases above. I made the mistake of hardcoding 6 different color code sets depending on the length of the data (from 1–8 data points). My chart obviously broke down when there was more data. What’s worse was that I had so much config and conditional code just for this color data!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwWWRRCJd2Dw-KJnNiQV3A.jpeg" /><figcaption>Don’t make the mistakes I made!</figcaption></figure><p>You might be thinking, well, what about gradients? There is <a href="https://blog.vanila.io/chart-js-tutorial-how-to-make-gradient-line-chart-af145e5c92f9">this wonderful tutorial on setting up gradients with Chart.js</a>, but you still need to choose <em>some</em> colors.</p><p>What if you <em>never</em> needed to manually pick another hex code for your charts?</p><p>Let’s dive in.</p><h3>1. Set Up Your Workspace</h3><p>Open up your favorite text editor, and set up your workspace to follow a similar format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6pOyZxd5C2aAtGBMKf2jWA.png" /></figure><p>Here’s an explanation of the important directories and files:</p><ul><li><strong>index.html</strong> (Where we will write HTML and JS code to create our chart)</li><li><strong>utils</strong> (For helper functions, like color generating functions)</li><li><strong>styles</strong> (For CSS files)</li></ul><h4>index.html</h4><p>Because we are writing everything in vanilla, client-side Javascript, we will import the relevant packages via a content delivery network.</p><p>First, we will be importing the Chart.js library. <a href="https://www.chartjs.org/">Chart.js</a> is an open-source Javascript charting library that uses <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">HTML5 Canvas</a>.</p><pre>&lt;!-- Import Chart.js via CDN --&gt;<br>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js&quot;&gt;&lt;/script&gt;</pre><p>If you’re using NPM, you can install it via</p><pre>npm install chart.js</pre><p>Next, we will import D3’s <a href="https://github.com/d3/d3-scale-chromatic">Scale Chromatic Library</a>. This library features a wonderful, diverse set of color scales.</p><pre>!-- Import D3 Scale Chromatic via CDN --&gt;<br>&lt;script src=&quot;https://d3js.org/d3-color.v1.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://d3js.org/d3-interpolate.v1.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://d3js.org/d3-scale-chromatic.v1.min.js&quot;&gt;&lt;/script&gt;</pre><p>If you’re using NPM, you can install it via</p><pre>npm install d3-scale-chromatic</pre><p>Next, we set up our HTML and import a file called color-generator.js which lives in our utils directory.</p><p>Lastly, we set up another &lt;script&gt;&lt;/script&gt; tag. This is where we&#39;ll place our chart configuration code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560d3bf7e24d6d322706005fae180df2/href">https://medium.com/media/560d3bf7e24d6d322706005fae180df2/href</a></iframe><h4>styles/app.css</h4><p>Here we place all of our styling code. You’ll see how certain elements, like <strong>.chart-container</strong> and <strong>#pie-chart</strong> are styled once we add them to our index.html file later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5891902d9b8e65a0a582658a06d6ac48/href">https://medium.com/media/5891902d9b8e65a0a582658a06d6ac48/href</a></iframe><h3>2. Create Color Generating Functions</h3><p>First, we’ll need to introduce the concept of <strong>interpolation</strong>. D3’s <a href="https://github.com/d3/d3-interpolate">Interpolate library</a> is a good reference to learn more if you’re interested.</p><p><strong>Interpolation</strong> is essentially when you map a value in the domain [0, 1] to a value in a specific range.</p><p>In this case, our range will be a set of color codes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*A4wiqRndvfK9mWN0PVOTww.jpeg" /><figcaption>Some D3 Color Scales</figcaption></figure><p>While D3’s Scale Chromatic library provides many color scales, we will only be using their <strong>interpolate </strong>color scales (they’re the ones that start with “d3.interpolate…”). All of the <strong>interpolate</strong> color scales have a domain of [0, 1]. So what happens if you choose a number in this domain? If you choose 0.2, you will receive a color that falls at the 0.2 mark on the scale.</p><p>Here’s an image to clarify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHV3m6Z4IQEmLMJoAwq9pQ.jpeg" /><figcaption>Interpolation using D3’s “d3.interpolateWarm” scale</figcaption></figure><p>To interpolate a color based on our data set, we’ll need to first map our data set to the color scale range, [0, 1].</p><p>We do this by breaking down our dataset into intervals of length 1.</p><h3><strong>EXAMPLE #1</strong></h3><p>Say we had a dataset of length 4. We’d need to map our dataset range, <strong>[0, 4]</strong>, to the color scale’s range, <strong>[0, 1]</strong>.</p><p><strong>Data related information</strong> <br>dataLength = 4;</p><p><strong>Color related information</strong> <br>colorStart = 0; <br>colorEnd = 1; <br>colorRange = 1;</p><p>We need to find the size of the color scale’s interval.</p><p>Our dataset intervals look like: <br><strong>(0, 1), (1, 2), (2, 3), (3, 4)</strong></p><p>The corresponding color intervals will look like: <br><strong>(0, 1/4), (1/4, 2/4), (2/4, 3/4), (3/4, 1)</strong> or <strong>(0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1)</strong></p><p>We’re dividing the color scale’s range length, 1, by the dataset’s range length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJysLrqjDA5qJ1tpgP4Edw.jpeg" /><figcaption>4 datapoints with color range [0, 1] (using “d3.interpolateWarm” scale)</figcaption></figure><p>Now let’s try a more complicated example.</p><h3>EXAMPLE #2</h3><p><strong>Data related information</strong> <br>dataLength = 4;</p><p><strong>Color related information</strong> <br>colorStart: 0.25; <br>colorEnd: 0.75; <br>colorRange = 0.5;</p><p>We want to map our dataset range, <strong>[0, 4]</strong>, to the color scale’s range, <strong>[0.25, 0.75]</strong>.</p><p><strong>Dataset intervals: (0, 1), (1, 2), (2, 3), (3, 4) -&gt; Color Intervals: ?</strong></p><p>First we find the <strong>colorRange</strong>, which is 0.75 - 0.25 = 0.5.</p><p>Notice that the <strong>intervalSize</strong> is colorRange / dataLength, so it is 0.5/4, or <strong>0.125</strong>.</p><p>Our scale starts at <strong>0.25</strong>, so that’s our starting number (<strong>colorStart</strong>).</p><p>Taking these two concepts into account, let’s build our <strong>color intervals</strong>:</p><p><strong>(0.25, (0.25 + (0 * 0.125))), <br>(0.25, (0.25 + (1 * 0.125))), <br>(0.25, (0.25 + (2 * 0.125))), <br>(0.25, (0.25 + (3 * 0.125)))</strong></p><p>or</p><p><strong>(0.25, 0.375), <br>(0.375, 0.5), <br>(0.5, 0.625), <br>(0.625, 0.75)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTikrIPT7MfKQd8NrQn_aQ.jpeg" /><figcaption>4 datapoints with color range [0.25, 0.75] (using “d3.interpolateWarm” scale)</figcaption></figure><p>Our equation, as we move up the scale, becomes</p><p>colorStart + (i * intervalSize)</p><p>…where i represents the index of the data point.</p><p>Note that we use the beginning of the <strong>interval</strong> as our color value. If you wanted to use the end of each <strong>interval</strong>, your equation would be</p><p>colorStart + ((i + 1) * intervalSize)</p><p>If we want to use the end of the <strong>scale</strong> as the start, we would move down the scale:</p><p>colorEnd - (i * intervalSize)</p><p>Taking these ideas into account, we can create a function to calculate a point in the range [0, 1] based on our dataset’s length. Remember</p><p>intervalSize = colorRange / dataLength</p><h4>utils/color-generator.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04ca8f9de4fd47a19d9d66e059aa12af/href">https://medium.com/media/04ca8f9de4fd47a19d9d66e059aa12af/href</a></iframe><p>Now that we understand how the colors are calculated, we can create an array of colors based on our data’s length (the number of data points).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6246b8ca858fecb0c249e05e4e43d9ae/href">https://medium.com/media/6246b8ca858fecb0c249e05e4e43d9ae/href</a></iframe><h3>3. Create Your Chart</h3><p>Now that we’ve got our color functions, we’ll focus on creating our chart.</p><p>We’ll be creating a pie (or “doughnut” to be more accurate) chart for this tutorial. However, you can still apply these concepts across other charts (bar charts, etc.)</p><p>We’ll create the chart in the “index.html” file because the necessary libraries will be imported there. I could place the libraries on the window (window.Chart = Chart), but I don’t want to go down that route. Just know that in a non-demo case, you’d likely want to place the following code snippets in a separate Javascript file.</p><h4>HTML Section — index.html</h4><p>In the body of the HTML portion of index.html, we’ll add a container for styling. Note that we’ll be mounting our pie chart to a <strong>“canvas”</strong> element. So let’s create that element and give an <strong>“id”</strong> attribute so we can later easily reference it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/455505811cd4220ef94b489a673516d0/href">https://medium.com/media/455505811cd4220ef94b489a673516d0/href</a></iframe><h4>Javascript Section — index.html</h4><p>First, we’ll set up our createChart function that take in an id, the chart data, the requested D3 interpolate color scale, and our color range information.</p><p>function createChart(chartId, chartData, colorScale, colorRangeInfo)</p><ul><li><strong>chartId</strong>: String</li><li><strong>chartData</strong>: { <strong>data</strong>: Array, <strong>labels</strong>: Array }</li><li><strong>colorScale</strong>: Function (D3 interpolate color scale)</li><li><strong>colorRangeInfo</strong>: { <strong>colorStart</strong>: Number, <strong>colorEnd</strong>: Number, <strong>useEndAsStart</strong>: Boolean }</li></ul><p>We’ll then grab our canvas element by using the inputted id. Then we’ll calculate the data’s length and pass it to our interpolateColors function. (Remember that we have access to these functions because we imported the color-generator.js file).</p><p>We configure our charts according to <a href="https://www.chartjs.org/docs/latest/charts/doughnut.html">Chart.js’</a> documentation. We specify the type of the chart, pass in the labels, pass in colors for the pie chart segments and segments on hover, and the chart data.</p><p>Then we choose to make the chart responsive, specify that we don’t want a legend, and set the cursor to have the “pointer” style on hover.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d69af0d352f46ed47e9e0029206dd7d/href">https://medium.com/media/6d69af0d352f46ed47e9e0029206dd7d/href</a></iframe><p>Next, we create a random number generator with min and max values to act as the range. We use this function to create dummy data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66422fc8645de8ab4dfc44a4a750049d/href">https://medium.com/media/66422fc8645de8ab4dfc44a4a750049d/href</a></iframe><p>Now it’s time for us to set up our example parameters and pass them into our createChartfunction.</p><p>I create an array of length 10, and for each data point, I generate a random number within the range [20, 110]. I generate labels that take the form “Label i”, where i is the index.</p><p>I set the colorScale as d3.interpolateInferno. Lastly I specify the colorRangeInfo where I set the start and end of the interval (both values must be within 0 and 1) and choose if I want to use the end of the color scale as my starting point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59f9ab6f1c71a8778b525cff1ee1452f/href">https://medium.com/media/59f9ab6f1c71a8778b525cff1ee1452f/href</a></iframe><p>Lastly, call your createChart function with the example parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46689dbe1706181984dd3bb9ebc7cb4d/href">https://medium.com/media/46689dbe1706181984dd3bb9ebc7cb4d/href</a></iframe><p>If you open your <strong>index.html</strong> in your browser, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TuQCAfINxe1ZXQ1z-mGGEA.jpeg" /></figure><h3>4. Mess Around With the Parameters (colorStart, colorEnd, useEndAsStart)</h3><p>We can mess around with the parameters mentioned above to produce various charts.</p><p><strong>Changing the Color Range</strong></p><p>In the previous example, I think the starting color is too dark. Let’s change the start value so that the colorRangeInfo object looks like</p><pre>const colorRangeInfo = {<br>   colorStart: 0.2,<br>   colorEnd: 1,<br>   useEndAsStart: false,<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pa6I1JINs58UYzYxPPa3g.jpeg" /><figcaption>Changing the “colorStart” parameter</figcaption></figure><p><strong>Using the End of the Scale as the Start</strong></p><p>Change the colorRangeInfo object to look like</p><pre>const colorRangeInfo = {<br>   colorStart: 0.2,<br>   colorEnd: 1,<br>   useEndAsStart: true,<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSdhQRwMtu6d0MX5OztLDw.jpeg" /><figcaption>Setting the “useEndAsStart” parameter to true</figcaption></figure><p><strong>Various Combinations</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pkjmai2OudY33Avb6M7Mhw.jpeg" /></figure><p>Feel free to check out more <strong>interpolate</strong> scales from <a href="https://github.com/d3/d3-scale-chromatic">D3 Scale Chromatic’s github page</a>.</p><p>Thanks for reading!</p><p><em>Do you want a clear and intuitive way to keep up with your Stripe subscriptions?</em></p><p><strong><em>ProfitKit</em></strong><em> is a free calendar for your Stripe account that allows you to track expiring trials, upcoming cancellations and expected payments from your customers in a simple and effective way. Integration with Google Calendar is included in our free plan.</em></p><p><em>Sign up for free at </em><a href="https://www.profitkit.io/"><em>https://www.profitkit.io</em></a><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN-uERvnEzXEfBPnl9voBA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62e282b2b41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-nebula/automatically-generate-chart-colors-with-chart-js-d3s-color-scales-f62e282b2b41">Automatically Generate Chart Colors with Chart.js &amp; D3’s Color Scales</a> was originally published in <a href="https://medium.com/code-nebula">Code Nebula</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 3)]]></title>
            <link>https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-3-63c56b991009?source=rss-457a07a72479------2</link>
            <guid isPermaLink="false">https://medium.com/p/63c56b991009</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[subscription]]></category>
            <dc:creator><![CDATA[Amy Sitwala]]></dc:creator>
            <pubDate>Fri, 12 Apr 2019 21:44:30 GMT</pubDate>
            <atom:updated>2019-04-12T21:55:37.153Z</atom:updated>
            <content:encoded><![CDATA[<p>For a fully-formatted version, you can view this tutorial on our site at:</p><p><a href="https://codenebula.io/stripe/node.js/2019/04/11/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-3/">Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 3)</a></p><p>As a reminder, this tutorial is broken up into 3 parts:</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03">PART 1</a>: Provides a general overview and demonstrates how to create subscription plans via the Stripe Dashboard.</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-2-66ecf510fae3">PART 2</a>: Goes into best practices when it comes to setting up your workspace with Node, Express, the Stripe API, etc.</p><p><strong>PART 3 (You’re here)</strong>: Shows you how to use the customer’s inputted card number to create a Stripe Token, Customer, and Subscription.</p><p>You can find all of the code posted here at:</p><p><a href="https://github.com/code-nebula/stripe-recurring-subscriptions">https://github.com/code-nebula/stripe-recurring-subscriptions</a></p><p>You might notice that some of the code in our repository isn’t featured in this tutorial. That’s because the repository includes code for</p><ol><li>An <strong>Admin</strong> View — Where you can create “Products” and “Plans” through the Stripe API. We’ll be covering how to do this in <strong>a separate blog post</strong>.</li><li>A <strong>Client</strong> View — Where your users can view and pay for your “Plans”. We are covering how to set this up in <strong>this tutorial</strong>.</li></ol><p>If any of these Stripe terms are unfamiliar to you, don’t worry, they’re covered in <a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03">Part 1</a>.</p><p>We last left off with a request to render the “signUp.html” page. Now we will actually code up that page.</p><p>It will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CL8h11PpPc0FaNR10H0eXA.png" /><figcaption>Sign Up Form that doubles as a Payment Form</figcaption></figure><h3>6. Set up Your Payment Form &amp; Create a Stripe Token</h3><p>First, we’ll need to set up a form where your customer can enter their credit card information.</p><p>For security purposes, we’ll want to avoid actually sending that raw credit card information to our server. Stripe understands this security concern and thus offers <a href="https://stripe.com/docs/api/tokens?lang=node">a few options</a> for securely collecting that data client-side.</p><p>For the purposes of this tutorial, we’ll be using <a href="https://stripe.com/docs/stripe-js/elements/quickstart">Stripe Elements</a> to handle card information.</p><p>If you remember from the last part, we included the Stripe client-side library in our “views/base.html” file. We included it in the “base.html” file as opposed to just on our sign up page, “signUp.html” because Stripe recommends we include this library on every page of our site to best protect against fraud.</p><pre>&lt;script src=&quot;<a href="https://js.stripe.com/v3/">https://js.stripe.com/v3/</a>&quot;&gt;&lt;/script&gt;</pre><p>Because all our HTML files extend “views/base.html”, we have access to this library in our “signUp.html” file.</p><p>Let’s move on to setting up this file:</p><p>If you’d prefer to see the code all at once instead of as snippets down below, please check out this Github link:</p><p><a href="https://github.com/code-nebula/stripe-recurring-subscriptions/blob/master/views/signUp.html">code-nebula/stripe-recurring-subscriptions</a></p><h4>HTML section — views/signUp.html</h4><p>Here, we take the passed-in parameters (product and plan) and access their relevant properties (product.name, plan.name, plan.amount, etc.). We do this to show the customer which product and plan they&#39;re signing up for. In the real version of the site, you would probably only show plan information (since the product represents the site).</p><p>Then we set up a conditional section that renders either a success or error message. Don’t worry about this section right now — it only becomes relevant after we submit the payment form, and our server sends us either a “success” or “error” parameter depending on how the payment was processed.</p><p>Next, we set up our payment form. As before, we’re utilizing the power of hidden input fields to grab data about our product and plan — we’ll need this data when we</p><ol><li>Create a Subscription after the form is submitted and</li><li>Re-render this page with a success or error message</li></ol><p>Then we create a simple input field to capture the customer’s email. Now comes the interesting part. We create a container div for our Stripe Elements instance: &lt;div id=&quot;card-element&quot;&gt;</p><p>We do the same thing and create a container div for the error messages that the Stripe Elements instance sends us: &lt;div id=&quot;card-errors&quot; role=&quot;alert&quot;&gt;</p><p>Lastly, we include an input of type “submit” to actually submit our form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede5630e22b123eddc004eb942b5e380/href">https://medium.com/media/ede5630e22b123eddc004eb942b5e380/href</a></iframe><h4>Javascript Section — views/signUp.html</h4><p>Note: All of the Javascript except for the helper function stripeTokenHandler is wrapped in an if (document.getElementById(&#39;card-element&#39;)) conditional block because the sign-up page doubles as a confirmation page. In the confirmation page, we don&#39;t render the payment form (see the HTML code above with the success, else if error, and else blocks).</p><p>Since I’ll be explaining the Javascript in many code snippets, I won’t be including the wrapper conditional block below, but it’s available on the <a href="https://github.com/code-nebula/stripe-recurring-subscriptions/blob/master/views/signUp.html">Github page</a>.</p><p>First, we’ll invoke the client-side Stripe Javascript library by passing in our Publishable Test Key. Unlike our Stripe Secret test key, our Stripe Publishable test key is not confidential, so it’s alright to include in your application code.</p><p>Then we create an instance of Stripe Elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c92b82ae28e81be578775b4f3c6549bc/href">https://medium.com/media/c92b82ae28e81be578775b4f3c6549bc/href</a></iframe><p>Because the Stripe Elements instance is wrapped in an iframe, it is difficult to style all of it with our own CSS. However, Stripe accounts for this and let’s us specify our own custom styles object so that the instance can match the rest of our form. Note that this styles object affects the <strong>inputs themselves</strong>, NOT the overall Stripe Elements container (that is handled in a CSS section below). The <strong>“base”</strong> property refers to the normal state, while <strong>“invalid”</strong> refers to the error state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f304f19dea47e4f7a75b28537f60df4b/href">https://medium.com/media/f304f19dea47e4f7a75b28537f60df4b/href</a></iframe><p>Next, we tell our Stripe Elements instance to specifically create the “card” element. The “card” element is a simple input field that features sections for the credit card number, CVC number, expiration date, and zip code.</p><p>We then attach, or mount, that Stripe Elements card instance to the div in our HTML with the id <strong>“card-element”</strong>.</p><p>Then we set up an event listener on the card instance. It listens for any changes in the inputs and if an error exists, it populates the error within the <strong>‘#card-errors’</strong> div.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88d28b03b2781243a3184371b8f8d17f/href">https://medium.com/media/88d28b03b2781243a3184371b8f8d17f/href</a></iframe><p>The following code intercepts the initial form “submit” event when we click the “Pay” button. event.preventDefault() prevents the form from being submitted and passing data to our Node server.</p><p>The next section introduces an important Stripe feature, <strong>tokenization</strong>.</p><p><a href="https://stripe.com/docs/api/tokens?lang=node">Tokens</a> are essentially how Stripe collects and abstracts sensitive card or bank information. Creating tokens on the client-side (as we will do with Stripe Elements) ensures that card information isn’t passed to our server. If it were passed to our server, someone could potentially intercept or monitor the request and see the sensitive data being passed.</p><p>Tokens, however, are safe to pass since they are an abstraction.</p><p>Note that tokens cannot be used more than once. This is why, as you’ll soon see, we’ll need to create a Stripe <strong>Customer</strong>. We can attach a token as a payment source for the Customer and thus create recurring charges.</p><p>So in the code below, we call the createToken method from the Stripe client-side library and pass in our Stripe Elements card instance.</p><p>If there is an error, we populate the ‘#card-errors’ div, otherwise we pass the successfully returned token to a helper function called stripeTokenHandler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/512bf3289344aaa0e806872ff81d08d3/href">https://medium.com/media/512bf3289344aaa0e806872ff81d08d3/href</a></iframe><p>The stripeTokenHandler function essentially grabs the payment form and adds yet another hidden input field with the token value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8534e186b87718df2ee2b13ced08a929/href">https://medium.com/media/8534e186b87718df2ee2b13ced08a929/href</a></iframe><h4>CSS Section — views/signUp.html</h4><p>This code is taken directly from the <a href="https://stripe.com/docs/stripe-js/elements/quickstart">Stripe Elements Quickstart </a>CSS portion. It is used to style the Stripe Elements container, not the actual inputs (which is what the custom styling above was used for).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b80bc94adb416068b64bca951198c3/href">https://medium.com/media/32b80bc94adb416068b64bca951198c3/href</a></iframe><h3>7. Create a Customer and Subscription</h3><p>As I mentioned above, we’ll need to attach the token to a Stripe Customer. Let’s go back to our <strong>“stripe-functions.js”</strong> file and create a helper function to handle this logic.</p><p>We will create a new function called createCustomerAndSubscription which will chain the process of creating a <strong>customer from a token</strong> and then creating a <strong>subscription from a customer</strong>.</p><p>We call stripe.customers.create() <a href="https://stripe.com/docs/api/customers/create">(API docs) </a>and pass in the customer&#39;s email and the token.</p><p>(Note that we specify the token as a “source”. A “source” in Stripe terminology is essentially a representation of a customer’s payment method. They can be tokens as well <a href="https://stripe.com/docs/api/sources">as other things</a>.)</p><p>Once we’ve created a customer, we take the result (a Customer object) and call another Stripe API method, stripe.subscriptions.create <a href="https://stripe.com/docs/api/subscriptions/create">(API docs)</a>. We pass in the customer id and create a plan object in the itemsarray. Notice that we are essentially connecting a Customer to a Plan! (Remember the diagram in Part 1)?</p><h4>api/stripe-functions.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f2fec9fa59a6d10c3f32fcbddb1ce8/href">https://medium.com/media/b2f2fec9fa59a6d10c3f32fcbddb1ce8/href</a></iframe><p>Now we’re ready to export this function and use it — make sure your <strong>“module.exports”</strong> at the bottom of the file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4867a8fe4d6be7f0173b197998e0ad2e/href">https://medium.com/media/4867a8fe4d6be7f0173b197998e0ad2e/href</a></iframe><h4>app.js</h4><p>Now that we’ve set up our helper function to create a Stripe Customer and Subscription, let’s see how it’s used when our sign-up page is submitted.</p><p>First we create product and plan objects that will be passed back as parameters in the confirmation page (recall that “signUp.html” doubles as a sign-up and confirmation page).</p><p>Next we invoke the createCustomerAndSubscription method and pass in req.body as the function parameter -- this is because the request body contains the token and plan information.</p><p>If the creation of a customer and subscription is successful, we render the sign-up page again, but now with a success parameter. Otherwise, we render the sign-up page with an errorparameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e005f0813648200b074aa3afaa88d795/href">https://medium.com/media/e005f0813648200b074aa3afaa88d795/href</a></iframe><p>And now we’re set to test our form out!</p><p>Run your application via npm start and once again, navigate to <a href="/service/localhost:3000/customerView">localhost:3000/customerView</a>.</p><p>Click the <strong>“Sign Up”</strong> button on either of the plans. You should then see the payment form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CL8h11PpPc0FaNR10H0eXA.png" /></figure><p>Enter any email and enter Stripe’s test number 4242 4242 4242 4242. Then choose any <strong>CVC number</strong>, <strong>future expiration date</strong>, and <strong>U.S. ZIP code</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOfx_WokjI0-vF6mXFasKA.png" /></figure><p>Hit the <strong>“Pay”</strong> button, and you should see the following success page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPX4UrzkwfzpZmoaLnvF7Q.png" /></figure><p>To verify if a Customer and Subscription have actually been created, navigate to your <a href="https://dashboard.stripe.com/">Stripe Dashboard</a>.</p><p>In the sidebar, click on <strong>“Billing”</strong>, and once expanded, click on <strong>“Subscriptions”</strong>. You should now see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08fTgiUl7qwYa9cT056T0A.png" /></figure><p>If you click on the Customer, you’ll get a more detailed view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaoBFrApGSUSUGTZSqKdZA.png" /></figure><p>And that’s it! You’ve created your first recurring subscription with Stripe! Congratulations on making it this far!</p><h3>8. Next Steps</h3><p>So far, we’ve been developing everything in a test environment. The next steps would be to set up your application for a live/production environment.</p><p>You’ll need to</p><ul><li>Activate Your Account</li><li>Switch out your test Stripe Secret Key and Stripe Publishable Key for live versions</li><li>Serve your site over HTTPS to keep payment information safe and uncompromised</li></ul><p>If you’re interested in these next steps and would like a more detailed guide, <a href="https://codenebula.io/contact/">please let us know</a>!</p><p><em>Do you want a clear and intuitive way to keep up with your Stripe subscriptions?</em></p><p><strong><em>ProfitKit</em></strong><em> is a free calendar for your Stripe account that allows you to track expiring trials, upcoming cancellations and expected payments from your customers in a simple and effective way. Integration with Google Calendar is included in our free plan.</em></p><p><em>Sign up for free at </em><a href="https://www.profitkit.io/"><em>https://www.profitkit.io</em></a><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN-uERvnEzXEfBPnl9voBA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63c56b991009" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-3-63c56b991009">Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 3)</a> was originally published in <a href="https://medium.com/code-nebula">Code Nebula</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 2)]]></title>
            <link>https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-2-66ecf510fae3?source=rss-457a07a72479------2</link>
            <guid isPermaLink="false">https://medium.com/p/66ecf510fae3</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Amy Sitwala]]></dc:creator>
            <pubDate>Fri, 12 Apr 2019 21:42:10 GMT</pubDate>
            <atom:updated>2019-04-12T21:54:59.714Z</atom:updated>
            <content:encoded><![CDATA[<p>For a fully-formatted version, you can view this tutorial on our site at:</p><p><a href="https://codenebula.io/stripe/node.js/2019/04/11/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-2/">Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 2)</a></p><p>As a reminder, this tutorial is broken up into 3 parts:</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03">PART 1</a>: Provides a general overview and demonstrates how to create subscription plans via the Stripe Dashboard.</p><p><strong>PART 2 (You’re here)</strong>: Goes into best practices when it comes to setting up your workspace with Node, Express, the Stripe API, etc.</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-3-63c56b991009">PART 3</a>: Shows you how to use the customer’s inputted card number to create a Stripe Token, Customer, and Subscription.</p><p>You can find all of the code posted here at:</p><p><a href="https://github.com/code-nebula/stripe-recurring-subscriptions">https://github.com/code-nebula/stripe-recurring-subscriptions</a></p><p>You might notice that some of the code in our repository isn’t featured in this tutorial. That’s because the repository includes code for</p><ol><li>An <strong>Admin</strong> View — Where you can create “Products” and “Plans” through the Stripe API. We’ll be covering how to do this in <strong>a separate blog post</strong>.</li><li>A <strong>Client</strong> View — Where your users can view and pay for your “Plans”. We are covering how to set this up in <strong>this tutorial</strong>.</li></ol><p>If any of these Stripe terms are unfamiliar to you, don’t worry, they’re covered in <a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03">Part 1</a>.</p><p>In the last section, we created our Stripe Product, <strong>Simple Albums</strong> and our 2 Plans, <strong>Hobbyist</strong> and <strong>Professional</strong>. In this section, we’ll be setting up our web application and grabbing data about these Products and Plans via the Stripe API.</p><p>Now, on to the technical part!</p><h3>4. Set up Your Workspace and Application Server</h3><p>First, open up your terminal and create a new Express app. As mentioned above, if you’re not familiar with Express, no worries — the Express site has some easy-to-follow documentation here: <a href="http://expressjs.com/en/starter/installing.html">http://expressjs.com/en/starter/installing.html</a>.</p><p>Next, install the following packages using your favorite package manager (npm, yarn, etc.):</p><ul><li><strong>body-parser</strong> (<a href="https://www.npmjs.com/package/body-parser">https://www.npmjs.com/package/body-parser</a>)</li><li><strong>nunjucks</strong> (<a href="https://www.npmjs.com/package/nunjucks">https://www.npmjs.com/package/nunjucks</a>)</li><li><strong>dotenv</strong> (<a href="https://www.npmjs.com/package/dotenv">https://www.npmjs.com/package/dotenv</a>)</li><li><strong>stripe</strong> (<a href="https://www.npmjs.com/package/stripe">https://www.npmjs.com/package/stripe</a>)</li></ul><p>We will use the <strong>body-parser</strong> package to parse incoming request bodies as “req.body” in our server-side code. We will use <strong>nunjucks</strong> for templating and passing data into our HTML files. We will use the <strong>dotenv</strong> package to house Stripe Secret keys. Lastly, we will use the <strong>stripe</strong> package to make Stripe API calls.</p><p>Next, set up your workspace to follow a similar format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*Ll1SrCF2Fdl0lFs6P3dLpg.png" /></figure><p>Here’s an explanation of the important directories and files:</p><ul><li><strong>api</strong> (We recommend having an “api” directory with the Stripe API calls in an effort to make your code more organized and modular)</li><li><strong>node_modules</strong> (Holds your installed dependencies)</li><li><strong>styles</strong> (For CSS files)</li><li><strong>utils</strong> (For helper functions)</li><li><strong>views</strong> (For your templates — your HTML files)</li><li><strong>.env</strong> (For your Stripe Secret API key)</li><li><strong>.gitignore</strong> (Where you will note which files — like “.env”, which houses unshareable secret keys — should not be version controlled and checked into your Github repository)</li><li><strong>app.js</strong> (For all of your server and application routing logic)</li><li><strong>package.json</strong> (Holds information about your app, including which dependencies you are using, etc.)</li></ul><h4>app.js</h4><p>Here we officially set up an Express application and import all necessary dependencies like <strong>body-parser</strong> and <strong>nunjucks</strong>.</p><p>Here’s a summary of what you will do in this file:</p><ul><li>Set the server to listen on port 3000</li><li>Import our Stripe API functions (we will set these up soon)</li><li>Set up Nunjucks with Express to serve up and render HTML files</li><li>Set up the content in the <strong>styles</strong> directory to be served up through the Express app</li><li>Set up your Express router to route client requests to different pages</li><li>Set up our Express app to start a server and listen for connections on the specified port</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3881c3d5f3cfbbf05088664795034b97/href">https://medium.com/media/3881c3d5f3cfbbf05088664795034b97/href</a></iframe><h4>views/base.html</h4><p>This file is your base HTML template. All other HTML files will be extended from this template, so you don’t have to repeat all the “set-up” code. By this, I mean the document metadata (the stuff under the “head” tag) and base structure (including all content within the styled “app-container” div).</p><p>Notice that there is some logic concerning an “Admin” vs. “Client”/”Customer” View. As mentioned in <a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03">Part 1</a>, this tutorial series will only cover the “Client”/”Customer” View. A separate blog post will cover the “Admin” view, where we will show you how to create Products and Plans via the Stripe API.</p><p>Also note that this file imports two CSS files, adminView.css and customerView.css. I won&#39;t be including the code snippets in this tutorial, because they&#39;re a bit long, but feel free to check them out here:</p><p><a href="https://github.com/code-nebula/stripe-recurring-subscriptions/tree/master/styles">https://github.com/code-nebula/stripe-recurring-subscriptions/tree/master/styles</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b499257a0cfec13cdb8ccbe50966ecea/href">https://medium.com/media/b499257a0cfec13cdb8ccbe50966ecea/href</a></iframe><h4>package.json</h4><p>An important piece of logic you need in your package.json is the “start” script (see “scripts” -&gt; “start”). The command npm run start will run node app.js to make your Express application start a server (basically this command will execute all of the logic specified in your <strong>app.js</strong> file).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b617592f3ad5364a17198e924530f7/href">https://medium.com/media/b5b617592f3ad5364a17198e924530f7/href</a></iframe><h4>.env</h4><p>The dot env file is a place where you can store environment variables. Environment variables are essentially key-value pairs that are loaded into the application at build time (in this case, they’re loaded in as process.env.{VARIABLE_NAME}. Environment variables can be used for many <a href="https://medium.com/chingu/an-introduction-to-environment-variables-and-how-to-use-them-f602f66d15fa">purposes</a>.</p><p>In this case, we’ll be treating the Stripe Secret key as an environment variable for security purposes. We don’t want other people to see this value (like on Github), yet we need it to be included in our application in order to properly configure the Stripe API. The dot env file allows us to store this secure data separately from our application logic. To use it in our application, we will later</p><ol><li>Require and configure dotenv and</li><li>Load in our Secret key via process.env.STRIPE_API_KEY</li></ol><p>To find the Secret key, go to the Stripe Dashboard — <a href="https://dashboard.stripe.com/">www.dashboard.stripe.com</a> — and click on the <strong>“Developers”</strong> menu item in the left sidebar to expand your options. Once expanded, click on <strong>“API keys”</strong>. In the main dashboard, you’ll see a section called <strong>“Standard Keys”</strong>. In this section, click to reveal the <strong>“Secret Key”</strong> token. This is the value of your Stripe Secret Key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38059f4fb94b7b1c5cc2ad53e3e70f69/href">https://medium.com/media/38059f4fb94b7b1c5cc2ad53e3e70f69/href</a></iframe><h4>.gitignore</h4><p>If you’re using git and are considering uploading your repository online, it’s important that you do <strong>NOT</strong> upload your Stripe Secret key stored in your .env file. Remember this is sensitive data that can allow other people to have programmatic access to your Stripe account.</p><p>We need to make sure that the .env file is not version controlled or checked in at any point. We can ignore it by specifying it in a .gitignore file. It’s also good practice to ignore checking in your node_modules, as checking these in can inflate storage and lead to many unnecessary merge conflicts in the future. Remember that your node_modules can always be reproduced by running npm install.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57207f1256d9ae43f9fdd6244d42a598/href">https://medium.com/media/57207f1256d9ae43f9fdd6244d42a598/href</a></iframe><h3>5. Set up Your Pricing “Table”</h3><p>In this step, we will create the Pricing Plan table customer view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmXhCOM3X1rwY02vLhYKPg.jpeg" /></figure><h4>api/stripe-functions.js</h4><p>As stated above, we recommend having an <strong>“api”</strong> directory with the Stripe API calls in an effort to make your code more organized and modular. Ideally, you may want a file for each part of the Stripe API you’re dealing with, but since we don’t make too many API calls in this tutorial, we’ll put everything within a <strong>“stripe-functions.js”</strong> file.</p><p>First, we will configure the <strong>“dotenv”</strong> package to be used in our application. Then we will initialize our instance of the Stripe API. We do this by importing the Stripe package and passing our Stripe secret key (as process.env.STRIPE_API_KEY) as a parameter.</p><p>Next, we will import some helper functions from the <strong>“utils”</strong> directory (I will showcase these functions as the next code snippet).</p><p>Then we create a function called getAllProductsAndPlans. This function utilizes the Stripe functions stripe.products.list({}) and stripe.plans.list({}) to grab all of your Stripe account&#39;s products and plans. Since these two functions return Javascript Promises and the functions are independent of each other, we use &quot;Promise.all&quot; to resolve them both at the same time (instead of chaining together the two promises and waiting for one to return before we call the second).</p><p>Once we get all the product and plan data, we sort the plans in ascending order of price (the <strong>“amount”</strong> field). Then we format the amount in dollars and cents. The Stripe amount is stored as a number, and it represents the price in cents. For instance, our Hobbyist Plan’s Stripe amount would be 2000 (which represents $20.00).</p><p>Lastly, we attach the appropriate plans to their corresponding product, so that the product now has a <strong>“plans”</strong> field that we can iterate through.</p><p>Instead of retrieving all products, you could have also retrieved the product (“Simple Albums”) that you were interested in by calling the <a href="https://stripe.com/docs/api/products/retrieve">“Retrieve a Product”</a> function and passing in the desired Product Id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2b9feb6ad706c2f83ea35cfb83cc132/href">https://medium.com/media/d2b9feb6ad706c2f83ea35cfb83cc132/href</a></iframe><h4>utils/format-numbers.js</h4><p>This file contains some helper functions to go between formatted USD numbers and Stripe amounts. (See section above for info on Stripe amounts)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56586e8164f07a2723b3c625afc784c5/href">https://medium.com/media/56586e8164f07a2723b3c625afc784c5/href</a></iframe><h4>app.js</h4><p>In this file, we call the function getAllProductsAndPlans to grab all of our Stripe product and plan information. Once we receive that data, we filter for products that actually have plans set up.</p><p>Then we render our “Customer View” and pass in the filtered product data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0a331ba713ba55fa773fa1011975bf2/href">https://medium.com/media/d0a331ba713ba55fa773fa1011975bf2/href</a></iframe><h4>views/customerView.html</h4><p>The goal of this “Customer View” page is to iterate through all products and their corresponding plans. In the real site, you may only want to display the plans for 1 specific product.</p><p>We set up a Sign Up form for each plan, and in the form, we include hidden inputs for the product name and the plan id, nickname, amount, interval, and interval_count.</p><p>Since we’re not using a Javascript front-end framework, this is our way of passing data to another page.</p><p>Once a user clicks on a specific plan’s “Sign Up” button, the data mentioned above (product name, plan id, plan nickname, plan amount, plan interval, and plan interval_count) will be submitted to our Express server through a POST request (via form action=&quot;/signUp&quot;).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bad3ddf5f4702cc0eff2aa86e5ae9558/href">https://medium.com/media/bad3ddf5f4702cc0eff2aa86e5ae9558/href</a></iframe><p>At this point, if you run your app via npm start and navigate to <a href="/service/localhost:3000/customerView">localhost:3000/customerView</a>, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmXhCOM3X1rwY02vLhYKPg.jpeg" /></figure><p>Next, we will handle what happens when you click on either of the “Sign Up” buttons.</p><h4>app.js (Back here)</h4><p>Here we will take the submitted product and plan data and pass it to a plan-specific sign up page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaa90e4f87147db33bdccba784464f8e/href">https://medium.com/media/aaa90e4f87147db33bdccba784464f8e/href</a></iframe><p>The next section will cover how to create a form that when submitted, creates a Stripe token, customer, and subscription.</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-3-63c56b991009">Continue on to Part 3 of this tutorial</a></p><p><em>Do you want a clear and intuitive way to keep up with your Stripe subscriptions?</em></p><p><strong><em>ProfitKit</em></strong><em> is a free calendar for your Stripe account that allows you to track expiring trials, upcoming cancellations and expected payments from your customers in a simple and effective way. Integration with Google Calendar is included in our free plan.</em></p><p><em>Sign up for free at </em><a href="https://www.profitkit.io/"><em>https://www.profitkit.io</em></a><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN-uERvnEzXEfBPnl9voBA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66ecf510fae3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-2-66ecf510fae3">Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 2)</a> was originally published in <a href="https://medium.com/code-nebula">Code Nebula</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 1)]]></title>
            <link>https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03?source=rss-457a07a72479------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b940f90fc03</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[ecommerce]]></category>
            <dc:creator><![CDATA[Amy Sitwala]]></dc:creator>
            <pubDate>Fri, 12 Apr 2019 21:40:04 GMT</pubDate>
            <atom:updated>2019-04-12T21:54:23.863Z</atom:updated>
            <content:encoded><![CDATA[<p>For a fully-formatted version, you can view this tutorial on our site at:</p><p><a href="https://codenebula.io/stripe/node.js/2019/04/11/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1/">Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 1)</a></p><h4>Who is this for?</h4><p>This tutorial is for online business owners who would like to set up subscription billing on their website. It is fairly technical, and we assume most readers will have some development experience with Stripe and Javascript.</p><h4>What do I need before I start?</h4><p>Like many of the other posts on this site, this post also assumes you have a working Stripe account and know how to set up a basic Node / Express server to serve HTML files and receive HTTP requests. If you don’t know how to do these things, no problem! You can still follow along but you may want to consider checking out these docs:</p><p><a href="https://docs.npmjs.com/cli/start">https://docs.npmjs.com/cli/start</a></p><p><a href="https://nodejs.org/en/docs/guides/getting-started-guide/">https://nodejs.org/en/docs/guides/getting-started-guide/</a></p><p><a href="http://expressjs.com/en/starter/hello-world.html">http://expressjs.com/en/starter/hello-world.html</a></p><h4>What will I learn?</h4><p>In this tutorial, you will learn how to</p><ul><li>Create subscriptions and incorporate them into your site</li><li>Create multiple pricing plans</li><li>Charge customers by setting up your own payment form</li><li>Interact with the Stripe Dashboard and API</li></ul><p>This tutorial is broken up into 3 parts:</p><p><strong>PART 1 (You’re here)</strong>: Provides a general overview and demonstrates how to create subscription plans via the Stripe Dashboard.</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-2-66ecf510fae3">PART 2</a>: Goes into best practices when it comes to setting up your workspace with Node, Express, the Stripe API, etc.</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-3-63c56b991009">PART 3</a>: Shows you how to use the customer’s inputted card number to create a Stripe Token, Customer, and Subscription.</p><p>You can find all of the code posted here at:</p><p><a href="https://github.com/code-nebula/stripe-recurring-subscriptions">code-nebula/stripe-recurring-subscriptions</a></p><p>You might notice that some of the code in our repository isn’t featured in this tutorial. That’s because the repository includes code for</p><ol><li>An <strong>Admin</strong> View — Where you can create “Products” and “Plans” through the Stripe API. We’ll be covering how to do this in <strong>an upcoming blog post</strong>.</li><li>A <strong>Client</strong> View — Where your users can view and pay for your “Plans”. We are covering how to set this up in <strong>this tutorial</strong>.</li></ol><p>If any of these Stripe terms are unfamiliar to you, don’t worry, we’ll be covering them below.</p><p>Let’s get started!</p><p>In this tutorial, we’ll be showing you how to set up Stripe subscriptions for a fabricated software-as-a-service website called “Simple Albums.” As the name suggests, Simple Albums is a site where users can upload their photos and create beautiful, online-hosted albums.</p><p>As the owner of Simple Albums, you want to offer the following paid plans:</p><ol><li><strong>Hobbyist ($20.00/month)</strong> — users get up to 16GB in storage</li><li><strong>Professional ($50.00/month)</strong> — users get unlimited storage and can invite other people to collaborate on albums</li></ol><p>The video below outlines a customer sign-up workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*VDgHiXj9cBhXyMDQgv85ZA.gif" /><figcaption>Customer Sign-up Workflow Demo</figcaption></figure><p>Your customers will see two pricing plans that they can choose from. When they click to sign up, they will be directed to a sign up form when they enter their payment credentials.</p><p>In the <strong>real</strong> (not demo) version of the site, it may make more sense to 1. have the payment form inside your application (past the sign up screen) and 2. appear after a trial period. For the purposes of keeping this tutorial direct, though, we’ve included payment with the sign-up form.</p><h3>1. Understand Stripe’s terminology (Products, Plans, Subscriptions, and Customers)</h3><p>It’s important for you to understand Stripe’s terminology, especially since it can be a bit misleading if you’re new to Stripe. For instance, it might be tempting to jump right into Stripe’s <strong>Subscription </strong>object, but you should really start with Stripe’s <strong>Product</strong> object. So what’s the difference?</p><p>A <strong>Product</strong> is essentially the subscription service you are offering. A <strong>Product</strong> can have many <strong>Plan</strong>s. A <strong>Subscription</strong> connects a <strong>Customer</strong> to a <strong>Plan</strong>.</p><p>Here’s a diagram that might help you visualize these terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6w8-vgCUcuuEJRfTBOmTA.jpeg" /></figure><p>We’ll cover these Stripe terms more in depth throughout the tutorial, but if you’d like to read more on your own, we’d recommend taking a look at the <a href="https://stripe.com/docs/api">Stripe API docs</a>.</p><h3>2. Create a Product</h3><p>You can create a product using the Stripe API or Dashboard. Because we only need to create 1 Stripe Product, it makes more sense to use the Stripe Dashboard. (As mentioned above, we’ll be covering how to create products and plans via the API in an upcoming post.)</p><p>Navigate to your Stripe Dashboard (<a href="https://dashboard.stripe.com/">www.dashboard.stripe.com</a>). In the left sidebar, click on the <strong>“Billing”</strong> menu item to expand your options. Once expanded, click on <strong>“Products”</strong>.</p><p>Click on the <strong>“+ New”</strong> option in the subheader to create a new product.</p><p>Creating a Product is as simple as entering a name. In this case, we’ll call our Product “Simple Albums”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCAnsLn-p8srIWI6PazNnA.jpeg" /></figure><h3>3. Create a Plan</h3><p>When you create a Product in the Dashboard, Stripe automatically assumes that you want to attach a pricing Plan to that Product.</p><p>Stripe gives you numerous options when allowing you to create your pricing Plan.</p><p>In this step, we’ll first create the “Hobbyist” Plan for Simple Albums, which costs $20.00/month. For our Plan, under the Pricing option, select the <strong>“Recurring quantity”</strong> option, since we’ll be automatically billing each month.</p><p>The other option, <strong>“Metered usage”</strong>, is based on how much you use an application. The example Stripe gives of “Metered usage” is a case where you are charged for the number of API calls you make. The first real-world example I can think of is <a href="https://www.clarifai.com/pricing">Clarifai</a>, which is free for the first 5,000 operations but then costs $1.20 for the next 1000 operations.</p><p>Next, you can specify the currency. We will choose “USD”. If you’re interested in seeing all the currencies that Stripe supports, here is a list: <a href="https://stripe.com/docs/currencies">https://stripe.com/docs/currencies</a>.</p><p>Because we selected the “Recurring quantity” Pricing option, we can now select the <strong>Billing Interval</strong>. We will choose <strong>“Monthly”</strong>. Stripe gives you a lot of flexibility with the Billing Interval. If you wanted to charge $20.00/2 months, you could select “Custom” and specify the billing interval type (Month) and number (2).</p><p>Lastly, you can specify the Trial Period if you’d like. You typically want a Trial Period if you want users to enter card numbers up front but also want to give them the option to cancel before the trial period ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_ulNiVQ2qyMnaYIJ0nECQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2clFOJWcq9ox1zdutwh0Kw.jpeg" /></figure><p>Once you have created the Hobbyist Plan, feel free to create the Professional Plan, which, remember costs $50.00/month.</p><p>If you’re having trouble creating this plan, navigate back to the <strong>“Products”</strong> page (“Billing &gt; Products” from the left sidebar). Click into the “Simple Albums” Product. Under the header, you’ll see the option to <strong>“+ Add pricing plan”</strong>. Click on that option, and repeat the process outlined above to now create the Professional Plan.</p><p>Now that we’ve set up the Product and Plans, we’re ready to jump into the code!</p><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-2-66ecf510fae3">Continue on to Part 2 of this tutorial</a></p><p><em>Do you want a clear and intuitive way to keep up with your Stripe subscriptions?</em></p><p><strong><em>ProfitKit</em></strong><em> is a free calendar for your Stripe account that allows you to track expiring trials, upcoming cancellations and expected payments from your customers in a simple and effective way. Integration with Google Calendar is included in our free plan.</em></p><p><em>Sign up for free at </em><a href="https://www.profitkit.io/"><em>https://www.profitkit.io</em></a><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN-uERvnEzXEfBPnl9voBA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b940f90fc03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-nebula/creating-monthly-recurring-subscriptions-in-stripe-using-node-js-part-1-6b940f90fc03">Creating Monthly Recurring Subscriptions in Stripe using Node.js (Part 1)</a> was originally published in <a href="https://medium.com/code-nebula">Code Nebula</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Steps to Pass Parameters from a Simple Stripe Checkout Form to Your Custom HTML form]]></title>
            <link>https://medium.com/code-nebula/5-steps-to-pass-parameters-from-a-simple-stripe-checkout-form-to-your-custom-html-form-fd114d20d2bc?source=rss-457a07a72479------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd114d20d2bc</guid>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[payment-processing]]></category>
            <category><![CDATA[checkout]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Amy Sitwala]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 00:29:59 GMT</pubDate>
            <atom:updated>2019-04-04T00:12:20.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 Steps to Collect Inputs from a Stripe Checkout Form and Pass them to a Custom HTML Form</h3><p>For a fully-formatted version you can see this tutorial on our site at:</p><p><a href="https://codenebula.io/stripe/node.js/2019/04/03/5-steps-to-collect-inputs-from-a-stripe-checkout-form-and-pass-them-to-a-custom-html-form/">5 Steps to Collect Inputs from a Stripe Checkout Form and Pass them to a Custom HTML Form</a></p><p><strong>Note: </strong>This post assumes you have a working Stripe account and know how to set up a basic Node / Express server to serve HTML files and receive HTTP requests. If you don’t know how to do these things, no problem! You can still follow along but you may want to consider checking out these docs:</p><p><a href="https://docs.npmjs.com/cli/start">https://docs.npmjs.com/cli/start</a></p><p><a href="https://nodejs.org/en/docs/guides/getting-started-guide/">https://nodejs.org/en/docs/guides/getting-started-guide/</a></p><p><a href="http://expressjs.com/en/starter/hello-world.html">http://expressjs.com/en/starter/hello-world.html</a></p><h3>TLDR</h3><p>Go to <strong>Section 4 (Set up your Simple Stripe Checkout Form and Retrieve Inputted Parameters)</strong> to get a general sense of how to pass customer-inputted parameters down from your Stripe form to another form.</p><p>You can find all of the code posted here at:</p><p><a href="https://github.com/code-nebula/simple-stripe-checkout">https://github.com/code-nebula/simple-stripe-checkout</a></p><h3>Introduction</h3><p>In your journey to become a fullstack web developer, it is not long until you stumble upon the magic that is Stripe Checkout (<a href="https://stripe.com/docs/checkout">https://stripe.com/docs/checkout</a>). You see the beautiful, comprehensive form and are instantly sold on using it to handle payments on your site.</p><p>So you sit down to integrate Stripe Checkout and think, “This should be a piece of cake”. But then…a few minutes in, you start feeling overwhelmed by the loads of parameters. You start asking yourself, “Should I use the <strong><em>Simple</em> </strong>or <strong><em>Custom</em></strong> form?” You continue reading the docs and messing around with the code, but before you know it, a few hours have passed and you’re left thinking Stripe’s Checkout Form is an untouchable, black box.</p><p>To help you demystify Stripe Checkout, we’ve devised a list of 4 simple exercises:</p><ol><li>Passing parameters<strong> </strong>from the <strong>Simple</strong> Stripe Checkout form to your own HTML form (this post)</li><li>Passing parameters from the <strong>Custom</strong> Stripe Checkout form to your own HTML form</li><li>Passing parameters from your own HTML form to the <strong>Simple</strong> Stripe Checkout form</li><li>Passing parameters from your own HTML form to the <strong>Custom</strong> Stripe Checkout form</li></ol><p>This post will deal with the first exercise:</p><p>1. Passing parameters<strong> </strong>from the <strong>Simple</strong> Stripe Checkout form to your own HTML form</p><p>Not only is this a great exercise to help you deep-dive into Stripe Checkout but it is also a workflow you may want to include on your site.</p><p><strong>The video below outlines this workflow for you:</strong></p><p>A new customer visits your site and purchases a product that will be shipped to them. After the customer pays, you redirect them to a form where they can opt-in to your email newsletter in order to get updates on new posts or products. You would like to auto-fill the name and email fields of this form using the information submitted via the Simple Stripe Checkout form.</p><p><a href="https://drive.google.com/file/d/1TyqWG8Cl1GgIp9teLQ6UhRR1guiOiRsA/preview">SimpleStripeCheckout_720.mov</a></p><p>Now that you’ve gotten a preview of what you’ll be building out, let’s get started!</p><p><strong>Note:</strong> You can find all of the code mentioned in this post here:</p><p><a href="https://github.com/code-nebula/simple-stripe-checkout">https://github.com/code-nebula/simple-stripe-checkout</a></p><h3>The 5 Steps</h3><h3>1. Understand which form elements the Stripe Checkout data parameters correspond to</h3><p>Re-read the documentation under the “Simple Tab” (<a href="https://stripe.com/docs/checkout#integration">https://stripe.com/docs/checkout#integration</a>). Try to determine which parameters would be the most useful for you.</p><p>In my case, I used the following parameters:</p><pre>/* Stripe&#39;s equivalent of a public key */<br>data-key=&quot;pk_test_6pRNASCoBOKtIshFeQd4XMUh&quot;<br>data-allow-remember-me=&quot;true&quot;<br>data-billing-address=&quot;true&quot;<br>data-shipping-address=&quot;true&quot;<br>data-name=&quot;Your Website Name&quot; <br>data-description=&quot;1 Product ($25.00)&quot;<br>data-amount=&quot;2500&quot;<br>data-image=&quot;./../assets/image-placeholder-cropped.png&quot;<br>data-label=&quot;Buy this Product!&quot;<br>data-panel-label=&quot;Purchase&quot;</pre><p><strong>See the photos below to see how these parameters correspond to your Simple Stripe Checkout form:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*htSnywtlW8D2p-9PyGNe0g.png" /><figcaption>Simple Stripe Checkout Form Parameters Visualized (Part 1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJnTPfT2ebHtHZaKV4CHow.png" /><figcaption>Simple Stripe Checkout Form Parameters Visualized (Part 2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*go4cC7uWg8R7YkiaVLxw0A.png" /><figcaption>Simple Stripe Checkout Form Parameters Visualized (Part 3)</figcaption></figure><h3>2. Understand why you need server side code to process the payment and extract the inputted parameters.</h3><p>When you first stumble upon the Simple Stripe Checkout Form, it may be tempting to simply embed the script in your front-end code and assume that Stripe takes care of the rest after you provide your Stripe Publishable Key (essentially a public key).</p><p>However, the <strong>action</strong> attribute in</p><pre>&lt;form action=&quot;&quot; method=&quot;POST&quot;&gt;</pre><p>is a clear indication that some work is needed in order for this form to be successfully processed.</p><p>The “action” attribute specifies where you want to send your form data to after the form has been submitted. The most ideal use case is to send this form data back to your server to process it.</p><p>How do you do this? Well, when the Stripe Checkout Form is successfully submitted, the customer-inputted data will first hit a Stripe endpoint. Stripe will then return some of that inputted information (e.g., email) along with a token (for security reasons, Stripe does not return any payment information such as credit card number, CVC, etc.). You should then pass this token into a token handler that you have set up on your server. The token handler will process the payment via a series of steps.</p><p>If you’re coming from more of a front-end background, you might also be wondering, “Can I extract the customer-inputted values directly from the form?”</p><p>You certainly can, but we would not recommend it, as the process is very “hacky”. You <em>could</em> find the id or class name that corresponds to the inputs using HTML DOM methods or jQuery:</p><p>$(‘input#email.control’)[0].value -&gt; Grab the user’s email</p><p>$(‘.telInput input.control’)[0].value -&gt; Grab the user’s phone number from the “Remember Me” section</p><p>However, there are <strong>2 major issues</strong> with this approach:</p><ol><li>Stripe at any point might decide to change the class name of the input elements, which would cause your logic to instantly break (note that you can’t lock down the version of Stripe Checkout that you use — Stripe automatically rolls out changes to <a href="https://checkout.stripe.com/checkout.js">https://checkout.stripe.com/checkout.js</a>)</li><li>You would need to know exactly <strong>when</strong> to look for the elements in order to grab the final user-inputted value. Note that not all of the form elements are always mounted to the DOM. The elements change depending on which screen you’re looking at on the form — for instance, you would have to collect the email information on the first screen when the “Payment Info” button is clicked. Here’s the tricky part…to do so, you first need to watch for when the “Payment Info” button is mounted to the DOM. The code to do this becomes very messy, very quickly, and it’s obvious that Stripe doesn’t want you to take this approach.</li></ol><p>So what <strong><em>should </em></strong>you do? Well, once the form is submitted, Stripe does in fact return some of the customer-parameters (email, shipping address information, etc.). It is much simpler and robust to use what is returned from the form submission.</p><h3>3. Set up Your Application Server and Your Workspace</h3><p>First, open up your terminal and create a new Express app. As mentioned above, if you are not familiar with Express, no worries — the Express site has some easy-to-follow documentation here: (<a href="http://expressjs.com/en/starter/installing.html">http://expressjs.com/en/starter/installing.html</a>)</p><p>Next, install the following packages using your favorite package manager (npm, yarn, etc.):</p><ul><li><strong>body-parser </strong>(<a href="https://www.npmjs.com/package/body-parser">https://www.npmjs.com/package/body-parser</a>)</li><li><strong>nunjucks </strong>(<a href="https://www.npmjs.com/package/nunjucks">https://www.npmjs.com/package/nunjucks</a>)</li></ul><p>We will use the <strong>body-parser </strong>package to parse incoming request bodies as “req.body” in our server-side code. We will use <strong>nunjucks </strong>for templating and passing data into our HTML files.</p><p>Next, set up your workspace to follow a similar format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*e0H8clxuXCUN_a3bKq51wg.png" /><figcaption>What your workspace should look like</figcaption></figure><p>Here’s an explanation of the important directories and files:</p><ul><li><strong>assets</strong> (Where you will place your image or media files — think images for your product)</li><li><strong>node_modules</strong> (Holds your installed dependencies)</li><li><strong>styles</strong> (Where you will place your CSS files)</li><li><strong>views</strong> (Where you will place your templates — your HTML files)</li><li><strong>app.js</strong> (Where you will place all of the logic for your application)</li><li><strong>package.json</strong> (Holds information about your app, including which dependencies you are using, etc.)</li></ul><h3>assets</h3><ul><li><strong>image-placeholder.png</strong> (the image of your product)</li><li><strong>image-placeholder-cropped.png</strong> (the thumbnail of your product — this is included in the Stripe Checkout form)</li></ul><h3>styles</h3><ul><li><strong>app.css</strong> (the stylesheet for your entire application)</li></ul><pre>body {<br>    font-family: &quot;Open Sans&quot;, &quot;Helvetica&quot;, sans-serif;<br>    margin: 0; <br>    padding: 0;<br>    width: 100%;<br>}</pre><pre>.app-container {<br>    margin: 0 auto;<br>    margin-top: 48px;<br>    text-align: center;<br>    width: 100%;<br>}</pre><pre>/* Index CSS */<br>.image-container {<br>    margin-bottom: 16px;<br>    width: 100%;<br>}</pre><pre>.image-placeholder {<br>    display: block;<br>    margin: 0 auto;<br>    width: 300px;<br>    height: 400px;<br>}</pre><pre>/* Custom Form CSS */<br>hr {<br>    border: none;<br>    border-top: 1px solid #ddd;<br>    width: 75%;<br>}</pre><pre>label {<br>    display: block;<br>    font-weight: bold;<br>}</pre><pre>.signup-form {<br>    background-color: #eee;<br>    border-radius: 6px;<br>    margin: 24px auto 0;<br>    padding: 24px;<br>    width: 400px;<br>}</pre><pre>.signup-field {<br>    display: block;<br>}</pre><pre>.signup-text {<br>    border: none;<br>    border-radius: 4px;<br>    font-size: 16px;<br>    font-family: &quot;Open Sans&quot;, &quot;Helvetica&quot;, sans-serif;<br>    margin: 4px 0 12px;<br>    padding: 12px;<br>    text-align: center;<br>}</pre><pre>.signup-button {<br>    background-color: #112d4e; /* dark blue */<br>    border-radius: 4px;<br>    color: #fff;<br>    font-family: &quot;Open Sans&quot;, &quot;Helvetica&quot;, sans-serif;<br>    font-size: 14px;<br>    padding: 12px;<br>}</pre><h3>views</h3><ul><li><strong>base.html</strong> (Uses Nunjucks to set up a template for your other HTML files)</li></ul><pre>&lt;!DOCTYPE html&gt;<br>    &lt;html&gt;<br>    &lt;head&gt;<br>        &lt;title&gt;Stripe Made Easy | {{ title }}&lt;/title&gt;<br>        &lt;link href=&quot;https://fonts.googleapis.com/css?family=Open+Sans&quot; rel=&quot;stylesheet&quot;&gt;<br>        &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;/styles/app.css&quot;&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;app-container&quot;&gt;<br>            {% block content %}<br>            {% endblock %}<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><ul><li><strong>index.html</strong> (<em>We will revisit later</em> — will be the homepage featuring the product)</li><li><strong>productConfirmation.html</strong> (<em>We will revisit later</em> — includes confirmation of your received order and features your own native form to prompt the user to sign up for your newsletter)</li><li><strong>newsletterConfirmation.html </strong>(<em>We will revisit later</em> — includes confirmation that the user signed up for your newsletter)</li></ul><h3>app.js</h3><p>Here we officially set up an Express application and import all necessary dependencies like <strong>body-parser</strong> and <strong>nunjucks</strong>.</p><p>Here’s a summary of what you will do in this file:</p><ul><li>Set the server to listen on port 3000</li><li>Set up Nunjucks with Express to serve up and render HTML files</li><li>Set up the content in the <strong>/assets</strong> and <strong>/styles</strong> directories to be served up through the Express app</li><li>Set up our Express router to route client requests to different pages</li><li>Set up our Express app to start a server and listen for connections on the specified port</li></ul><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;);<br>const nunjucks = require(&#39;nunjucks&#39;);</pre><pre>const app = express();<br>const port = 3000;<br>const router = express.Router();<br>const path = require(&#39;path&#39;);</pre><pre>/* Set up Express to serve HTML files using &quot;res.render&quot; with help of Nunjucks */<br>app.set(&#39;view engine&#39;, &#39;html&#39;);<br>app.engine(&#39;html&#39;, nunjucks.render);<br>nunjucks.configure(&#39;views&#39;, { noCache: true });</pre><pre>app.use(express.static(__dirname));<br>app.use(&#39;/assets&#39;, express.static(&#39;assets&#39;))<br>app.use(&#39;/styles&#39;, express.static(&#39;styles&#39;));<br>app.use(bodyParser());<br>app.use(&#39;/&#39;, router)</pre><pre>/* Place all routes here */<br>router.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.render(&#39;index.html&#39;)<br>});</pre><pre>/* Start listening on specified port */<br>app.listen(port, () =&gt; {<br>    console.info(&#39;Example app listening on port&#39;, port)<br>});</pre><h3>package.json</h3><p>An important piece of logic you need in your package.json file is the “start” script (see “scripts” -&gt; “start”). The command npm run start will run node app.js to make your Express application start a server (basically this command will execute all of the logic specified in your <strong>app.js</strong> file)</p><pre>{<br>  &quot;name&quot;: &quot;stripe-checkout&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node app.js&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;^1.18.3&quot;,<br>    &quot;express&quot;: &quot;^4.16.3&quot;,<br>    &quot;nunjucks&quot;: &quot;^3.1.3&quot;<br>  }<br>}</pre><h3>4. Set up your Simple Stripe Checkout Form and Retrieve Inputted Parameters</h3><p>We will first extend our <strong>index.html</strong> file using the base template provided in <strong>base.html</strong>. All content will be contained in a div containing the class app-container.</p><p>Set up your <strong>index.html </strong>to look like the following:</p><pre>{% set title = &#39;Stripe Checkout Form Setup&#39; %}<br>{% extends &#39;base.html&#39; %}</pre><pre>{% block content %}<br>    &lt;h2&gt;Passing parameters from Stripe Checkout Form&lt;/h2&gt;<br>    &lt;div class=&quot;image-container&quot;&gt;<br>        &lt;img class=&quot;image-placeholder&quot; src=&quot;./../assets/image-placeholder.png&quot;/&gt;<br>        &lt;p&gt;$25.00&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;form action=&quot;/charge&quot; method=&quot;POST&quot;&gt;<br>        &lt;script<br>            src=&quot;https://checkout.stripe.com/checkout.js&quot;<br>            class=&quot;stripe-button&quot;<br>            data-key=&quot;pk_test_6pRNASCoBOKtIshFeQd4XMUh&quot;<br>            data-allow-remember-me=&quot;true&quot;<br>            data-billing-address=&quot;true&quot;<br>            data-shipping-address=&quot;true&quot;<br>            data-name=&quot;Your Website Name&quot;<br>            data-description=&quot;1 Product ($25.00)&quot;<br>            data-amount=&quot;2500&quot;<br>            data-image=&quot;./../assets/image-placeholder-cropped.png&quot;<br>            data-label=&quot;Buy this Product!&quot;<br>            data-panel-label=&quot;Purchase&quot;<br>            &gt;<br>        &lt;/script&gt;<br>    &lt;/form&gt;<br>{% endblock %}</pre><p>We will be using the test key that Stripe provides by default, though you should eventually get your own Stripe Test Key for development and Stripe Publishable Key for production.</p><p>Notice that we specified the form action to go to the <strong>/charge</strong> route. What this means is that when the form is successfully submitted, all data returned from the form will be posted to the <strong>/charge</strong> route on the server.</p><p>Now, let’s make sure we set that route up! Navigate to <strong>app.js</strong> under the /* Place all routes here */ comment. Add the following:</p><pre>router.post(&#39;/charge&#39;, (req, res) =&gt; {<br>    /* 1. Have a handler here to process &quot;req.body.stripeToken&quot; to complete payment<br>     * 2. Store email, billing address, or shipping address (follow various compliance rules -- GDPR, PCI, etc.) <br>     */</pre><pre>/* Example: <br>        req.body = { <br>            stripeToken: &#39;tok_1DDe1f2eZvKYlo2C3JanAVvx&#39;,<br>            stripeTokenType: &#39;card&#39;,<br>            stripeEmail: &#39;user@example.com&#39;,<br>            stripeBillingName: &#39;Jane Doe&#39;,<br>            stripeBillingAddressCountry: &#39;United States&#39;,<br>            stripeBillingAddressCountryCode: &#39;US&#39;,<br>            stripeBillingAddressZip: &#39;95104&#39;,<br>            stripeBillingAddressLine1: &#39;1 Infinite Loop&#39;,<br>            stripeBillingAddressCity: &#39;Cupertino&#39;,<br>            stripeBillingAddressState: &#39;CA&#39;,<br>            stripeShippingName: &#39;Jane Doe&#39;,<br>            stripeShippingAddressCountry: &#39;United States&#39;,<br>            stripeShippingAddressCountryCode: &#39;US&#39;,<br>            stripeShippingAddressZip: &#39;95104&#39;,<br>            stripeShippingAddressLine1: &#39;1 Infinite Loop&#39;,<br>            stripeShippingAddressCity: &#39;Cupertino&#39;,<br>            stripeShippingAddressState: &#39;CA&#39; <br>        }<br>    */</pre><pre>/* 3. Pass relevant data to another page */<br>    var data = {<br>        email: req.body.stripeEmail,<br>        name: req.body.stripeBillingName<br>    };<br>    res.render(&#39;productConfirmation&#39;, data);<br>});</pre><p>The form data will first hit a Stripe endpoint. Stripe will then return a token, the user’s shipping address, the user’s billing address, and the user’s email. <strong><em>Note that at this time, Stripe does not return the phone number entered under the “Remember Me” section.</em></strong></p><p>So what does the code above actually do?</p><p><strong>Step 1</strong></p><p>As mentioned before, to actually process this payment, you will need to set up a Stripe token handler that deals with the token that Stripe passes back to you.</p><p><strong>Step 2</strong></p><p>This code snippet gives you an idea of what is returned by Stripe via req.body. In this step, you can process that information however you like — maybe you want to store some of that information in your own user database.</p><p><strong>Step 3</strong></p><p>This is where you take the returned user information and pass it down to your own HTML form so that the user doesn’t need to enter their personal information repeatedly.</p><p>Basically what you’re doing is passing the returned data, namely the user’s name from the billing address and the user’s email, and passing it down to another page, namely the <strong>productConfirmation.html</strong> page.</p><h3>5. Pass down the Retrieved Parameters to Your Own Form</h3><p>Set up your <strong>productConfirmation.html</strong> file to look like:</p><pre>{% set title = &#39;Custom Form&#39; %}<br>{% extends &#39;base.html&#39; %}</pre><pre>{% block content %}</pre><pre>&lt;h2&gt;Your Order Has Been Received!&lt;/h2&gt;<br>&lt;p&gt;Once your product has been delivered, we will notify you via email.&lt;/p&gt;</pre><pre>&lt;hr&gt;</pre><pre>&lt;div class=&quot;signup-form&quot;&gt;<br>    &lt;form action=&quot;/newsletterSignup&quot; method=&quot;POST&quot;&gt;<br>        &lt;div class=&quot;signup-field&quot;&gt;<br>            &lt;label&gt;Name&lt;/label&gt;<br>            &lt;input class=&quot;signup-text&quot; placeholder=&quot;Your Name&quot; name=&quot;name&quot; value=&quot;{{ name }}&quot;/&gt;<br>        &lt;/div&gt;<br>    <br>        &lt;div class=&quot;signup-field&quot;&gt;<br>            &lt;label&gt;Email&lt;/label&gt;<br>            &lt;input class=&quot;signup-text&quot; placeholder=&quot;Email&quot; name=&quot;email&quot; value=&quot;{{ email }}&quot; /&gt;<br>        &lt;/div&gt;<br>        <br>        &lt;div class=&quot;signup-field&quot;&gt;<br>            &lt;input class=&quot;signup-button&quot; type=&quot;submit&quot; value=&quot;Sign up for our weekly newsletter!&quot;&gt;<br>        &lt;/div&gt;<br>    &lt;/form&gt;<br>&lt;/div&gt;</pre><pre>{% endblock %}</pre><p>Here, we are passing down the user’s name via {{ name }} and user&#39;s email via {{ email }} and rendering them in our own newsletter signup form. The user has the option to change those inputs if they decide they actually want to use another name or email.</p><p>Notice that we specified the form action to go to the <strong>/newsletterSignup</strong> route. What this means is that when the form is successfully submitted, all data returned from the form (the user’s name and email) will be posted to the <strong>/newsletterSignup</strong> route on the server.</p><p>Let’s set that route up next!</p><p>Once again, navigate to <strong>app.js</strong> under the /* Place all routes here */ comment. Add the following route method:</p><pre>router.post(&#39;/newsletterSignup&#39;, (req, res) =&gt; {<br>    /* 1. Save this information to database: <br>     * req.body.email<br>     * req.body.name<br>     */<br>    <br>    /* 2. Pass relevant data to another page */<br>    var data = {<br>        name: req.body.name<br>    };<br>    res.render(&#39;newsletterConfirmation&#39;, data);<br>});</pre><p>This code is fairly self explanatory, but to be thorough:</p><p><strong>Step 1</strong></p><p>The form will post the user’s name and email via req.body.name and req.body.email, respectively. You can take that information and pass it into a handler that adds the user to your mailing list.</p><p><strong>Step 2</strong></p><p>To get into the habit of passing information down to your HTML files, we will pass down the user’s name to the <strong>newsletterConfirmation.html</strong> file, which looks like</p><pre>{% set title = &#39;Sign Up Success&#39; %}<br>{% extends &#39;base.html&#39; %}</pre><pre>{% block content %}<br>&lt;div&gt;<br>    &lt;h2&gt;Congrats, {{ name }}!&lt;/h2&gt;<br>    &lt;p&gt;You&#39;ve signed up for our email newsletter. Check your inbox for updates!&lt;/p&gt;<br>&lt;/div&gt;</pre><pre>{% endblock %}</pre><p>This file extends <strong>base.html</strong> and displays the user’s name inputted from the newsletter signup form.</p><p>And that’s basically it — congrats on getting this far! Go out there and utilize the full power of Simple Stripe Checkout!</p><p>Please leave a comment if you have any questions — we’re more than happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd114d20d2bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-nebula/5-steps-to-pass-parameters-from-a-simple-stripe-checkout-form-to-your-custom-html-form-fd114d20d2bc">5 Steps to Pass Parameters from a Simple Stripe Checkout Form to Your Custom HTML form</a> was originally published in <a href="https://medium.com/code-nebula">Code Nebula</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>