<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Shaurya Pethe</title>
    <description>The latest articles on DEV Community by Shaurya Pethe (@rshaurya).</description>
    <link>https://dev.to/rshaurya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3919178%2F1f229d23-b0f2-4035-8482-3d2851470d46.png</url>
      <title>DEV Community: Shaurya Pethe</title>
      <link>https://dev.to/rshaurya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rshaurya"/>
    <language>en</language>
    <item>
      <title>Integrating Stripe into a Legacy Codebase: What I Learned About Payments</title>
      <dc:creator>Shaurya Pethe</dc:creator>
      <pubDate>Thu, 19 Nov 2026 03:14:49 +0000</pubDate>
      <link>https://dev.to/rshaurya/integrating-stripe-into-a-legacy-codebase-what-i-learned-about-payments-f7</link>
      <guid>https://dev.to/rshaurya/integrating-stripe-into-a-legacy-codebase-what-i-learned-about-payments-f7</guid>
      <description>&lt;p&gt;I recently finished integrating Stripe into a legacy codebase with a FastAPI backend and a TypeScript frontend. I went in thinking it would be "just an API call". It turned out to be a lesson in system design, security, and how money actually moves between banks.&lt;/p&gt;

&lt;p&gt;This blog covers how card payments works, how a payment gateway fits in, the difference between Stripe's Payment Intents and Checkout Sessions, hosted vs custom UI, webhooks, and a handful of things that will bite you if nobody warns you first.&lt;/p&gt;

&lt;h2&gt;
  
  
  How card payments actually work
&lt;/h2&gt;

&lt;p&gt;Before touching any API, it helps to know who is involved when a customer pays by card:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Cardholder: the customer.&lt;/li&gt;
&lt;li&gt;Merchant: the busines selling something.&lt;/li&gt;
&lt;li&gt;Payment gateway: the service that securely captures payment details from the customer and transmits them onward.&lt;/li&gt;
&lt;li&gt;Payment processor: the company that routes the transaction to the card networks and banks.&lt;/li&gt;
&lt;li&gt;Acquiring bank (acquirer): the merchant's bank, which receives the money on the merchant's behalf.&lt;/li&gt;
&lt;li&gt;Card network: Visa, Mastercard, RuPay, and so on. They carry messages between the acquirer and the issuer.&lt;/li&gt;
&lt;li&gt;Issuing bank (issuer): the customer's bank, which decides whether to approve the payment.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A single card payment has 4 stages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Authorization - The issuer checks that the card is valid, if there are sufficient funds, and that the transaction does not look fraudulent. If everything checks out, it places a hold on those funds and sends back an approval. No money has moved yet.&lt;/li&gt;
&lt;li&gt;Capture - The merchant confirms it wants the held funds.&lt;/li&gt;
&lt;li&gt;Clearing - The card network and banks reconcile the transaction details&lt;/li&gt;
&lt;li&gt;Settlement - The money is transferred from the issuer to the acquirer, and then paid out to the merchant, usually after a delay of a few days.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Stripe is technically a &lt;strong&gt;payment service provider (PSP)&lt;/strong&gt;. It bundles the gateway, processor connections, the merchant account, fraud detection, and payouts into one product.&lt;/p&gt;

&lt;h2&gt;
  
  
  What a payment gateway does
&lt;/h2&gt;

&lt;p&gt;A payment gateway sits between an application and the bank. It is usually responsible for&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Collecting payment details securely.&lt;/li&gt;
&lt;li&gt;Tokenization: tokens or IDs are the only thing that are stored in the system, not raw card details.&lt;/li&gt;
&lt;li&gt;Encryption during transmission of card details.&lt;/li&gt;
&lt;li&gt;Authentication: Sometimes an extra verifciation step where the customer confirms the payment with their bank, for example via an OTP.&lt;/li&gt;
&lt;li&gt;Fraud detection: Stripe Radar, for example, scores each payment for risk.&lt;/li&gt;
&lt;li&gt;Returning the status of the payment.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You technically could talk to banks directly. In practice, almost nobody should. The advantages of a gateway:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reduced PCI DSS scope. PCI DSS is the security standard for anyone who handles card data. If card numbers are stored on your application's servers, you take on a heavy compliance burden. With a gateway's hosted fields or hosted page, the card data goes straight to the gateway, and your compliance obligations shrink considerably.&lt;/li&gt;
&lt;li&gt;Many payment methods, one integration. Cards, wallets, bank debits, UPI, and others can often be enabled without a separate integration for each.&lt;/li&gt;
&lt;li&gt;Authentication flows, retries, currency handling, refunds, disputes (chargebacks), and receipts are all provided.&lt;/li&gt;
&lt;li&gt;Dashboards, test mode, logs, event history, and reporting are included.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  General Architecture of gateway integration
&lt;/h2&gt;

