Skip to content

OurBusWay/Payment

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Payment Service - Backend Setup Guide

βœ… Implementation Status

BACKEND: FULLY IMPLEMENTED βœ…

All backend components are complete and ready to run:

  • βœ… Stripe Integration: Java SDK v24.9.0 configured
  • βœ… Payment Models: PaymentModel, PaymentStatusEnum (PENDING, REQUIRES_CONFIRMATION, SUCCEEDED, FAILED)
  • βœ… Repository Layer: PaymentRepository with JPA + Specifications
  • βœ… Service Layer: PaymentService, PaymentProcessingService with Stripe API calls
  • βœ… REST API: PaymentController with /process and /webhook endpoints
  • βœ… Event-Driven: RabbitMQ integration (listens to payment-request, publishes payment-success)
  • βœ… Configuration: Stripe keys, database, service discovery all configured

πŸš€ How to Run the Payment Service

Prerequisites

  1. PostgreSQL running on localhost:5432

    • Database: db-payment
    • Username: postgres
    • Password: mysecretpassword
  2. Consul running on localhost:8500 (service discovery)

  3. RabbitMQ running on localhost:5672 (event messaging)

  4. Environment Variables configured (see below)


Step 1: Configure Environment Variables

The Payment service reads Stripe credentials from environment variables. You have two options:

Option A: Load from .env file (Recommended for local dev)

The .env file already contains:

STRIPE_SECRET_KEY=sk_test_51SYuUWRzGsmN2IxdQKjXO5Odsr4xVR9KLe0yCcwkaSTIaAUOw5EKO4ioim5pj75XQn4DoBp2MFJ84nac7ZZUM8Qq00JSZBCjzK
STRIPE_WEBHOOK_SECRET=whsec_661b1cccb7ca673417e10f38c798ea1841d6449a716f268d89890d71db5bcb8d

In PowerShell:

