Lý thuyết
40 phút
Bài 12/15

User Authentication & Payments

Thêm đăng nhập, membership tiers và thanh toán vào AI apps

🔐 User Authentication & Payments

Thêm authentication và payment system vào AI apps.

Why Auth & Payments?

Text
1Benefits:
2- Personalized experience
3- Usage tracking per user
4- Monetization
5- Data privacy
6- Feature gating

User Authentication

Bubble Built-in Auth

Text
1User Data Type (built-in):
2- email
3- password (encrypted)
4- created date
5- modified date
6
7Add custom fields:
8- plan_type (text)
9- usage_count (number)
10- usage_reset_date (date)
11- profile_picture (image)

Signup Flow

Text
1Signup Page Elements:
21. Email input
32. Password input
43. Confirm password input
54. Signup button
65. "Already have account?" link

Signup Workflow

Text
1Button "Sign Up" clicked:
2
31. Validate
4 - Email format valid
5 - Password min 8 chars
6 - Passwords match
7
82. Sign user up
9 - Email: Email Input's value
10 - Password: Password Input's value
11
123. Initialize user
13 - Set plan_type = "free"
14 - Set usage_count = 0
15 - Set usage_reset_date = Current date
16
174. Navigate to app

Login Flow

Text
1Login Page Elements:
21. Email input
32. Password input
43. Login button
54. "Forgot password?" link
65. "Sign up" link

Login Workflow

Text
1Button "Login" clicked:
2
31. Log user in
4 - Email: Email Input
5 - Password: Password Input
6
72. If login successful:
8 - Navigate to app
9
103. If login fails:
11 - Show error message

OAuth (Google, etc.)

Text
1In Bubble:
21. Plugins → Add Google OAuth
32. Configure in Google Console
43. Add "Login with Google" button
54. Workflow: Login with Google

Membership Tiers

Plan Structure

Text
1Free Plan:
2- 10 AI requests/day
3- Basic features
4- No history export
5
6Pro Plan ($9/month):
7- 100 AI requests/day
8- All features
9- Export & history
10- Priority support
11
12Business Plan ($29/month):
13- Unlimited requests
14- API access
15- Team features
16- Custom branding

Database Updates

Text
1User fields:
2- plan_type: free/pro/business
3- subscription_id: Stripe subscription ID
4- subscription_status: active/cancelled/past_due
5- usage_count: number (daily)
6- usage_reset_date: date

Usage Tracking

Text
1Check before AI call:
2
31. Get user's plan_type
42. Get usage_count
53. Get limit for plan
64. If usage_count >= limit
7 - Show upgrade prompt
8 - Stop workflow
95. Else
10 - Continue
11 - Increment usage_count

Reset Daily Usage

Text
1Scheduled workflow (runs daily):
2
3Search for Users:
4 where usage_reset_date < Current date - 1 day
5
6Make changes to list:
7 - usage_count = 0
8 - usage_reset_date = Current date

Feature Gating

Conditional Display

Text
1Show Pro features only to Pro users:
2
3Element conditional:
4- Visible when: Current User's plan_type is "pro"
5
6Or hide with blur + upgrade prompt

Workflow Gates

Text
1Before premium action:
2
3Only when: Current User's plan_type is "pro"
4
5Else: Show upgrade popup

Payment Integration

Stripe Setup

Stripe Integration
Text
1Steps:
21. Create Stripe account
32. Get API keys (test mode first)
43. Install Stripe plugin in Bubble
54. Configure API keys
65. Create products in Stripe Dashboard

Stripe Products

Text
1In Stripe Dashboard:
2
3Product 1: Pro Monthly
4- Price: $9/month
5- Recurring
6
7Product 2: Business Monthly
8- Price: $29/month
9- Recurring
10
11Get Price IDs for each

Checkout Flow

Text
1Button "Upgrade to Pro" clicked:
2
31. Create Stripe Checkout Session
4 - Price ID: pro_monthly_price_id
5 - Success URL: your-app.com/success
6 - Cancel URL: your-app.com/pricing
7 - Customer email: Current User's email
8
92. Navigate to Stripe Checkout URL

Success Page

Text
1On success page load:
2
31. Get session_id from URL
42. Retrieve Stripe session details
53. Update User:
6 - plan_type = "pro"
7 - subscription_id = session's subscription ID
8 - subscription_status = "active"
94. Show success message
105. Navigate to app