&lt;p&gt;Most modern integrations look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight markdown"&gt;&lt;code&gt;Browser (TypeScript)         Your backend (FastAPI)         Stripe
      |                              |                        |
      |-- 1. "I want to pay" -------&amp;gt;|                        |
      |                              |-- 2. Create payment --&amp;gt;|
      |                              |&amp;lt;-- 3. client_secret ---|
      |&amp;lt;-- 4. client_secret ---------|                        |
      |                                                       |
      |-- 5. Card details go DIRECTLY to Stripe -------------&amp;gt;|
      |&amp;lt;-- 6. Result (success / needs action / failure) ------|
      |                                                       |
      |                              |&amp;lt;-- 7. Webhook event ---|
      |                              |-- 8. Mark order paid   |
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some important ideas here are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The backend decides the price. The frontend never tells the server how much to charge. The server looks up the order and computes the amount itself. Otherwise anyone with browser dev tools can change the price to 1 rupee.&lt;/li&gt;
&lt;li&gt;Sensitive data bypasses your servers. Card details go from the browser straight to Stripe.&lt;/li&gt;
&lt;li&gt;Secrets stay on the server. The secret key never appears in frontend code. The frontend only gets a publishable key, which is designed to be public.&lt;/li&gt;
&lt;li&gt;The source of truth for "was this paid?" is the webhook, not the browser. More on this shortly.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Payment Intents vs Checkout Sessions
&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;PaymentIntent&lt;/code&gt; represents your intention to collect a specific amount from a customer, and it tracks that payment through its entire lifecycle. You create one on your server, hand its &lt;code&gt;client_secret&lt;/code&gt; to the frontend, and the frontend uses it to confirm the payment.&lt;br&gt;
A &lt;code&gt;PaymentIntent&lt;/code&gt; moves through statuses such as:&lt;br&gt;
• &lt;code&gt;requires_payment_method&lt;/code&gt;: created, but no payment details attached yet.&lt;br&gt;
• &lt;code&gt;requires_confirmation&lt;/code&gt;: details attached, waiting to be confirmed.&lt;br&gt;
• &lt;code&gt;requires_action&lt;/code&gt;: the customer must do something, for example complete 3D Secure.&lt;br&gt;
• &lt;code&gt;processing&lt;/code&gt;: submitted, awaiting a result (common with bank debits).&lt;br&gt;
• &lt;code&gt;requires_capture&lt;/code&gt;: authorized, but you chose to capture later.&lt;br&gt;
• &lt;code&gt;succeeded&lt;/code&gt;: the payment went through.&lt;br&gt;
• &lt;code&gt;canceled&lt;/code&gt;: you or Stripe canceled it.&lt;br&gt;
The &lt;code&gt;PaymentIntent&lt;/code&gt; is the lower-level building block. It gives you full control, but you are responsible for the surrounding pieces: the checkout UI, cart and line items, tax logic, success and failure handling, and so on.&lt;/p&gt;

&lt;p&gt;A Checkout Session is a higher-level object that represents an entire checkout experience. You describe what the customer is buying (line items, currency, success and cancel URLs), and Stripe provides the payment page, collects the details, handles authentication, and shows the result. Under the hood, a Checkout Session in payment mode creates and manages a PaymentIntent for you. It can also handle things like subscriptions, promotion codes, shipping address collection, and tax calculation, depending on how sessions are configured.&lt;/p&gt;

&lt;p&gt;Which one to use depends on your usecase and business requirements. Generally, Checkout Sessions are used unless there's need for more granular control.&lt;/p&gt;
&lt;h2&gt;
  
  
  Hosted Page UI vs Custom UI
&lt;/h2&gt;

&lt;p&gt;When defining a checkoutSession or PaymentIntent, you can choose from a bunch of &lt;code&gt;ui_mode&lt;/code&gt;s:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ui_mode="hosted_page"&lt;/code&gt;&lt;br&gt;
The customer is redirected to a page on Stripe's domain, pays there, and is redirected back to your site.&lt;/p&gt;

