# RateRight Stripe Payment Flow Design

## Executive Summary

**Recommended Approach: Stripe Checkout** - The most suitable integration for our $50 one-time contractor hiring fee, offering the best balance of security, user experience, and implementation speed.

## 1. Stripe Integration Options Analysis

### Stripe Checkout (Recommended ✅)
- **What it is**: Pre-built, hosted payment page by Stripe
- **Pros**: 
  - PCI compliant out of the box
  - Mobile-optimized design
  - Supports all major payment methods
  - Fraud protection included
  - Fastest to implement (1-2 days)
  - No payment form to build/maintain
- **Cons**: 
  - User redirected to Stripe domain
  - Less customization of payment UI
- **Implementation**: ~4-8 hours

### Payment Intents API
- **What it is**: Build your own payment form, Stripe handles processing
- **Pros**: 
  - Full control over payment UI
  - User stays on your domain
  - Advanced customization
- **Cons**: 
  - Must build and maintain payment form
  - Need PCI compliance considerations
  - More complex implementation
  - Fraud protection setup required
- **Implementation**: 2-3 days

### Payment Links
- **What it is**: Shareable payment links (not suitable for our use case)
- **Verdict**: ❌ Not recommended - designed for invoices/single payments, not dynamic hiring scenarios

## 2. Recommended Approach: Stripe Checkout

**Rationale**: For a $50 one-time payment with our timeline constraints, Checkout provides the optimal balance of security, speed, and reliability.

## 3. User Journey Flow

```
┌─────────────────────────────────────────────────────────────────┐
│                        USER JOURNEY                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ 1. Contractor Views Worker Profile                              │
│    ┌─────────────────────────────────────────────────────────┐   │
│    │  [Worker: Sarah M.]                                     │   │
│    │  Skills: Carpentry, Electrical                          │   │
│    │  Rating: ⭐⭐⭐⭐⭐ (4.8/5)                                 │   │
│    │  [HIRE WORKER - $50] ← Click here                       │   │
│    └─────────────────────────────────────────────────────────┘   │
│                                                                 │
│ 2. Confirmation Modal                                           │
│    ┌─────────────────────────────────────────────────────────┐   │
│    │  Hire Sarah M. for your job?                            │   │
│    │                                                         │   │
│    │  ✓ Unlock contact details                               │   │
│    │  ✓ Get direct messaging access                          │   │
│    │  ✓ View full work history                               │   │
│    │                                                         │   │
│    │  One-time fee: $50.00                                   │   │
│    │                                                         │   │
│    │  [Cancel]  [Continue to Payment]                        │   │
│    └─────────────────────────────────────────────────────────┘   │
│                                                                 │
│ 3. Redirect to Stripe Checkout                                  │
│    ┌─────────────────────────────────────────────────────────┐   │
│    │  SECURE PAYMENT - Stripe Checkout                       │   │
│    │                                                         │   │
│    │  RateRight - Hire Sarah M.                              │   │
│    │  Amount: $50.00 AUD                                      │   │
│    │                                                         │   │
│    │  [Card Input Fields]                                    │   │
│    │  [Pay $50.00]                                           │   │
│    └─────────────────────────────────────────────────────────┘   │
│                                                                 │
│ 4a. Payment Success                                            │
│    ┌─────────────────────────────────────────────────────────┐   │
│    │  ✅ Payment Successful!                                  │   │
│    │                                                         │   │
│    │  Sarah's contact details are now unlocked:              │   │
│    │  📞 Phone: +61 4XX XXX XXX                              │   │
│    │  📧 Email: sarah@example.com                            │   │
│    │  💬 Message: Start conversation                           │   │
│    │                                                         │   │
│    │  [View Full Profile]                                    │   │
│    └─────────────────────────────────────────────────────────┘   │
│                                                                 │
│ 4b. Payment Failed/Cancelled                                   │
│    ┌─────────────────────────────────────────────────────────┐   │
│    │  ❌ Payment Unsuccessful                                 │   │
│    │                                                         │   │
│    │  Your payment could not be processed.                   │   │
│    │  Please try again or contact support.                   │   │
│    │                                                         │   │
│    │  [Try Again] [Contact Support]                          │   │
│    └─────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
```

## 4. Post-Payment Actions

### Immediate (within seconds):
1. **Database Update**: Mark worker as "hired" by contractor
2. **Contact Unlock**: Reveal worker's phone/email to contractor
3. **Notification Sent**: Worker receives "You've been hired" notification
4. **Payment Record**: Create payment record in database
5. **Receipt Email**: Send payment confirmation to contractor

### Within 1 hour:
1. **Profile Access**: Contractor gets full access to worker's complete profile
2. **Messaging Enabled**: Direct messaging channel opened
3. **Contractor Dashboard**: Worker added to "My Hires" section

## 5. Stripe Fee Impact

**Current Stripe Fees (Australia - 2024):**
- Domestic cards: 1.75% + $0.30
- International cards: 2.9% + $0.30

**For $50 payment:**
- Domestic: $50 × 1.75% + $0.30 = $1.18 fee
- International: $50 × 2.9% + $0.30 = $1.75 fee

**Net Revenue:**
- Domestic: $50 - $1.18 = **$48.82**
- International: $50 - $1.75 = **$48.25**

## 6. Refund Policy Considerations

### Recommended Policy:
**"No refunds once contact details are accessed"**

**Rationale:**
- Digital service (contact access)
- Irreversible once delivered
- Low transaction amount ($50)
- Industry standard for marketplace platforms