Webhook Handling

Why Webhooks?

Text
1Stripe events to handle:
2- Payment successful
3- Subscription renewed
4- Payment failed
5- Subscription cancelled

Setup Webhook

Text
11. In Stripe Dashboard → Webhooks
22. Add endpoint: your-app.com/api/stripe-webhook
33. Select events to listen
4
54. In Bubble → Backend Workflows
65. Create API workflow: stripe-webhook
76. Handle each event type

Handle Events

Text
1Event: customer.subscription.deleted
2
31. Get subscription_id from event
42. Search User where subscription_id = event's ID
53. Update User:
6 - plan_type = "free"
7 - subscription_status = "cancelled"

Pricing Page

Layout

Text
1┌────────────────────────────────────────────────┐
2│ Choose Your Plan │
3├──────────────┬───────────────┬────────────────┤
4│ FREE │ PRO │ BUSINESS │
5│ $0 │ $9/mo │ $29/mo │
6├──────────────┼───────────────┼────────────────┤
7│ 10 req/day │ 100 req/day │ Unlimited │
8│ Basic AI │ All AI tools │ All AI tools │
9│ No export │ Export │ Export + API │
10│ - │ History │ Team access │
11│ - │ Support │ Priority │
12├──────────────┼───────────────┼────────────────┤
13│ [Current] │ [Upgrade] │ [Upgrade] │
14└──────────────┴───────────────┴────────────────┘

Dynamic Buttons

Text
1Conditionals:
2
3If user's plan = this plan:
4- Text: "Current Plan"
5- Disabled
6
7If user's plan < this plan:
8- Text: "Upgrade"
9- Clickable
10
11If user's plan > this plan:
12- Hidden or "Contact Us"

Cancel Subscription

Cancel Flow

Text
1Button "Cancel Subscription" clicked:
2
31. Confirm popup
4 "Are you sure? You'll lose Pro features."
5
62. Call Stripe API: Cancel Subscription
7 - Subscription ID: Current User's subscription_id
8 - Cancel at period end: yes (grace period)
9
103. Update User:
11 - subscription_status = "cancelling"
12
134. Show confirmation

Free Trial

Trial Setup

Text
1Stripe subscription with trial:
2- Trial period: 7 days
3- No charge during trial
4- Auto-charges after trial
5
6User fields:
7- trial_end_date
8- has_used_trial (yes/no)

Trial Workflow

Text
1New user signup:
2
31. Check if eligible for trial
4 - has_used_trial = no
5
62. Create subscription with trial
7 - trial_period_days: 7
8
93. Update User:
10 - has_used_trial = yes
11 - trial_end_date = +7 days

Usage Dashboard

User Dashboard

Text
1┌────────────────────────────────┐
2│ Your Plan: Pro │
3│ Usage: 45/100 today │
4│ ████████░░░░░ 45% │
5│ │
6│ Renews: Jan 15, 2025 │
7│ [Manage Subscription] │
8└────────────────────────────────┘

Implementation

Text
1Progress bar width:
2(Current User's usage_count / plan_limit) * 100 %
3
4Text display:
5Current User's usage_count / plan_limit " today"

Security Best Practices

Security
Text
11. Server-side validation
2 - Don't trust client-side only
3 - Verify plan in backend
4
52. Secure webhooks
6 - Verify Stripe signature
7 - Use webhook secrets
8
93. Protect sensitive data
10 - Don't expose subscription IDs
11 - Privacy rules on database
12
134. Handle edge cases
14 - Payment failures
15 - Expired cards
16 - Cancelled but active period

Testing

Test Mode
Text
1Use Stripe test mode:
2- Test card: 4242 4242 4242 4242
3- Any future expiry
4- Any CVC
5
6Test scenarios:
7- Successful payment
8- Failed payment (use 4000000000000002)
9- Cancel subscription
10- Webhook events

Bài Tập

Practice

Implement Auth & Payments:

  1. Set up user signup/login
  2. Create membership tiers
  3. Implement usage tracking
  4. Set up Stripe (test mode)
  5. Build pricing page
  6. Create checkout flow
  7. Handle webhooks
  8. Test full flow

Tiếp theo: Bài 13 - Deployment & Hosting