&lt;p&gt;Pros&lt;br&gt;
• Fastest to build and the smallest security surface.&lt;br&gt;
• Stripe maintains the page: new payment methods, localization, accessibility, and compliance updates arrive without you changing code.&lt;br&gt;
• Well tested across devices.&lt;br&gt;
Cons&lt;br&gt;
• Limited visual customization (logo, colors, and some layout options).&lt;br&gt;
• The customer leaves your site, which some brands do not want.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ui_mode="embedded_page&lt;/code&gt;&lt;br&gt;
Displays the Checkout Session as an embedded container directly on your website without redirecting away&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ui_mode="elements"&lt;/code&gt;&lt;br&gt;
You render the payment form inside your own page using Stripe.js and Stripe Elements (such as the Payment Element). The form fields are iframes served by Stripe, so card data still never touches your servers, but they sit inside your page and design.&lt;br&gt;
Pros&lt;br&gt;
• Full control of layout and user experience.&lt;br&gt;
• The customer never leaves your site.&lt;br&gt;
Cons&lt;br&gt;
• More frontend code to write and maintain.&lt;br&gt;
• You must handle the states yourself: loading, validation errors, declined cards, authentication redirects.&lt;/p&gt;
&lt;h2&gt;
  
  
  Webhooks
&lt;/h2&gt;

&lt;p&gt;After the customer pays, Stripe redirects them back to the success page as defined. Can you mark the order as paid after this? No. The browser redirect is not reliable.&lt;br&gt;&lt;br&gt;
The customer may close the tab right after paying, or their network may drop before the redirect completes, or the payment result (success or fail) may arrive minutes later, or a malicious user can simply visit a success URL without paying.  &lt;/p&gt;

&lt;p&gt;Webhooks fix this by flipping the direction of communication. Instead of the application asking Stripe for the status of a payment, Stripe sends a response to the application server when an action(payment) is triggered.&lt;/p&gt;
&lt;h3&gt;
  
  
  How they work?
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;In the Stripe dashboard (or Stripe CLI for local development), you register an endpoint URL, for example &lt;code&gt;https://yourapp.com/stripe-webhook&lt;/code&gt; (or &lt;code&gt;stripe listen --all-snapshot --forward-to localhost:8001/api/v1/payments/stripe-webhook&lt;/code&gt; using Stripe CLI), and choose which event types to receive.&lt;/li&gt;
&lt;li&gt;When an event is triggered, Stripe sends an HTTP &lt;code&gt;POST&lt;/code&gt; request to that URL. The body is JSON describing an Event objectm with a &lt;code&gt;type&lt;/code&gt; (like &lt;code&gt;checkout.session.completed&lt;/code&gt;) and the relevant data.&lt;/li&gt;
&lt;li&gt;The application's backend server verifies if the request really came from Stripe (signature verification), processes the event, and returns a &lt;code&gt;200&lt;/code&gt; status code.&lt;/li&gt;
&lt;li&gt;If the server does not respond with success, Stripe retries with backoff. In live mode, retries continue for up to three days.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Verifying the signature
&lt;/h3&gt;

&lt;p&gt;Since the endpoint is a public URL, anyone could send fake requests to it. Stripe includes a &lt;code&gt;Stripe-Signature&lt;/code&gt; header containing a timestamp and an HMAC-SHA256 signature computed with a webhook signing secret. Application's server recomputes the signature over the raw request body and compares.&lt;br&gt;
Note: signature verification must use the exact raw bytes of the body. If a framework parses and re-serializes the JSON before verification, the signature will not match. In FastAPI, read the raw body with &lt;code&gt;await request.body()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Events I found useful for one-time payments:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;checkout.session.completed&lt;/code&gt; (if using Checkout)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;payment_intent.succeeded&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;payment_intent.payment.failed&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;charge.refunded&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  The Code
&lt;/h2&gt;

&lt;p&gt;The webhook endpoint in FastAPI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;stripe&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;api_key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stripe_api_key&lt;/span&gt;
&lt;span class="no"&gt;STRIPE_WEBHOOK_SECRET&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stripe_webhook_secret&lt;/span&gt;

