Skip to content

Commit

Permalink
Minor fixes on stripe webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
beastoin committed Dec 10, 2024
1 parent cc46cfb commit 4b24e26
Show file tree
Hide file tree
Showing 7 changed files with 24 additions and 17 deletions.
2 changes: 1 addition & 1 deletion app/lib/pages/home/page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver, Ticker
tabs: [
Tab(
child: Text(
'Convos.',
'Home',
style: TextStyle(
color: home.selectedIndex == 0 ? Colors.white : Colors.grey,
fontSize: MediaQuery.sizeOf(context).width < 410 ? 14 : 16,
Expand Down
4 changes: 3 additions & 1 deletion backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from modal import Image, App, asgi_app, Secret
from routers import workflow, chat, firmware, plugins, memories, transcribe_v2, notifications, \
speech_profile, agents, facts, users, processing_memories, trends, sdcard, sync, apps, custom_auth
speech_profile, agents, facts, users, processing_memories, trends, sdcard, sync, apps, custom_auth, payment

if os.environ.get('SERVICE_ACCOUNT_JSON'):
service_account_info = json.loads(os.environ["SERVICE_ACCOUNT_JSON"])
Expand Down Expand Up @@ -38,6 +38,8 @@
app.include_router(apps.router)
app.include_router(custom_auth.router)

app.include_router(payment.router)

modal_app = App(
name='backend',
secrets=[Secret.from_name("gcp-credentials"), Secret.from_name('envs')],
Expand Down
3 changes: 2 additions & 1 deletion backend/models/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,11 @@ class App(BaseModel):
money_made: Optional[float] = None
usage_count: Optional[int] = None
is_paid: Optional[bool] = False
price: Optional[float] = 0.0
price: Optional[float] = 0.0 # cents/100
payment_plan: Optional[str] = None
payment_product_id: Optional[str] = None
payment_price_id: Optional[str] = None
payment_link_id: Optional[str] = None
payment_link: Optional[str] = None
is_user_paid: Optional[bool] = False

Expand Down
4 changes: 2 additions & 2 deletions backend/routers/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def create_app(app_data: str = Form(...), file: UploadFile = File(...), uid=Depe

# payment link
app = App(**data)
upsert_app_payment_link(app.id, app.is_paid, app.price, app.payment_type)
upsert_app_payment_link(app.id, app.is_paid, app.price, app.payment_plan)

return {'status': 'ok'}

Expand Down Expand Up @@ -107,7 +107,7 @@ def update_app(app_id: str, app_data: str = Form(...), file: UploadFile = File(N

# payment link
app = App(**data)
upsert_app_payment_link(app.id, app.is_paid, app.price, app.payment_plan)
upsert_app_payment_link(app.id, app.is_paid, app.price, app.payment_plan, previous_price=plugin.get("price", 0))

if plugin['approved'] and (plugin['private'] is None or plugin['private'] is False):
delete_generic_cache('get_public_approved_apps_data')
Expand Down
2 changes: 1 addition & 1 deletion backend/routers/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async def stripe_webhook(request: Request, stripe_signature: str = Header(None))
print(session)
print(f"Payment completed for session: {session['id']}")

app_id = session['app_id']
app_id = session['metadata']['app_id']
uid = session['client_reference_id'][4:]
paid_app(app_id, uid)

Expand Down
15 changes: 8 additions & 7 deletions backend/utils/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,13 +260,13 @@ def get_app_money_made(app_id: str) -> dict[str, int | float]:

return money

def upsert_app_payment_link(app_id: str, is_paid_app: bool, price: float, payment_plan: str):
def upsert_app_payment_link(app_id: str, is_paid_app: bool, price: float, payment_plan: str, previous_price: float | None = None):
if not is_paid_app:
print(f"App is not a paid app, app_id: {app_id}")
return None

if payment_plan not in ['monthly_recurring']:
print(f"App payment type is invalid, app_id: {app_id}")
print(f"App payment plan is invalid, app_id: {app_id}")
return None

app_data = get_app_by_id_db(app_id)
Expand All @@ -276,7 +276,7 @@ def upsert_app_payment_link(app_id: str, is_paid_app: bool, price: float, paymen

app = App(**app_data)

if price == app.price:
if previous_price and previous_price == price:
print(f"App price is existing, app_id: {app_id}")
return app

Expand All @@ -288,16 +288,17 @@ def upsert_app_payment_link(app_id: str, is_paid_app: bool, price: float, paymen
if payment_plan == 'monthly_recurring':
# product
if not app.payment_product_id:
payment_product = stripe.create_product(f"{app.name} Monthly Subscription", app.description)
payment_product = stripe.create_product(f"{app.name} Monthly Plan", app.description, app.image)
app.payment_product_id = payment_product.id

# price
payment_price = stripe.create_app_monthly_recurring_price(app.payment_product_id, price)
payment_price = stripe.create_app_monthly_recurring_price(app.payment_product_id, int(price*100))
app.payment_price_id = payment_price.id

# payment link
payment_price = stripe.create_app_payment_link(app.payment_product_id, price)
app.payment_link = app.payment_price_id
payment_link = stripe.create_app_payment_link(app.payment_price_id, app.id)
app.payment_link_id = payment_link.id
app.payment_link = payment_link.url

# updates
update_app_in_db(app.dict())
Expand Down
11 changes: 7 additions & 4 deletions backend/utils/stripe.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,27 @@
stripe.api_key = os.getenv('STRIPE_API_KEY')
endpoint_secret = os.getenv('STRIPE_WEBHOOK_SECRET')

def create_product(name, description):
def create_product(name: str, description: str, image: str):
"""Create a new product in Stripe."""
product = stripe.Product.create(
name=name,
description=description,
images=[image] if image and len(image) > 0 else [],
tax_code="txcd_10103000", # saas
)
return product

def create_app_monthly_recurring_price(product_id, amount, currency='usd'):
def create_app_monthly_recurring_price(product_id:str, amount_in_cents: int, currency:str = 'usd'):
"""Create a price for the given product."""
price = stripe.Price.create(
unit_amount=amount,
unit_amount=amount_in_cents,
currency=currency,
product=product_id,
recurring={'interval': 'month'},
)
return price

def create_app_payment_link(price_id, app_id):
def create_app_payment_link(price_id:str, app_id: str):
"""Create a payment link for the specified price."""
payment_link = stripe.PaymentLink.create(
line_items=[{
Expand All @@ -37,6 +39,7 @@ def create_app_payment_link(price_id, app_id):


def parse_event(payload, sig_header):
"""Parse the Stripe event."""
return stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)

0 comments on commit 4b24e26

Please sign in to comment.