-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstripe.html
More file actions
1774 lines (1536 loc) · 100 KB
/
stripe.html
File metadata and controls
1774 lines (1536 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stripe & Payments - Better Dev</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group"><a href="index.html">Home</a></div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Stripe & Payments</div>
<h1>Stripe & Payments</h1>
<p>Everything you need to accept payments on the web. From understanding how card payments actually work to building production-ready Stripe integrations with Node.js and TypeScript -- payment intents, checkout, subscriptions, webhooks, error handling, and security.</p>
</div>
<div class="toc">
<h4>Table of Contents</h4>
<a href="#how-payments-work">1. How Payments Work</a>
<a href="#stripe-architecture">2. Stripe Architecture</a>
<a href="#setup">3. Setting Up Stripe</a>
<a href="#payment-intents">4. Payment Intents</a>
<a href="#checkout">5. Stripe Checkout (Hosted)</a>
<a href="#elements">6. Stripe Elements (Embedded)</a>
<a href="#subscriptions">7. Subscriptions</a>
<a href="#webhooks">8. Webhooks</a>
<a href="#customers">9. Customers & Payment Methods</a>
<a href="#error-handling">10. Error Handling</a>
<a href="#security">11. Security & PCI Compliance</a>
<a href="#testing">12. Testing</a>
<a href="#common-patterns">13. Common Patterns</a>
<a href="#full-example">14. Full Integration Example</a>
</div>
<!-- ============================================================ -->
<!-- SECTION 1: How Payments Work -->
<!-- ============================================================ -->
<section id="how-payments-work" class="section">
<h2>1. How Payments Work</h2>
<p>Before writing a single line of Stripe code, you need to understand what happens when a customer swipes, taps, or types their card number. The payment lifecycle involves multiple parties and distinct phases.</p>
<div class="formula-box">
<div class="label">The Payment Flow</div>
<p>Customer -> Merchant -> Acquirer (merchant's bank) -> Card Network (Visa/MC) -> Issuer (customer's bank)</p>
<p>Response flows back the same path in reverse.</p>
</div>
<h3>Authorization</h3>
<p>When a customer submits payment, an <strong>authorization request</strong> travels from the merchant through the acquiring bank, through the card network (Visa, Mastercard, Amex), to the issuing bank. The issuer checks if the card is valid, has sufficient funds, passes fraud checks, and then sends back an approval or decline. This entire round-trip happens in under 2 seconds. No money has moved yet -- the issuer has only placed a <strong>hold</strong> on the funds.</p>
<h3>Capture</h3>
<p>After authorization, the merchant <strong>captures</strong> the payment. This tells the system "yes, I want this money." In many integrations, authorization and capture happen simultaneously (called an <strong>auto-capture</strong>). But some businesses (hotels, car rentals, marketplaces) authorize first and capture later -- this is called <strong>auth-and-capture</strong> or <strong>manual capture</strong>.</p>
<div class="tip-box">
<div class="label">Auth-and-Capture Use Case</div>
<p>A hotel authorizes $500 at check-in but only captures $350 at checkout (the actual stay cost). Authorizations expire after ~7 days, so you must capture within that window or re-authorize.</p>
</div>
<h3>Settlement</h3>
<p>Settlement is when money actually moves between banks. The card network batches up all the day's captured transactions and orchestrates fund transfers between issuing and acquiring banks. This typically takes 1-3 business days. Stripe abstracts this -- you see payouts to your bank account on a rolling basis (usually 2 business days after the charge).</p>
<h3>Refunds and Chargebacks</h3>
<p>A <strong>refund</strong> is merchant-initiated: you return funds to the customer. A <strong>chargeback</strong> (or dispute) is customer-initiated: they contact their bank to reverse the charge. Chargebacks cost you the transaction amount plus a fee ($15 on Stripe). Too many chargebacks and your account gets flagged or terminated.</p>
<div class="warning-box">
<div class="label">Chargeback Rate</div>
<p>Card networks flag merchants with dispute rates above 0.9% (Visa) or 1.0% (Mastercard). If you cross this threshold, you enter a monitoring program with escalating fines. Track your dispute rate in the Stripe Dashboard under Radar.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 2: Stripe Architecture -->
<!-- ============================================================ -->
<section id="stripe-architecture" class="section">
<h2>2. Stripe Architecture</h2>
<p>Stripe is an API-first payment processor. Everything -- charges, customers, subscriptions, payouts -- is a REST API call. The Dashboard is just a UI on top of the same API you use.</p>
<h3>API-First Design</h3>
<p>Every Stripe resource is a JSON object with a unique ID (e.g., <code>pi_1234abc</code> for a PaymentIntent, <code>cus_xyz</code> for a Customer). You create, read, update, and delete these via HTTP requests. The Node.js SDK wraps these calls into clean async methods.</p>
<h3>Test Mode vs Live Mode</h3>
<p>Stripe gives you two completely isolated environments. Test mode uses fake card numbers, generates no real charges, and has its own Dashboard view. Live mode processes real money. Each mode has its own API keys. You toggle between them in the Dashboard with a single switch.</p>
<div class="example-box">
<div class="label">API Key Prefixes</div>
<p><code>sk_test_...</code> -- Secret key (test mode). Server-side only.</p>
<p><code>pk_test_...</code> -- Publishable key (test mode). Safe for client-side.</p>
<p><code>sk_live_...</code> -- Secret key (live mode). NEVER expose this.</p>
<p><code>pk_live_...</code> -- Publishable key (live mode). Client-side.</p>
</div>
<h3>Secret vs Publishable Keys</h3>
<p>The <strong>secret key</strong> can do anything: create charges, read customer data, issue refunds. It lives exclusively on your server. The <strong>publishable key</strong> can only do limited operations like tokenizing card details. It is safe to include in frontend JavaScript. Leaking your secret key is a catastrophic security incident.</p>
<div class="warning-box">
<div class="label">Never Commit API Keys</div>
<p>Store Stripe keys in environment variables. Never hardcode them. Never commit <code>.env</code> files. Use Stripe's restricted keys in production to limit permissions to only what each service needs.</p>
</div>
<h3>Stripe API Versioning</h3>
<p>Stripe versions its API by date (e.g., <code>2024-06-20</code>). Your account is pinned to the version you signed up with. You can override per-request with the <code>Stripe-Version</code> header, or set a default in your SDK initialization. Stripe never removes fields from existing versions -- breaking changes only appear in new versions.</p>
</section>
<!-- ============================================================ -->
<!-- SECTION 3: Setting Up -->
<!-- ============================================================ -->
<section id="setup" class="section">
<h2>3. Setting Up Stripe</h2>
<h3>Install the SDK</h3>
<pre><code><span class="lang-label">bash</span>
<span class="comment"># Install Stripe Node.js SDK</span>
npm install stripe
<span class="comment"># If using TypeScript (types are included in the stripe package)</span>
npm install stripe typescript @types/node
<span class="comment"># Install dotenv for environment variables</span>
npm install dotenv
</code></pre>
<h3>Environment Variables</h3>
<pre><code><span class="lang-label">.env</span>
<span class="comment"># Stripe API Keys</span>
STRIPE_SECRET_KEY=sk_test_51ABC123...
STRIPE_PUBLISHABLE_KEY=pk_test_51ABC123...
STRIPE_WEBHOOK_SECRET=whsec_abc123...
<span class="comment"># App config</span>
PORT=<span class="number">3000</span>
CLIENT_URL=http://localhost:5173
</code></pre>
<h3>Initialize Stripe in Node.js</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">import</span> Stripe <span class="keyword">from</span> <span class="string">'stripe'</span>;
<span class="keyword">import</span> dotenv <span class="keyword">from</span> <span class="string">'dotenv'</span>;
dotenv.<span class="function">config</span>();
<span class="keyword">const</span> stripe = <span class="keyword">new</span> <span class="function">Stripe</span>(process.env.STRIPE_SECRET_KEY!, {
apiVersion: <span class="string">'2024-06-20'</span>,
typescript: <span class="keyword">true</span>,
});
<span class="keyword">export default</span> stripe;
</code></pre>
<div class="tip-box">
<div class="label">TypeScript Benefits</div>
<p>The Stripe SDK has excellent TypeScript support. Every API response is fully typed, every parameter has autocomplete, and you get compile-time errors for invalid fields. Always use TypeScript with Stripe -- the type safety alone prevents countless bugs.</p>
</div>
<h3>Project Structure</h3>
<pre><code><span class="lang-label">text</span>
my-stripe-app/
src/
config/
stripe.ts <span class="comment">// Stripe instance</span>
routes/
payments.ts <span class="comment">// Payment endpoints</span>
webhooks.ts <span class="comment">// Webhook handler</span>
subscriptions.ts <span class="comment">// Subscription endpoints</span>
services/
stripe.service.ts <span class="comment">// Business logic</span>
middleware/
auth.ts <span class="comment">// Authentication</span>
index.ts <span class="comment">// Express app</span>
.env
package.json
tsconfig.json
</code></pre>
</section>
<!-- ============================================================ -->
<!-- SECTION 4: Payment Intents -->
<!-- ============================================================ -->
<section id="payment-intents" class="section">
<h2>4. Payment Intents</h2>
<p>PaymentIntent is Stripe's core payment object. It represents the lifecycle of a single payment from creation to confirmation to completion. It handles 3D Secure authentication, retries, and state management automatically.</p>
<div class="formula-box">
<div class="label">PaymentIntent Lifecycle</div>
<p>requires_payment_method -> requires_confirmation -> requires_action (optional, for 3DS) -> processing -> succeeded / requires_capture</p>
</div>
<h3>Create a PaymentIntent (Server-Side)</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">import</span> express <span class="keyword">from</span> <span class="string">'express'</span>;
<span class="keyword">import</span> stripe <span class="keyword">from</span> <span class="string">'../config/stripe'</span>;
<span class="keyword">const</span> router = express.<span class="function">Router</span>();
<span class="comment">// POST /api/create-payment-intent</span>
router.<span class="function">post</span>(<span class="string">'/create-payment-intent'</span>, <span class="keyword">async</span> (req, res) => {
<span class="keyword">try</span> {
<span class="keyword">const</span> { amount, currency = <span class="string">'usd'</span>, metadata } = req.body;
<span class="comment">// Validate amount (Stripe uses smallest currency unit -- cents for USD)</span>
<span class="keyword">if</span> (!amount || amount < <span class="number">50</span>) {
<span class="keyword">return</span> res.<span class="function">status</span>(<span class="number">400</span>).<span class="function">json</span>({ error: <span class="string">'Minimum amount is $0.50'</span> });
}
<span class="keyword">const</span> paymentIntent = <span class="keyword">await</span> stripe.paymentIntents.<span class="function">create</span>({
amount, <span class="comment">// e.g., 2000 = $20.00</span>
currency,
metadata: metadata || {},
automatic_payment_methods: {
enabled: <span class="keyword">true</span>, <span class="comment">// Accept cards, wallets, etc.</span>
},
});
<span class="comment">// Send the client_secret to the frontend</span>
res.<span class="function">json</span>({
clientSecret: paymentIntent.client_secret,
paymentIntentId: paymentIntent.id,
});
} <span class="keyword">catch</span> (error: <span class="keyword">any</span>) {
res.<span class="function">status</span>(<span class="number">500</span>).<span class="function">json</span>({ error: error.message });
}
});
<span class="keyword">export default</span> router;
</code></pre>
<h3>Confirm on the Client</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Frontend: React or vanilla JS</span>
<span class="keyword">import</span> { loadStripe } <span class="keyword">from</span> <span class="string">'@stripe/stripe-js'</span>;
<span class="keyword">const</span> stripePromise = <span class="function">loadStripe</span>(<span class="string">'pk_test_...'</span>);
<span class="keyword">async function</span> <span class="function">handlePayment</span>() {
<span class="keyword">const</span> stripe = <span class="keyword">await</span> stripePromise;
<span class="keyword">if</span> (!stripe) <span class="keyword">return</span>;
<span class="comment">// 1. Create PaymentIntent on the server</span>
<span class="keyword">const</span> response = <span class="keyword">await</span> <span class="function">fetch</span>(<span class="string">'/api/create-payment-intent'</span>, {
method: <span class="string">'POST'</span>,
headers: { <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span> },
body: JSON.<span class="function">stringify</span>({ amount: <span class="number">2000</span> }),
});
<span class="keyword">const</span> { clientSecret } = <span class="keyword">await</span> response.<span class="function">json</span>();
<span class="comment">// 2. Confirm with Stripe.js (handles 3D Secure automatically)</span>
<span class="keyword">const</span> { error, paymentIntent } = <span class="keyword">await</span> stripe.<span class="function">confirmCardPayment</span>(clientSecret, {
payment_method: {
card: cardElement, <span class="comment">// From Stripe Elements</span>
billing_details: {
name: <span class="string">'Sean'</span>,
},
},
});
<span class="keyword">if</span> (error) {
console.<span class="function">error</span>(error.message);
} <span class="keyword">else if</span> (paymentIntent.status === <span class="string">'succeeded'</span>) {
console.<span class="function">log</span>(<span class="string">'Payment succeeded!'</span>);
}
}
</code></pre>
<div class="tip-box">
<div class="label">Why Client Secret?</div>
<p>The <code>client_secret</code> lets the frontend confirm the payment without exposing your secret key. It is scoped to one PaymentIntent and cannot be used to create new payments or access other data. The server creates the intent, the client confirms it -- this split is the core Stripe security model.</p>
</div>
<h3>Manual Capture (Auth-then-Capture)</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Create with manual capture</span>
<span class="keyword">const</span> paymentIntent = <span class="keyword">await</span> stripe.paymentIntents.<span class="function">create</span>({
amount: <span class="number">50000</span>, <span class="comment">// $500 hold</span>
currency: <span class="string">'usd'</span>,
capture_method: <span class="string">'manual'</span>,
automatic_payment_methods: { enabled: <span class="keyword">true</span> },
});
<span class="comment">// Later: capture a different (lower) amount</span>
<span class="keyword">const</span> captured = <span class="keyword">await</span> stripe.paymentIntents.<span class="function">capture</span>(paymentIntent.id, {
amount_to_capture: <span class="number">35000</span>, <span class="comment">// Only capture $350</span>
});
</code></pre>
</section>
<!-- ============================================================ -->
<!-- SECTION 5: Stripe Checkout -->
<!-- ============================================================ -->
<section id="checkout" class="section">
<h2>5. Stripe Checkout (Hosted)</h2>
<p>Stripe Checkout is a pre-built, hosted payment page. You redirect customers to Stripe's domain, they pay, and Stripe redirects them back. Zero frontend payment UI code. It handles card input, validation, 3D Secure, Apple Pay, Google Pay, and localization automatically.</p>
<div class="tip-box">
<div class="label">When to Use Checkout</div>
<p>Use Checkout when you want the fastest integration, highest conversion rates (Stripe A/B tests it constantly), and minimal PCI scope. It is the recommended approach for most businesses unless you need a fully custom payment UI.</p>
</div>
<h3>One-Time Payment Checkout Session</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// POST /api/create-checkout-session</span>
router.<span class="function">post</span>(<span class="string">'/create-checkout-session'</span>, <span class="keyword">async</span> (req, res) => {
<span class="keyword">try</span> {
<span class="keyword">const</span> session = <span class="keyword">await</span> stripe.checkout.sessions.<span class="function">create</span>({
mode: <span class="string">'payment'</span>,
payment_method_types: [<span class="string">'card'</span>],
line_items: [
{
price_data: {
currency: <span class="string">'usd'</span>,
product_data: {
name: <span class="string">'Pro License'</span>,
description: <span class="string">'Lifetime access to all features'</span>,
images: [<span class="string">'https://example.com/product.png'</span>],
},
unit_amount: <span class="number">4999</span>, <span class="comment">// $49.99</span>
},
quantity: <span class="number">1</span>,
},
],
success_url: <span class="string">`${process.env.CLIENT_URL}/success?session_id={CHECKOUT_SESSION_ID}`</span>,
cancel_url: <span class="string">`${process.env.CLIENT_URL}/cancel`</span>,
metadata: {
userId: req.body.userId,
},
});
res.<span class="function">json</span>({ url: session.url });
} <span class="keyword">catch</span> (error: <span class="keyword">any</span>) {
res.<span class="function">status</span>(<span class="number">500</span>).<span class="function">json</span>({ error: error.message });
}
});
</code></pre>
<h3>Redirect on the Client</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Frontend: redirect to Stripe Checkout</span>
<span class="keyword">async function</span> <span class="function">goToCheckout</span>() {
<span class="keyword">const</span> response = <span class="keyword">await</span> <span class="function">fetch</span>(<span class="string">'/api/create-checkout-session'</span>, {
method: <span class="string">'POST'</span>,
headers: { <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span> },
body: JSON.<span class="function">stringify</span>({ userId: <span class="string">'user_123'</span> }),
});
<span class="keyword">const</span> { url } = <span class="keyword">await</span> response.<span class="function">json</span>();
window.location.href = url; <span class="comment">// Redirect to Stripe's hosted page</span>
}
</code></pre>
<h3>Subscription Checkout Session</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Checkout for recurring payments</span>
<span class="keyword">const</span> session = <span class="keyword">await</span> stripe.checkout.sessions.<span class="function">create</span>({
mode: <span class="string">'subscription'</span>,
line_items: [
{
price: <span class="string">'price_monthly_pro'</span>, <span class="comment">// Pre-created Price ID</span>
quantity: <span class="number">1</span>,
},
],
success_url: <span class="string">`${process.env.CLIENT_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`</span>,
cancel_url: <span class="string">`${process.env.CLIENT_URL}/pricing`</span>,
customer_email: <span class="string">'user@example.com'</span>,
subscription_data: {
trial_period_days: <span class="number">14</span>,
metadata: { plan: <span class="string">'pro'</span> },
},
});
</code></pre>
<div class="example-box">
<div class="label">Checkout Session Modes</div>
<p><code>payment</code> -- One-time charge</p>
<p><code>subscription</code> -- Recurring billing</p>
<p><code>setup</code> -- Save a card for later (no charge now)</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 6: Stripe Elements -->
<!-- ============================================================ -->
<section id="elements" class="section">
<h2>6. Stripe Elements (Embedded)</h2>
<p>Stripe Elements lets you embed payment inputs directly in your page with full control over styling. The <code>PaymentElement</code> is the modern, recommended component -- it renders all payment methods (cards, wallets, bank transfers) in a single, adaptive UI.</p>
<h3>Setting Up Elements</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Frontend: initialize Stripe Elements</span>
<span class="keyword">import</span> { loadStripe } <span class="keyword">from</span> <span class="string">'@stripe/stripe-js'</span>;
<span class="keyword">const</span> stripe = <span class="keyword">await</span> <span class="function">loadStripe</span>(<span class="string">'pk_test_...'</span>);
<span class="comment">// Fetch client secret from your server</span>
<span class="keyword">const</span> response = <span class="keyword">await</span> <span class="function">fetch</span>(<span class="string">'/api/create-payment-intent'</span>, {
method: <span class="string">'POST'</span>,
headers: { <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span> },
body: JSON.<span class="function">stringify</span>({ amount: <span class="number">2999</span> }),
});
<span class="keyword">const</span> { clientSecret } = <span class="keyword">await</span> response.<span class="function">json</span>();
<span class="comment">// Create Elements instance with appearance customization</span>
<span class="keyword">const</span> elements = stripe.<span class="function">elements</span>({
clientSecret,
appearance: {
theme: <span class="string">'stripe'</span>, <span class="comment">// or 'night', 'flat', 'none'</span>
variables: {
colorPrimary: <span class="string">'#0570de'</span>,
borderRadius: <span class="string">'8px'</span>,
fontFamily: <span class="string">'Inter, sans-serif'</span>,
},
},
});
<span class="comment">// Mount the PaymentElement</span>
<span class="keyword">const</span> paymentElement = elements.<span class="function">create</span>(<span class="string">'payment'</span>);
paymentElement.<span class="function">mount</span>(<span class="string">'#payment-element'</span>);
</code></pre>
<h3>HTML Container</h3>
<pre><code><span class="lang-label">HTML</span>
<form id=<span class="string">"payment-form"</span>>
<div id=<span class="string">"payment-element"</span>>
<span class="comment"><!-- Stripe injects the PaymentElement here --></span>
</div>
<button id=<span class="string">"submit"</span> type=<span class="string">"submit"</span>>Pay now</button>
<div id=<span class="string">"error-message"</span>></div>
</form>
</code></pre>
<h3>Handle Form Submission</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">const</span> form = document.<span class="function">getElementById</span>(<span class="string">'payment-form'</span>)!;
form.<span class="function">addEventListener</span>(<span class="string">'submit'</span>, <span class="keyword">async</span> (e) => {
e.<span class="function">preventDefault</span>();
<span class="keyword">const</span> submitBtn = document.<span class="function">getElementById</span>(<span class="string">'submit'</span>) <span class="keyword">as</span> HTMLButtonElement;
submitBtn.disabled = <span class="keyword">true</span>;
<span class="keyword">const</span> { error } = <span class="keyword">await</span> stripe.<span class="function">confirmPayment</span>({
elements,
confirmParams: {
return_url: <span class="string">'http://localhost:5173/success'</span>,
},
});
<span class="comment">// This point is only reached if there is an immediate error</span>
<span class="comment">// (e.g., card declined). Otherwise, the customer is redirected.</span>
<span class="keyword">if</span> (error) {
<span class="keyword">const</span> errorDiv = document.<span class="function">getElementById</span>(<span class="string">'error-message'</span>)!;
errorDiv.textContent = error.message || <span class="string">'An unexpected error occurred.'</span>;
submitBtn.disabled = <span class="keyword">false</span>;
}
});
</code></pre>
<div class="warning-box">
<div class="label">Never Collect Raw Card Numbers</div>
<p>Always use Stripe Elements or Checkout. If you collect raw card numbers yourself, you must be PCI DSS Level 1 certified -- an extremely expensive, time-consuming audit. Elements and Checkout handle card data on Stripe's servers, keeping you at PCI SAQ-A (the lightest level).</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 7: Subscriptions -->
<!-- ============================================================ -->
<section id="subscriptions" class="section">
<h2>7. Subscriptions</h2>
<p>Stripe's subscription system is built on two core objects: <strong>Products</strong> (what you sell) and <strong>Prices</strong> (how much it costs). A Product can have many Prices (monthly, yearly, different tiers). A Subscription ties a Customer to one or more Prices.</p>
<h3>Create a Product and Price</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Usually you create these in the Dashboard, but here's the API way</span>
<span class="keyword">const</span> product = <span class="keyword">await</span> stripe.products.<span class="function">create</span>({
name: <span class="string">'Pro Plan'</span>,
description: <span class="string">'All features, unlimited projects'</span>,
});
<span class="comment">// Monthly price</span>
<span class="keyword">const</span> monthlyPrice = <span class="keyword">await</span> stripe.prices.<span class="function">create</span>({
product: product.id,
unit_amount: <span class="number">1999</span>, <span class="comment">// $19.99/month</span>
currency: <span class="string">'usd'</span>,
recurring: {
interval: <span class="string">'month'</span>,
},
});
<span class="comment">// Yearly price (with discount)</span>
<span class="keyword">const</span> yearlyPrice = <span class="keyword">await</span> stripe.prices.<span class="function">create</span>({
product: product.id,
unit_amount: <span class="number">19990</span>, <span class="comment">// $199.90/year (~$16.66/month)</span>
currency: <span class="string">'usd'</span>,
recurring: {
interval: <span class="string">'year'</span>,
},
});
</code></pre>
<h3>Create a Subscription</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Create subscription for an existing customer</span>
<span class="keyword">const</span> subscription = <span class="keyword">await</span> stripe.subscriptions.<span class="function">create</span>({
customer: <span class="string">'cus_abc123'</span>,
items: [
{ price: <span class="string">'price_monthly_pro'</span> },
],
payment_behavior: <span class="string">'default_incomplete'</span>,
payment_settings: {
save_default_payment_method: <span class="string">'on_subscription'</span>,
},
expand: [<span class="string">'latest_invoice.payment_intent'</span>],
});
<span class="comment">// Send client_secret to frontend to confirm the first payment</span>
<span class="keyword">const</span> clientSecret =
(subscription.latest_invoice <span class="keyword">as</span> Stripe.Invoice)
.payment_intent <span class="keyword">as</span> Stripe.PaymentIntent;
res.<span class="function">json</span>({ clientSecret: clientSecret.client_secret });
</code></pre>
<h3>Free Trials</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// 14-day free trial -- no charge until trial ends</span>
<span class="keyword">const</span> subscription = <span class="keyword">await</span> stripe.subscriptions.<span class="function">create</span>({
customer: <span class="string">'cus_abc123'</span>,
items: [{ price: <span class="string">'price_monthly_pro'</span> }],
trial_period_days: <span class="number">14</span>,
});
<span class="comment">// Trial with no card required (collect card later)</span>
<span class="keyword">const</span> trialSub = <span class="keyword">await</span> stripe.subscriptions.<span class="function">create</span>({
customer: <span class="string">'cus_abc123'</span>,
items: [{ price: <span class="string">'price_monthly_pro'</span> }],
trial_period_days: <span class="number">14</span>,
payment_settings: {
save_default_payment_method: <span class="string">'on_subscription'</span>,
},
trial_settings: {
end_behavior: { missing_payment_method: <span class="string">'cancel'</span> },
},
});
</code></pre>
<h3>Proration</h3>
<p>When a customer upgrades or downgrades mid-cycle, Stripe calculates the prorated amount automatically. If a customer on a $10/month plan upgrades to $20/month halfway through the cycle, they get credited $5 for the unused portion and charged $10 for the remaining half on the new plan.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Upgrade a subscription (proration happens automatically)</span>
<span class="keyword">const</span> subscription = <span class="keyword">await</span> stripe.subscriptions.<span class="function">retrieve</span>(<span class="string">'sub_abc123'</span>);
<span class="keyword">await</span> stripe.subscriptions.<span class="function">update</span>(<span class="string">'sub_abc123'</span>, {
items: [
{
id: subscription.items.data[<span class="number">0</span>].id,
price: <span class="string">'price_yearly_pro'</span>, <span class="comment">// Switch to yearly</span>
},
],
proration_behavior: <span class="string">'create_prorations'</span>, <span class="comment">// or 'none' or 'always_invoice'</span>
});
</code></pre>
<h3>Cancel a Subscription</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Cancel at end of current billing period (most common)</span>
<span class="keyword">await</span> stripe.subscriptions.<span class="function">update</span>(<span class="string">'sub_abc123'</span>, {
cancel_at_period_end: <span class="keyword">true</span>,
});
<span class="comment">// Cancel immediately (prorated refund)</span>
<span class="keyword">await</span> stripe.subscriptions.<span class="function">cancel</span>(<span class="string">'sub_abc123'</span>, {
prorate: <span class="keyword">true</span>,
});
<span class="comment">// Pause instead of cancel (resume later)</span>
<span class="keyword">await</span> stripe.subscriptions.<span class="function">update</span>(<span class="string">'sub_abc123'</span>, {
pause_collection: {
behavior: <span class="string">'mark_uncollectible'</span>, <span class="comment">// or 'keep_as_draft', 'void'</span>
},
});
</code></pre>
<div class="example-box">
<div class="label">Subscription Statuses</div>
<p><code>trialing</code> -- In trial period</p>
<p><code>active</code> -- Paid and current</p>
<p><code>past_due</code> -- Payment failed, retrying</p>
<p><code>unpaid</code> -- All retries exhausted</p>
<p><code>canceled</code> -- Terminated</p>
<p><code>incomplete</code> -- First payment not yet confirmed</p>
<p><code>incomplete_expired</code> -- First payment window expired</p>
<p><code>paused</code> -- Collection paused</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 8: Webhooks -->
<!-- ============================================================ -->
<section id="webhooks" class="section">
<h2>8. Webhooks</h2>
<p>Webhooks are how Stripe tells your server about events: a payment succeeded, a subscription was cancelled, a dispute was created. They are not optional -- they are essential. You cannot build a reliable Stripe integration without webhooks.</p>
<div class="warning-box">
<div class="label">Do Not Rely on Redirects</div>
<p>The <code>success_url</code> redirect after Checkout is NOT reliable. The customer might close the tab, lose connection, or their browser might crash. The ONLY reliable way to know a payment succeeded is via the <code>checkout.session.completed</code> webhook. Always fulfill orders in your webhook handler, not on the success page.</p>
</div>
<h3>Setting Up the Webhook Endpoint</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">import</span> express <span class="keyword">from</span> <span class="string">'express'</span>;
<span class="keyword">import</span> Stripe <span class="keyword">from</span> <span class="string">'stripe'</span>;
<span class="keyword">import</span> stripe <span class="keyword">from</span> <span class="string">'../config/stripe'</span>;
<span class="keyword">const</span> router = express.<span class="function">Router</span>();
<span class="comment">// CRITICAL: This route must use express.raw(), NOT express.json()</span>
router.<span class="function">post</span>(
<span class="string">'/webhook'</span>,
express.<span class="function">raw</span>({ type: <span class="string">'application/json'</span> }),
<span class="keyword">async</span> (req, res) => {
<span class="keyword">const</span> sig = req.headers[<span class="string">'stripe-signature'</span>] <span class="keyword">as</span> <span class="builtin">string</span>;
<span class="keyword">let</span> event: Stripe.Event;
<span class="keyword">try</span> {
event = stripe.webhooks.<span class="function">constructEvent</span>(
req.body,
sig,
process.env.STRIPE_WEBHOOK_SECRET!
);
} <span class="keyword">catch</span> (err: <span class="keyword">any</span>) {
console.<span class="function">error</span>(<span class="string">`Webhook signature verification failed: ${err.message}`</span>);
<span class="keyword">return</span> res.<span class="function">status</span>(<span class="number">400</span>).<span class="function">send</span>(<span class="string">`Webhook Error: ${err.message}`</span>);
}
<span class="comment">// Handle the event</span>
<span class="keyword">switch</span> (event.type) {
<span class="keyword">case</span> <span class="string">'payment_intent.succeeded'</span>:
<span class="keyword">await</span> <span class="function">handlePaymentSuccess</span>(event.data.object <span class="keyword">as</span> Stripe.PaymentIntent);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">'payment_intent.payment_failed'</span>:
<span class="keyword">await</span> <span class="function">handlePaymentFailure</span>(event.data.object <span class="keyword">as</span> Stripe.PaymentIntent);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">'checkout.session.completed'</span>:
<span class="keyword">await</span> <span class="function">handleCheckoutComplete</span>(event.data.object <span class="keyword">as</span> Stripe.Checkout.Session);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">'customer.subscription.updated'</span>:
<span class="keyword">await</span> <span class="function">handleSubscriptionUpdate</span>(event.data.object <span class="keyword">as</span> Stripe.Subscription);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">'customer.subscription.deleted'</span>:
<span class="keyword">await</span> <span class="function">handleSubscriptionCanceled</span>(event.data.object <span class="keyword">as</span> Stripe.Subscription);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">'invoice.payment_failed'</span>:
<span class="keyword">await</span> <span class="function">handleInvoicePaymentFailed</span>(event.data.object <span class="keyword">as</span> Stripe.Invoice);
<span class="keyword">break</span>;
<span class="keyword">default</span>:
console.<span class="function">log</span>(<span class="string">`Unhandled event type: ${event.type}`</span>);
}
<span class="comment">// Always return 200 quickly -- do heavy processing async</span>
res.<span class="function">json</span>({ received: <span class="keyword">true</span> });
}
);
</code></pre>
<div class="tip-box">
<div class="label">express.raw() is Required</div>
<p>Signature verification needs the raw request body. If you use <code>express.json()</code> on the webhook route, the body gets parsed and the signature check fails. Apply <code>express.raw()</code> specifically to the webhook route, and <code>express.json()</code> to everything else.</p>
</div>
<h3>Signature Verification</h3>
<p>Every webhook request includes a <code>Stripe-Signature</code> header. You verify it using your webhook secret (<code>whsec_...</code>). This prevents attackers from sending fake webhook events to your endpoint. Never skip signature verification in production.</p>
<h3>Handling Events: Example Handlers</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">async function</span> <span class="function">handleCheckoutComplete</span>(session: Stripe.Checkout.Session) {
<span class="keyword">const</span> userId = session.metadata?.userId;
<span class="keyword">if</span> (!userId) {
console.<span class="function">error</span>(<span class="string">'No userId in session metadata'</span>);
<span class="keyword">return</span>;
}
<span class="keyword">if</span> (session.mode === <span class="string">'payment'</span>) {
<span class="comment">// One-time payment: grant access</span>
<span class="keyword">await</span> db.users.<span class="function">update</span>({
<span class="keyword">where</span>: { id: userId },
data: { hasPro: <span class="keyword">true</span>, stripeCustomerId: session.customer <span class="keyword">as</span> <span class="builtin">string</span> },
});
} <span class="keyword">else if</span> (session.mode === <span class="string">'subscription'</span>) {
<span class="comment">// Subscription: store subscription ID</span>
<span class="keyword">await</span> db.users.<span class="function">update</span>({
<span class="keyword">where</span>: { id: userId },
data: {
stripeCustomerId: session.customer <span class="keyword">as</span> <span class="builtin">string</span>,
stripeSubscriptionId: session.subscription <span class="keyword">as</span> <span class="builtin">string</span>,
plan: <span class="string">'pro'</span>,
},
});
}
}
<span class="keyword">async function</span> <span class="function">handleSubscriptionCanceled</span>(subscription: Stripe.Subscription) {
<span class="keyword">const</span> customerId = subscription.customer <span class="keyword">as</span> <span class="builtin">string</span>;
<span class="keyword">await</span> db.users.<span class="function">update</span>({
<span class="keyword">where</span>: { stripeCustomerId: customerId },
data: { plan: <span class="string">'free'</span>, stripeSubscriptionId: <span class="keyword">null</span> },
});
}
</code></pre>
<h3>Idempotency</h3>
<p>Stripe may send the same webhook event more than once (network issues, retries). Your handler must be <strong>idempotent</strong> -- processing the same event twice should produce the same result. Use the event ID (<code>event.id</code>) to deduplicate.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Idempotent webhook handler with event tracking</span>
<span class="keyword">async function</span> <span class="function">handleWebhookEvent</span>(event: Stripe.Event) {
<span class="comment">// Check if we already processed this event</span>
<span class="keyword">const</span> existing = <span class="keyword">await</span> db.stripeEvents.<span class="function">findUnique</span>({
<span class="keyword">where</span>: { eventId: event.id },
});
<span class="keyword">if</span> (existing) {
console.<span class="function">log</span>(<span class="string">`Event ${event.id} already processed, skipping`</span>);
<span class="keyword">return</span>;
}
<span class="comment">// Process the event</span>
<span class="keyword">await</span> <span class="function">processEvent</span>(event);
<span class="comment">// Record that we processed it</span>
<span class="keyword">await</span> db.stripeEvents.<span class="function">create</span>({
data: {
eventId: event.id,
type: event.type,
processedAt: <span class="keyword">new</span> <span class="function">Date</span>(),
},
});
}
</code></pre>
<div class="example-box">
<div class="label">Key Webhook Events</div>
<p><code>checkout.session.completed</code> -- Customer completed Checkout</p>
<p><code>payment_intent.succeeded</code> -- Payment confirmed</p>
<p><code>payment_intent.payment_failed</code> -- Payment declined</p>
<p><code>customer.subscription.created</code> -- New subscription</p>
<p><code>customer.subscription.updated</code> -- Plan change, renewal, etc.</p>
<p><code>customer.subscription.deleted</code> -- Subscription ended</p>
<p><code>invoice.payment_failed</code> -- Subscription renewal failed</p>
<p><code>charge.dispute.created</code> -- Chargeback initiated</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 9: Customers -->
<!-- ============================================================ -->
<section id="customers" class="section">
<h2>9. Customers & Payment Methods</h2>
<p>A Stripe Customer object stores payment methods, billing info, and links to subscriptions and invoices. Always create a Customer for users who will pay more than once -- it enables saved cards, subscription management, and better analytics.</p>
<h3>Create a Customer</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Create a Stripe customer when a user signs up</span>
<span class="keyword">async function</span> <span class="function">createStripeCustomer</span>(user: { id: <span class="builtin">string</span>; email: <span class="builtin">string</span>; name: <span class="builtin">string</span> }) {
<span class="keyword">const</span> customer = <span class="keyword">await</span> stripe.customers.<span class="function">create</span>({
email: user.email,
name: user.name,
metadata: {
userId: user.id, <span class="comment">// Link back to your database</span>
},
});
<span class="comment">// Store the Stripe customer ID in your database</span>
<span class="keyword">await</span> db.users.<span class="function">update</span>({
<span class="keyword">where</span>: { id: user.id },
data: { stripeCustomerId: customer.id },
});
<span class="keyword">return</span> customer;
}
</code></pre>
<h3>Attach a Payment Method</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Attach a payment method to a customer</span>
<span class="keyword">const</span> paymentMethod = <span class="keyword">await</span> stripe.paymentMethods.<span class="function">attach</span>(
<span class="string">'pm_card_visa'</span>, <span class="comment">// Payment method ID from the frontend</span>
{ customer: <span class="string">'cus_abc123'</span> }
);
<span class="comment">// Set as default payment method</span>
<span class="keyword">await</span> stripe.customers.<span class="function">update</span>(<span class="string">'cus_abc123'</span>, {
invoice_settings: {
default_payment_method: paymentMethod.id,
},
});
</code></pre>
<h3>Setup Intents (Save Card Without Charging)</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Create a SetupIntent to save a card for later</span>
router.<span class="function">post</span>(<span class="string">'/create-setup-intent'</span>, <span class="keyword">async</span> (req, res) => {
<span class="keyword">const</span> { customerId } = req.body;
<span class="keyword">const</span> setupIntent = <span class="keyword">await</span> stripe.setupIntents.<span class="function">create</span>({
customer: customerId,
payment_method_types: [<span class="string">'card'</span>],
});
res.<span class="function">json</span>({ clientSecret: setupIntent.client_secret });
});
<span class="comment">// Frontend: confirm the SetupIntent</span>
<span class="keyword">const</span> { error } = <span class="keyword">await</span> stripe.<span class="function">confirmCardSetup</span>(clientSecret, {
payment_method: {
card: cardElement,
billing_details: { name: <span class="string">'Sean'</span> },
},
});
</code></pre>
<h3>List a Customer's Payment Methods</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">const</span> paymentMethods = <span class="keyword">await</span> stripe.paymentMethods.<span class="function">list</span>({
customer: <span class="string">'cus_abc123'</span>,
type: <span class="string">'card'</span>,
});
paymentMethods.data.<span class="function">forEach</span>((pm) => {
console.<span class="function">log</span>(<span class="string">`${pm.card?.brand} ending in ${pm.card?.last4}`</span>);
console.<span class="function">log</span>(<span class="string">`Expires: ${pm.card?.exp_month}/${pm.card?.exp_year}`</span>);
});
</code></pre>
<div class="tip-box">
<div class="label">Customer Portal</div>
<p>Stripe offers a pre-built Customer Portal where customers can update their payment method, switch plans, cancel subscriptions, and view invoices -- zero UI code on your end. Enable it in Dashboard > Settings > Customer Portal, then create a portal session:</p>
</div>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Create a Customer Portal session</span>
<span class="keyword">const</span> portalSession = <span class="keyword">await</span> stripe.billingPortal.sessions.<span class="function">create</span>({
customer: <span class="string">'cus_abc123'</span>,
return_url: <span class="string">`${process.env.CLIENT_URL}/dashboard`</span>,
});
res.<span class="function">json</span>({ url: portalSession.url });
</code></pre>
</section>
<!-- ============================================================ -->
<!-- SECTION 10: Error Handling -->
<!-- ============================================================ -->
<section id="error-handling" class="section">
<h2>10. Error Handling</h2>
<p>Payment failures are not bugs -- they are expected. Cards get declined, banks flag transactions, 3D Secure challenges time out. Your integration must handle every failure gracefully.</p>
<h3>Stripe Error Types</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">try</span> {
<span class="keyword">const</span> paymentIntent = <span class="keyword">await</span> stripe.paymentIntents.<span class="function">create</span>({
amount: <span class="number">2000</span>,
currency: <span class="string">'usd'</span>,
});
} <span class="keyword">catch</span> (error) {
<span class="keyword">if</span> (error <span class="keyword">instanceof</span> Stripe.errors.StripeCardError) {
<span class="comment">// Card was declined</span>
console.<span class="function">log</span>(<span class="string">`Card declined: ${error.decline_code}`</span>);
<span class="comment">// e.g., 'insufficient_funds', 'lost_card', 'stolen_card'</span>
} <span class="keyword">else if</span> (error <span class="keyword">instanceof</span> Stripe.errors.StripeRateLimitError) {
<span class="comment">// Too many requests -- back off and retry</span>
console.<span class="function">log</span>(<span class="string">'Rate limited, retrying...'</span>);
} <span class="keyword">else if</span> (error <span class="keyword">instanceof</span> Stripe.errors.StripeInvalidRequestError) {
<span class="comment">// Invalid parameters (your bug, not the customer's)</span>
console.<span class="function">error</span>(<span class="string">`Invalid request: ${error.message}`</span>);
} <span class="keyword">else if</span> (error <span class="keyword">instanceof</span> Stripe.errors.StripeAPIError) {
<span class="comment">// Stripe's servers had an error (rare)</span>
console.<span class="function">error</span>(<span class="string">'Stripe API error'</span>);
} <span class="keyword">else if</span> (error <span class="keyword">instanceof</span> Stripe.errors.StripeConnectionError) {
<span class="comment">// Network issue between your server and Stripe</span>
console.<span class="function">error</span>(<span class="string">'Connection to Stripe failed'</span>);
} <span class="keyword">else if</span> (error <span class="keyword">instanceof</span> Stripe.errors.StripeAuthenticationError) {
<span class="comment">// Invalid API key</span>
console.<span class="function">error</span>(<span class="string">'Invalid Stripe API key'</span>);
}
}
</code></pre>
<h3>Common Decline Codes</h3>
<div class="example-box">
<div class="label">Decline Code Reference</div>
<p><code>insufficient_funds</code> -- Not enough money. Ask to try another card.</p>
<p><code>card_declined</code> -- Generic decline. The issuer did not give a reason.</p>
<p><code>expired_card</code> -- Card is past its expiration date.</p>
<p><code>incorrect_cvc</code> -- Wrong CVC/CVV number.</p>
<p><code>processing_error</code> -- Temporary issue. Retry once.</p>
<p><code>lost_card</code> / <code>stolen_card</code> -- Do NOT retry. Do NOT tell the customer the specific reason (security risk).</p>
<p><code>fraudulent</code> -- Stripe Radar flagged it. Review in Dashboard.</p>
</div>