&lt;span class="nd"&gt;@router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/stripe-webhook"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;stripe_webhook&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Session&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Depends&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;get_db&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stripe_signature&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;payload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;body&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;stripe&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Webhook&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;construct_event&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sig_header&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;stripe_signature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;secret&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;STRIPE_WEBHOOK_SECRET&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;ValueError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Invalid payload&lt;/span&gt;
        &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;HTTPException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;detail&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Invalid payload"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;stripe&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SignatureVerificationError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Invalid signature&lt;/span&gt;
        &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;HTTPException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;detail&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Invalid signature"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;event_type&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;data_object&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"data"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"object"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;event_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"checkout.session.completed"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Handle completed checkout session (e.g., fulfill order, update database)&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Checkout session completed for session ID: {data_object['id']}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;event_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"payment_intent.succeeded"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Handle successful payment intent&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Payment intent succeeded: {data_object['id']} for amount"&lt;/span&gt;
            &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;" {data_object['amount']}"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;event_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"payment_intent.payment_failed"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Handle failed payment&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Payment failed: {data_object['id']}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Unhandled event type: {event_type}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;JSONResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"success"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sample Checkout session implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Stripe demands integers in sub-units (cents), so define a function format_stripe_amount() to handle this.&lt;/span&gt;
&lt;span class="n"&gt;stripe_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;format_stripe_amount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;charge_amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;currency&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;session&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;stripe&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;checkout&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Session&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;mode&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"payment"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;line_items&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;# used only necessary data here. refer to official stripe documentation to see &lt;/span&gt;
        &lt;span class="s2"&gt;"price_data"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;currency&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"product_data"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Wallet Topup - {amount} INR"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"unit_amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;stripe_amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"quantity"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;success_url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{redirect_url}&amp;amp;session_id={{CHECKOUT_SESSION_ID}}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;cancel_url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{origin}/checkout/cancelled"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;metadata&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"kind"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"wallet_topup"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;actor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;subject_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"credit_amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"charge_amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;charge_amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"transaction_fee"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;currency&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;stripe&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;StripeError&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Stripe wallet session creation failed: {e}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;HTTPException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;HTTP_400_BAD_REQUEST&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;detail&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Other Things worth knowing
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Stripe provides separate test keys and test card numbers (such as 4242 4242 4242 4242) so you can simulate successes, declines, and authentication challenges without real money. Stripe also provides test cards for 3D Secure and various failure scenarios.&lt;/li&gt;
&lt;li&gt;Test webhooks locally with the Stripe CLI. Running &lt;code&gt;stripe listen --forward-to localhost:8000/stripe-webhook/&lt;/code&gt; forwards events to your local server and prints a temporary signing secret to use in development. You can also trigger sample events with &lt;code&gt;stripe trigger&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Amounts are integers in the smallest currency unit. 499 rupees is 49900 paise. Never use floating-point numbers for money anywhere in your system.&lt;/li&gt;
&lt;li&gt;Idempotency keys protect against double charges. If a network timeout makes you retry a request, an idempotency key tells Stripe that this is the same operation.&lt;/li&gt;
&lt;li&gt;Publishable keys go in the frontend. Secret keys stay server-side in environment variables or a secrets manager and never get committed to Git. Restricted keys let you limit what a key can do. Webhook signing secrets are separate again, one per endpoint.&lt;/li&gt;
&lt;li&gt;Store Stripe's IDs. Save the PaymentIntent ID, Checkout Session ID, and customer ID against your own orders. When something goes wrong, those IDs are how you connect your database to the Stripe dashboard.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>backend</category>
      <category>python</category>
      <category>typescript</category>
      <category>stripe</category>
    </item>
    <item>
      <title>Neural Networks: A Broad Overview</title>
      <dc:creator>Shaurya Pethe</dc:creator>
      <pubDate>Tue, 12 May 2026 14:17:20 +0000</pubDate>
      <link>https://dev.to/rshaurya/neural-networks-a-broad-overview-340p</link>
      <guid>https://dev.to/rshaurya/neural-networks-a-broad-overview-340p</guid>
      <description>&lt;p&gt;Before we start, this blog is for people who have somewhat heard the terms involved with neural networks. This gives an extremely high overview of a few concepts, helpful for building intuition. &lt;/p&gt;

&lt;h2&gt;
  
  
  Neural Networks - easily explained
&lt;/h2&gt;

&lt;p&gt;Neural Networks are essentially used to fit a curve to some set of data points. That's it. Atleast that's how much I know. Theoretically, by this definition, you can fit any sort of data using a neural network.&lt;/p&gt;