# Load .env file (run from Payment directory)
Get-Content .env | ForEach-Object {
    if ($_ -match '^([^=]+)=(.*)$') {
        [System.Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process")
    }
}

Or set manually:

$env:STRIPE_SECRET_KEY="sk_test_51SYuUWRzGsmN2IxdQKjXO5Odsr4xVR9KLe0yCcwkaSTIaAUOw5EKO4ioim5pj75XQn4DoBp2MFJ84nac7ZZUM8Qq00JSZBCjzK"
$env:STRIPE_WEBHOOK_SECRET="whsec_661b1cccb7ca673417e10f38c798ea1841d6449a716f268d89890d71db5bcb8d"

Option B: Set in IDE (IntelliJ/Eclipse)

Add to Run Configuration β†’ Environment Variables:

STRIPE_SECRET_KEY=sk_test_51SYuUWRzGsmN2IxdQKjXO5Odsr4xVR9KLe0yCcwkaSTIaAUOw5EKO4ioim5pj75XQn4DoBp2MFJ84nac7ZZUM8Qq00JSZBCjzK
STRIPE_WEBHOOK_SECRET=whsec_661b1cccb7ca673417e10f38c798ea1841d6449a716f268d89890d71db5bcb8d

Step 2: Build the Project

# From Payment directory
./mvnw clean install -DskipTests

Step 3: Run the Service

Option A: Using Maven

./mvnw spring-boot:run

Option B: Using IDE

  • Run PaymentApplication.java main class
  • Ensure environment variables are set in Run Configuration

Option C: Using JAR

java -jar target/payment-0.0.1-SNAPSHOT.jar

Step 4: Verify Service is Running

  1. Check Consul: http://localhost:8500/ui/

    • Service payment should appear
  2. Check Actuator Health: http://localhost:8087/actuator/health

    {
      "status": "UP"
    }
  3. Check Logs for:

    πŸ”§ Stripe API initialized
    πŸ’Ύ Database connection established
    πŸ“‘ Consul registration successful
    🐰 RabbitMQ connection established
    πŸš€ Payment service started on port 8087
    

πŸ“‘ API Endpoints

1. Process Payment

Creates/retrieves a Stripe PaymentIntent for a ticket purchase.

Request:

POST /payments/process
Content-Type: application/json

{
  "ticketRequestId": "ticket-uuid-here"
}

Response:

{
  "paymentIntentId": "pi_xxx",
  "clientSecret": "pi_xxx_secret_xxx",
  "amount": 150.0,
  "currency": "MAD"
}

2. Stripe Webhook

Receives events from Stripe when payments succeed/fail.

Request:

POST /payments/webhook
Content-Type: application/json
Stripe-Signature: t=xxx,v1=xxx

{...stripe event payload...}

Response:

"Success"

πŸ”„ Event-Driven Flow

Incoming Events (Listens To)

Event: payment-request (from Ticket service) Queue: payment-process Payload:

{
  "userId": "user-uuid",
  "routeId": "route-uuid",
  "amount": 150.0,
  "currency": "MAD",
  "ticketRequestId": "ticket-uuid"
}

Action:

  1. Creates PaymentModel with status PENDING
  2. Creates Stripe PaymentIntent
  3. Updates status to REQUIRES_CONFIRMATION
  4. Stores stripePaymentIntentId

Outgoing Events (Publishes)

Event: payment-success (to Ticket service) Exchange: payment.success.exchange Payload:

{
  "paymentId": "payment-uuid",
  "ticketRequestId": "ticket-uuid",
  "routeId": "route-uuid",
  "userId": "user-uuid",
  "amount": 150.0,
  "currency": "MAD"
}

Triggered By: Stripe webhook payment_intent.succeeded


πŸ—„οΈ Database Schema

Table: N_PAYMENT

Column Type Description
id VARCHAR Primary key (UUID)
user_id VARCHAR User who initiated payment
amount DOUBLE Payment amount
currency VARCHAR(3) Currency code (MAD)
status VARCHAR PENDING, REQUIRES_CONFIRMATION, SUCCEEDED, FAILED
stripe_payment_intent_id VARCHAR Stripe PaymentIntent ID
stripe_charge_id VARCHAR Stripe Charge ID (after success)
description VARCHAR Optional description
ticket_request_id VARCHAR Reference to ticket being purchased
ticket_id VARCHAR Final ticket ID (after success)
subscription_id VARCHAR For future subscription support
created_at TIMESTAMP Creation timestamp
updated_at TIMESTAMP Last update timestamp

πŸ§ͺ Testing the Payment Flow

1. Start Required Services

# Start PostgreSQL, Consul, RabbitMQ
cd platform-local-env
docker-compose up -d

2. Run Payment Service

cd Payment
./mvnw spring-boot:run

3. Simulate Payment Request Event

Use RabbitMQ Management UI (http://localhost:15672) or code to publish to payment-process queue:

{
  "userId": "test-user-123",
  "routeId": "route-456",
  "amount": 150.0,
  "currency": "MAD",
  "ticketRequestId": "ticket-789"
}

4. Check Payment Created

Query database:

SELECT * FROM n_payment WHERE ticket_request_id = 'ticket-789';

Should show:

  • status: REQUIRES_CONFIRMATION
  • stripe_payment_intent_id: pi_xxx

5. Test Payment Process Endpoint

curl http://localhost:8087/payments/process `
  -H "Content-Type: application/json" `
  -d '{"ticketRequestId":"ticket-789"}'

Should return:

{
  "paymentIntentId": "pi_xxx",
  "clientSecret": "pi_xxx_secret_xxx",
  "amount": 150.0,
  "currency": "MAD"
}

6. Simulate Stripe Webhook (Payment Success)

Use Stripe CLI or send webhook manually:

stripe trigger payment_intent.succeeded

Check logs for:

πŸŽ‰ Stripe PaymentIntent succeeded: pi_xxx
βœ… Payment SUCCESS updated
πŸ“€ payment-success event published

πŸ› οΈ Troubleshooting

Problem: Service won't start

Symptom: Error about missing environment variables

Could not resolve placeholder 'STRIPE_SECRET_KEY'

Solution: Ensure environment variables are set:

echo $env:STRIPE_SECRET_KEY
echo $env:STRIPE_WEBHOOK_SECRET

If empty, run:

Get-Content .env | ForEach-Object {
    if ($_ -match '^([^=]+)=(.*)$') {
        [System.Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process")
    }
}

Problem: Database connection failed

Symptom: Connection to localhost:5432 refused

Solution:

  1. Check PostgreSQL is running:

    docker ps | Select-String postgres
  2. Create database if missing:

    CREATE DATABASE "db-payment";
  3. Verify credentials in application-dev.yml


Problem: Consul not found

Symptom: Could not locate Consul agent

Solution:

# Start Consul
docker run -d -p 8500:8500 consul agent -dev

Problem: RabbitMQ connection failed

Symptom: Connection refused: localhost:5672

Solution:

# Check RabbitMQ
docker ps | Select-String rabbitmq

# If not running:
docker run -d -p 5672:5672 -p 15672:15672 rabbitmq:management

Problem: Stripe API errors

Symptom: No API key provided

Solution:

  1. Verify Stripe key is set:

    echo $env:STRIPE_SECRET_KEY
  2. Check key starts with sk_test_

  3. Test key in Stripe Dashboard: https://dashboard.stripe.com/test/apikeys


πŸ“‹ Quick Start Checklist

  • PostgreSQL running with db-payment database
  • Consul running on port 8500
  • RabbitMQ running on port 5672
  • Environment variables set (STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET)
  • Project built: ./mvnw clean install
  • Service running: ./mvnw spring-boot:run
  • Health check passes: http://localhost:8087/actuator/health
  • Service registered in Consul: http://localhost:8500/ui/

πŸ”— Integration with Other Services

Gateway Routes

The Gateway should route /paymentMgtApi/** to Payment service:

# Gateway application.yml
spring:
  cloud:
    gateway:
      routes:
        - id: payment-service
          uri: lb://payment
          predicates:
            - Path=/paymentMgtApi/**
          filters:
            - StripPrefix=1

Frontend Integration (TODO)

See frontend todo list for:

  • Installing Stripe.js packages
  • Creating paymentService.ts
  • Creating PaymentPage component
  • Updating BuyTicketPage flow

πŸ“š Additional Resources


🎯 Next Steps (Frontend)

The backend is COMPLETE. Next, implement the frontend:

  1. Install Stripe.js packages in FrontEnd
  2. Create paymentService.ts API client
  3. Create PaymentPage.tsx with Stripe Elements
  4. Modify BuyTicketPage.tsx to redirect to payment
  5. Add payment route to router
  6. Configure Stripe publishable key in frontend .env

See updated todo list for detailed frontend tasks.

change this by your path to set the env variables """ cd C:\Users\ZACKWEB\Desktop\OurBusWay\Payment; Get-Content .env | ForEach-Object { if ($_ -match '^([^=]+)=(.*)$') { [System.Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process") } }; $env:STRIPE_SECRET_KEY; $env:STRIPE_WEBHOOK_SECRET

"""

C:\Users\ZACKWEB\Desktop\OurBusWay\strip_133\stripe.exe listen --forward-to localhost:8087/paymentMgtApi/webhook

About

No description or website provided.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors