-
Notifications
You must be signed in to change notification settings - Fork 133
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #860 from MikeSoft007/feat/stripe_checkout
feat: integrate stripe payment and add endpoint for fetching user plans in organisation
- Loading branch information
Showing
13 changed files
with
479 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
alembic/versions/9a4e3d412f8e_updated_billing_model_ensuing_that_plan_.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
"""updated billing model ensuing that plan name is unique | ||
Revision ID: 9a4e3d412f8e | ||
Revises: af8459ffc616 | ||
Create Date: 2024-08-11 21:16:54.902038 | ||
""" | ||
from typing import Sequence, Union | ||
|
||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
|
||
# revision identifiers, used by Alembic. | ||
revision: str = '9a4e3d412f8e' | ||
down_revision: Union[str, None] = 'af8459ffc616' | ||
branch_labels: Union[str, Sequence[str], None] = None | ||
depends_on: Union[str, Sequence[str], None] = None | ||
|
||
|
||
def upgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table('user_subscriptions', | ||
sa.Column('user_id', sa.String(), nullable=False), | ||
sa.Column('plan_id', sa.String(), nullable=False), | ||
sa.Column('organisation_id', sa.String(), nullable=False), | ||
sa.Column('active', sa.Boolean(), nullable=True), | ||
sa.Column('start_date', sa.String(), nullable=False), | ||
sa.Column('end_date', sa.String(), nullable=True), | ||
sa.Column('id', sa.String(), nullable=False), | ||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), | ||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), | ||
sa.ForeignKeyConstraint(['organisation_id'], ['organisations.id'], ondelete='CASCADE'), | ||
sa.ForeignKeyConstraint(['plan_id'], ['billing_plans.id'], ondelete='CASCADE'), | ||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), | ||
sa.PrimaryKeyConstraint('id') | ||
) | ||
op.create_index(op.f('ix_user_subscriptions_id'), 'user_subscriptions', ['id'], unique=False) | ||
op.create_unique_constraint(None, 'billing_plans', ['name']) | ||
op.add_column('user_organisation_roles', sa.Column('status', sa.String(length=20), nullable=False)) | ||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.drop_column('user_organisation_roles', 'status') | ||
op.drop_constraint(None, 'billing_plans', type_='unique') | ||
op.drop_index(op.f('ix_user_subscriptions_id'), table_name='user_subscriptions') | ||
op.drop_table('user_subscriptions') | ||
# ### end Alembic commands ### |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
from fastapi import APIRouter, Depends, HTTPException, Request, status | ||
from sqlalchemy.orm import Session | ||
import stripe | ||
from api.v1.services.stripe_payment import stripe_payment_request, update_user_plan, fetch_all_organisations_with_users_and_plans | ||
import json | ||
from api.v1.schemas.stripe import PlanUpgradeRequest | ||
from typing import List | ||
from api.db.database import get_db | ||
import os | ||
from api.utils.success_response import success_response | ||
from api.v1.models.user import User | ||
from api.v1.services.user import user_service | ||
from dotenv import load_dotenv, find_dotenv | ||
|
||
load_dotenv(find_dotenv()) | ||
|
||
stripe.api_key = os.getenv('STRIPE_SECRET_KEY') | ||
endpoint_secret = os.getenv('STRIPE_WEBHOOK_SECRET') | ||
|
||
subscription_ = APIRouter(prefix="/payment", tags=["subscribe-plan"]) | ||
|
||
@subscription_.post("/stripe/upgrade-plan") | ||
def stripe_payment( | ||
plan_upgrade_request: PlanUpgradeRequest, | ||
request: Request, | ||
db: Session = Depends(get_db), | ||
current_user: User = Depends(user_service.get_current_user) | ||
): | ||
return stripe_payment_request(db, plan_upgrade_request.user_id, request, plan_upgrade_request.plan_name) | ||
|
||
@subscription_.get("/stripe/success") | ||
def success_upgrade(): | ||
return {"message" : "Payment successful"} | ||
|
||
@subscription_.get("/stripe/cancel") | ||
def cancel_upgrade(): | ||
return {"message" : "Payment canceled"} | ||
|
||
@subscription_.post("/webhook") | ||
async def webhook_received( | ||
request: Request, | ||
db: Session = Depends(get_db) | ||
): | ||
|
||
payload = await request.body() | ||
event = None | ||
|
||
try: | ||
event = stripe.Event.construct_from(json.loads(payload), stripe.api_key) | ||
except ValueError as e: | ||
print("Invalid payload") | ||
raise HTTPException(status_code=400, detail="Invalid payload") | ||
except stripe.error.SignatureVerificationError as e: | ||
print("Invalid signature") | ||
raise HTTPException(status_code=400, detail="Invalid signature") | ||
|
||
if event["type"] == "checkout.session.completed": | ||
payment = event["data"]["object"] | ||
response_details = { | ||
"amount": payment["amount_total"], | ||
"currency": payment["currency"], | ||
"user_id": payment["metadata"]["user_id"], | ||
"user_email": payment["customer_details"]["email"], | ||
"user_name": payment["customer_details"]["name"], | ||
"order_id": payment["id"] | ||
} | ||
# Save to DB | ||
# Send email in background task | ||
await update_user_plan(db, payment["metadata"]["user_id"], payment["metadata"]["plan_name"]) | ||
return {"message": response_details} | ||
|
||
|
||
@subscription_.get("/organisations/users/plans") | ||
async def get_organisations_with_users_and_plans(db: Session = Depends(get_db), current_user: User = Depends(user_service.get_current_super_admin)): | ||
try: | ||
data = fetch_all_organisations_with_users_and_plans(db) | ||
if not data: | ||
return {"status_code": 404, "success": False, "message": "No data found"} | ||
return success_response( | ||
status_code=status.HTTP_302_FOUND, | ||
message='billing details successfully retrieved', | ||
data=data, | ||
) | ||
except Exception as e: | ||
raise HTTPException(status_code=500, detail=str(e)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
from typing import List, Optional | ||
|
||
from pydantic import BaseModel, Field, validator | ||
|
||
|
||
class PaymentInfo(BaseModel): | ||
card_number: str = Field(..., min_length=16, max_length=16) | ||
exp_month: int | ||
exp_year: int | ||
cvc: str = Field(..., min_length=3, max_length=4) | ||
|
||
@validator('card_number') | ||
def card_number_validator(cls, v): | ||
if not v.isdigit() or len(v) != 16: | ||
raise ValueError('Card number must be 16 digits') | ||
return v | ||
|
||
@validator('cvc') | ||
def cvc_validator(cls, v): | ||
if not v.isdigit() or not (3 <= len(v) <= 4): | ||
raise ValueError('CVC must be 3 or 4 digits') | ||
return v | ||
|
||
|
||
class PlanUpgradeRequest(BaseModel): | ||
user_id: str | ||
plan_name: str | ||
payment_info: Optional[PaymentInfo] = None | ||
|
||
|
Oops, something went wrong.