&lt;p&gt;A standard Neural Network is just a series of nested functions. Data flows strictly in one direction, from input to output. Each layer takes the data, multiplies it by its Weights (which determine the strength of a connection), adds a Bias (which shifts the activation function), and hands it directly to the next neuron. The output of the activation function from the first layer becomes the input for the second layer. This sequential processing allows the network to build hierarchal representations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bias Variance Tradeoff
&lt;/h2&gt;

&lt;p&gt;Every neural network architecture embodies a fundamental tension between bias and variance:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;High bias (underfitting)&lt;/strong&gt; occurs when your network lacks the capacity to capture the underlying data patterns. Basically, the network fails to capture the underlying pattern or "meaning" of the data. A network that's too shallow or too constrained produces consistently wrong predictions across both training and test data. The model's assumptions are too rigid.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;High variance (overfitting)&lt;/strong&gt; emerges when your network is too complex. It memorizes training data, including the noise, rather than learning generalizable patterns..Deep networks with millions of parameters can achieve near- zero training error while failing catastrophically on unseen data. The model is too flexible, capturing noise as signal. The tradeoff is unavoidable: reducing bias typically increases variance and vice versa.&lt;/p&gt;

&lt;p&gt;Engineering a neural network is a constant balancing act between building a model expressive enough to learn the data, but constrained enough to generalize to the real world.&lt;/p&gt;

&lt;h2&gt;
  
  
  Weights and Biases: The Learnable Parameters
&lt;/h2&gt;

&lt;p&gt;Neural networks learn through two types of parameters:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Weights (W)&lt;/strong&gt; define the strength and sign of connections between neurons. In a fully connected layer, the weight matrix transforms input vectors into new representational spaces. Each weight determines how much influence one neuron has on another—positive weights amplify signals, negative weights inhibit them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Biases (b)&lt;/strong&gt; provide translation invariance, shifting activation thresholds independently of input magnitude. Without biases, neurons can only learn transformations passing through the origin— a severe limitation. The bias term allows: output = W·x + b , enabling the network to learn arbitrary decision boundaries. Together, these parameters define the network's hypothesis space. A network with L layers, each containing n neurons, can have millions of parameters—each one adjusted during training to minimize loss.&lt;/p&gt;

&lt;h2&gt;
  
  
  Activation Functions
&lt;/h2&gt;

&lt;p&gt;Activation functions are the crucial non-linear components that make deep learning possible. Without them, stacking multiple layers would collapse into a single linear transformation— rendering depth meaningless. Without activation functions, a neural network is just a series of linear matrix multiplications. No matter how many layers you stack, it collapses into a single linear transformation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ReLU (Rectified Linear Unit)&lt;/strong&gt; is the industry standard for hidden layers. Its math is simple: &lt;br&gt;
&lt;code&gt;f(x) = max(0, x)&lt;/code&gt; &lt;br&gt;
If the input is positive, it passes it through. If it is negative, it outputs zero. This introduces the non-linearity required to learn complex shapes, while remaining computationally cheap and helping to mitigate the vanishing gradient problem that plagued earlier functions like Sigmoid.&lt;/p&gt;

&lt;p&gt;Why ReLU? It is easier to compute as compared to exponential functions. And it has a constant gradient of 1 for positive inputs which prevents gradients from vanishing. There are some edge cases though. It is also called as the "Dying ReLU" problem where neurons which get input less than zero get stuck at zero due to the nature of the ReLU function. This causes a lot of neurons to "die" or go to a "dead" state, effectively decreasing the accuracy of the neural network. This is overcome by adding a very small slope for all negative inputs, so that the gradient is non-zero. This keeps a steady flow of gradients.&lt;/p&gt;

&lt;h2&gt;
  
  
  Loss Function
&lt;/h2&gt;

&lt;p&gt;Loss functions are used to find out how wrong our model is after training. Like activation functions, there are many loss functions.&lt;/p&gt;

&lt;p&gt;For regression tasks, we often use the &lt;strong&gt;Residual Sum of Squares (RSS)&lt;/strong&gt;, or &lt;strong&gt;Sum of Squared Errors&lt;/strong&gt;. The formula is:&lt;/p&gt;

&lt;p&gt;RSS = \sum_{i=1}^{n} (y_i - \hat{y}_i)^2&lt;/p&gt;

&lt;p&gt;Where &lt;em&gt;y_i&lt;/em&gt; is the actual value and &lt;em&gt;haty_i&lt;/em&gt; is the predicted value.&lt;/p&gt;