### Implementation:
- Clear refund policy shown before payment
- Require checkbox acknowledgment
- Process refunds only for technical failures
- Dispute handling through Stripe dashboard

## 7. Required API Endpoints

### Backend Endpoints:
```
POST   /api/payments/create-checkout-session
       → Creates Stripe Checkout session
       ← Returns: { sessionId, url }

POST   /api/payments/webhook
       → Receives Stripe webhook events
       ← Returns: { received: true }

GET    /api/payments/status/:paymentId
       → Checks payment status
       ← Returns: { status, workerId, contractorId }

POST   /api/hires/confirm
       → Confirms hire after payment
       ← Returns: { hireId, workerContact }
```

### Frontend Routes:
```
/payment/success?session_id={id}    → Payment success page
/payment/cancelled                  → Payment cancelled page
/hire/confirmation/{workerId}       → Post-hire confirmation
```

## 8. Database Schema Additions

```sql
-- Payments table
CREATE TABLE payments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    contractor_id UUID REFERENCES users(id) NOT NULL,
    worker_id UUID REFERENCES users(id) NOT NULL,
    stripe_payment_intent_id VARCHAR(255) UNIQUE NOT NULL,
    stripe_checkout_session_id VARCHAR(255) UNIQUE NOT NULL,
    amount INTEGER NOT NULL, -- in cents ($50 = 5000)
    currency VARCHAR(3) NOT NULL DEFAULT 'AUD',
    status VARCHAR(50) NOT NULL, -- 'pending', 'completed', 'failed', 'refunded'
    stripe_fee INTEGER, -- in cents
    net_amount INTEGER, -- in cents
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    completed_at TIMESTAMP,
    refunded_at TIMESTAMP,
    metadata JSONB
);

-- Hires table (tracks successful hires)
CREATE TABLE hires (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    contractor_id UUID REFERENCES users(id) NOT NULL,
    worker_id UUID REFERENCES users(id) NOT NULL,
    payment_id UUID REFERENCES payments(id) NOT NULL,
    job_posting_id UUID REFERENCES job_postings(id),
    status VARCHAR(50) NOT NULL DEFAULT 'active', -- 'active', 'completed', 'cancelled'
    hired_at TIMESTAMP DEFAULT NOW(),
    completed_at TIMESTAMP,
    contractor_rating INTEGER CHECK (contractor_rating >= 1 AND contractor_rating <= 5),
    worker_rating INTEGER CHECK (worker_rating >= 1 AND worker_rating <= 5),
    UNIQUE(contractor_id, worker_id, payment_id)
);

-- Add indexes for performance
CREATE INDEX idx_payments_contractor ON payments(contractor_id);
CREATE INDEX idx_payments_worker ON payments(worker_id);
CREATE INDEX idx_payments_status ON payments(status);
CREATE INDEX idx_payments_created ON payments(created_at);
CREATE INDEX idx_hires_contractor ON hires(contractor_id);
CREATE INDEX idx_hires_worker ON hires(worker_id);
```

## 9. Security Considerations

### Authentication & Authorization:
- Verify contractor is logged in before payment
- Ensure contractor hasn't already hired this worker
- Rate limiting on payment attempts (max 3 per hour)

### Data Protection:
- Never store full card details (Stripe handles this)
- Encrypt sensitive data in database
- Use HTTPS for all payment-related endpoints
- Implement CSRF protection on payment forms

### Webhook Security:
- Verify Stripe webhook signatures
- Use webhook endpoint secrets
- Implement idempotency for webhook processing
- Log all webhook events for audit trail

### Fraud Prevention:
- Enable Stripe Radar (included free)
- Monitor for suspicious payment patterns
- Implement velocity checks (max hires per day)
- Use Stripe's built-in 3D Secure when required

## 10. Implementation Timeline

### Phase 1: Core Integration (4-6 hours)
- [ ] Set up Stripe account and API keys
- [ ] Install Stripe SDK
- [ ] Create checkout session endpoint
- [ ] Implement webhook handler
- [ ] Basic success/cancel pages

### Phase 2: Database & Business Logic (3-4 hours)
- [ ] Create payments and hires tables
- [ ] Implement payment status tracking
- [ ] Add hire confirmation logic
- [ ] Update user models and relationships

### Phase 3: Frontend Integration (2-3 hours)
- [ ] Add "Hire Worker" button to profiles
- [ ] Create confirmation modal
- [ ] Implement payment flow UI
- [ ] Add success notifications

### Phase 4: Testing & Polish (2-3 hours)
- [ ] Test payment flow end-to-end
- [ ] Add error handling and edge cases
- [ ] Implement logging and monitoring
- [ ] Add payment receipts/emails

**Total Estimated Time: 11-16 hours (2-3 days)**

## 11. Quick Start Checklist

- [ ] Create Stripe account (if not exists)
- [ ] Get Stripe API keys (test mode first)
- [ ] Install Stripe SDK: `npm install stripe`
- [ ] Set up webhook endpoint in Stripe dashboard
- [ ] Create payments table in database
- [ ] Implement basic checkout session creation
- [ ] Test with Stripe test card: 4242 4242 4242 4242
- [ ] Switch to live mode and test with real payment

## 12. Next Steps

1. **Start with test mode** - Use Stripe's test cards
2. **Implement webhook endpoint first** - Critical for reliability
3. **Add comprehensive logging** - Essential for debugging
4. **Plan for scaling** - Consider payment volume limits
5. **Set up monitoring** - Track payment success rates
6. **Create support process** - Handle payment issues

---

**Remember**: This is designed for fast implementation. Start simple, test thoroughly, then add enhancements based on user feedback and payment analytics.