&lt;p&gt;We square the residuals for two critical reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Positivity: It turns all negative errors into positive numbers, preventing opposing errors from canceling each other out.&lt;/li&gt;
&lt;li&gt;Penalization: Squaring mathematically punishes large errors much more aggressively than small ones, forcing the model to prioritize its biggest mistakes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;However, for classification tasks (like predicting the next word in a language model), RSS falls short. Instead, we use the &lt;strong&gt;Cross-Entropy Loss&lt;/strong&gt; function. This function takes a predicted probability distribution and compares it against the true answer, calculating a smooth, differentiable error score that teaches the model how to adjust its confidence for the next pass. More about Cross Entropy Loss in another blog.&lt;/p&gt;

&lt;h2&gt;
  
  
  Gradient Descent
&lt;/h2&gt;

&lt;p&gt;I studied all of this from the YouTube channel "StatQuest" (amazing resource). And the narrator sang a silly song about Gradient Descent that I still remember. "Gradient Descent is decent....at optimising parameters!" And that's it. &lt;/p&gt;

&lt;p&gt;After calculating the loss (using the loss function), we update parameters (weights and biases) one by one and repeat our calculations again till the loss is near zero meaning our model is trained optimally.&lt;/p&gt;

&lt;p&gt;Here's a useful visualisation for understanding gradient descent better, Imagine the model is blindfolded on a high-dimensional mountain, trying to find the lowest point in the valley (the minimum error). Because the model is blindfolded, it uses calculus to feel the slope of the ground directly under its feet. &lt;strong&gt;Gradient Descent&lt;/strong&gt; is the mathematical process of taking a step downward. The size of that step is dictated by your Learning Rate. In simple terms, gradient descent uses the chain rule to calculate derivative of the loss function with respect to a particular weight. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;θ_new = θ_old - η*∇L(θ)&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;&lt;code&gt;η*∇&lt;/code&gt; where is the learning rate and &lt;code&gt;L&lt;/code&gt; is the loss gradient with respect to parameters and &lt;code&gt;θ&lt;/code&gt; is the parameter(either weigh or bias) which has to be updated.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Backpropogation
&lt;/h2&gt;

&lt;p&gt;Backpropagation is the algorithm that makes training deep networks tractable. It computes gradients of the loss with respect to every parameter through recursive application of the chain rule. Starting at the final output (the Loss), it uses the Chain Rule from calculus to propagate backward through the network, calculating the exact gradient (slope) for every single weight and uses Gradient descent to update the parameters.&lt;/p&gt;

&lt;h2&gt;
  
  
  Attention Mechanism
&lt;/h2&gt;

&lt;p&gt;Attention has revolutionized neural networks, enabling models to  focus on relevant information rather than processing all inputs equally. The mechanism computes weighted combinations of input representations based on learned relevance scores.&lt;/p&gt;

&lt;p&gt;The core attention operation: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Attention(Q, K, V) = softmax(Q*K^T/√d_k)*V&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;where queries (Q), keys (K), and values (V) are learned projections of inputs. This allows the model to learn which parts of the input are most relevant for each prediction. Attention mechanisms underpin Transformers, which have become the dominant architecture for NLP (GPT, BERT, Claude, etc.).  Self-attention enables modeling long-range dependencies without the recurrence bottlenecks of RNNs. A detailed exploration of attention mechanisms, multi-head attention, and Transformer architectures will be covered in an upcoming blog post.&lt;/p&gt;

&lt;h2&gt;
  
  
  Layer Normalisation and Batch Normalisation
&lt;/h2&gt;

&lt;p&gt;As data passes through dozens of layers, the distribution of those activations can shift wildly, called as Internal Covariate Shift, causing gradients to explode or vanish.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Batch Normalization&lt;/strong&gt; normalizes the activations across the batch dimension. It is highly effective for CNNs and standard FFNs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Layer Normalization&lt;/strong&gt; normalizes the activations across the feature dimension for a single data point. This is the stabilization technique of choice for modern Transformer models, ensuring that sequence lengths and batch sizes don't disrupt the mathematical flow.&lt;/p&gt;

&lt;p&gt;That's it for this blog. Hope you liked it! Be sure to suggest any changes if needed :)&lt;/p&gt;

</description>
      <category>ai</category>
      <category>beginners</category>
      <category>machinelearning</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
