diff --git a/backend/services/stripe_service.py b/backend/services/stripe_service.py index b9653946..31807d29 100644 --- a/backend/services/stripe_service.py +++ b/backend/services/stripe_service.py @@ -66,6 +66,10 @@ class StripeService: self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com") # After consolidation, buy URL is the same as frontend URL self.buy_url = os.getenv("BUY_URL", self.frontend_url) + # Payment method configuration ID from Stripe Dashboard + # Enables Google Pay, Apple Pay, Link, and other wallet methods + # Get this from: Dashboard > Settings > Payment methods > [Your Config] > Copy ID + self.payment_method_config = os.getenv("STRIPE_PAYMENT_METHOD_CONFIG") if self.secret_key: stripe.api_key = self.secret_key @@ -73,6 +77,11 @@ class StripeService: else: logger.warning("STRIPE_SECRET_KEY not set - payments disabled") + if self.payment_method_config: + logger.info(f"Using payment method config: {self.payment_method_config}") + else: + logger.info("No STRIPE_PAYMENT_METHOD_CONFIG set - using Stripe defaults") + def is_configured(self) -> bool: """Check if Stripe is properly configured.""" return bool(self.secret_key) @@ -114,10 +123,10 @@ class StripeService: if not cancel_url: cancel_url = f"{self.buy_url}?cancelled=true" - # Create checkout session - session = stripe.checkout.Session.create( + # Build checkout session params + session_params = { # Omit payment_method_types to auto-enable Apple Pay, Google Pay, Link, etc. - line_items=[{ + 'line_items': [{ 'price_data': { 'currency': 'usd', 'product_data': { @@ -129,18 +138,25 @@ class StripeService: }, 'quantity': 1, }], - mode='payment', - success_url=success_url, - cancel_url=cancel_url, - customer_email=user_email, - metadata={ + 'mode': 'payment', + 'success_url': success_url, + 'cancel_url': cancel_url, + 'customer_email': user_email, + 'metadata': { 'package_id': package_id, 'credits': str(package['credits']), 'user_email': user_email, }, # Allow promotion codes - allow_promotion_codes=True, - ) + 'allow_promotion_codes': True, + } + + # Add payment method configuration if set (enables Google Pay, Link, etc.) + if self.payment_method_config: + session_params['payment_method_configuration'] = self.payment_method_config + + # Create checkout session + session = stripe.checkout.Session.create(**session_params) logger.info(f"Created checkout session {session.id} for {user_email}, package {package_id}") return True, session.url, "Checkout session created" @@ -206,10 +222,10 @@ class StripeService: # Truncate notes to fit Stripe's 500 char limit per metadata value metadata['notes'] = notes[:500] if len(notes) > 500 else notes - # Create checkout session - session = stripe.checkout.Session.create( + # Build checkout session params + session_params = { # Omit payment_method_types to auto-enable Apple Pay, Google Pay, Link, etc. - line_items=[{ + 'line_items': [{ 'price_data': { 'currency': 'usd', 'product_data': { @@ -221,13 +237,20 @@ class StripeService: }, 'quantity': 1, }], - mode='payment', - success_url=success_url, - cancel_url=cancel_url, - customer_email=customer_email, - metadata=metadata, - allow_promotion_codes=True, - ) + 'mode': 'payment', + 'success_url': success_url, + 'cancel_url': cancel_url, + 'customer_email': customer_email, + 'metadata': metadata, + 'allow_promotion_codes': True, + } + + # Add payment method configuration if set (enables Google Pay, Link, etc.) + if self.payment_method_config: + session_params['payment_method_configuration'] = self.payment_method_config + + # Create checkout session + session = stripe.checkout.Session.create(**session_params) logger.info( f"Created made-for-you checkout session {session.id} for {customer_email}, " diff --git a/docs/STRIPE-SETUP.md b/docs/STRIPE-SETUP.md index 8c69de53..91f43948 100644 --- a/docs/STRIPE-SETUP.md +++ b/docs/STRIPE-SETUP.md @@ -61,8 +61,24 @@ STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret # Optional (defaults shown) FRONTEND_URL=https://gen.nomadkaraoke.com # BUY_URL defaults to FRONTEND_URL after site consolidation + +# Payment Method Configuration (enables Google Pay, Apple Pay, Link) +# Get this from: Dashboard > Settings > Payment methods > [Your Config] > Copy ID +STRIPE_PAYMENT_METHOD_CONFIG=pmc_your_config_id_here ``` +### Payment Method Configuration + +To enable Google Pay, Apple Pay, Link, and other wallet payment methods in your checkout: + +1. Go to **Stripe Dashboard** > **Settings** > **Payment methods** +2. Create or select a configuration (e.g., "Default") +3. Enable the payment methods you want (Google Pay, Apple Pay, Link, etc.) +4. Copy the configuration ID (starts with `pmc_`) +5. Set it as `STRIPE_PAYMENT_METHOD_CONFIG` + +Without this setting, checkout sessions will only show basic payment methods (cards, some regional methods). With it, customers will see Google Pay, Apple Pay, and Link options when available on their device. + ### For Cloud Run deployment: The CI workflow (`.github/workflows/ci.yml`) automatically injects these secrets during deployment. No manual `gcloud` commands needed - just add the secret values to Secret Manager (step 2) and the next backend deployment will pick them up. diff --git a/scripts/inspect_stripe_config.py b/scripts/inspect_stripe_config.py new file mode 100755 index 00000000..3668e7c0 --- /dev/null +++ b/scripts/inspect_stripe_config.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +""" +Inspect Stripe configuration to debug payment method issues. + +This script: +1. Shows your payment method configuration details +2. Creates a test checkout session and inspects what methods are enabled +3. Compares with your Payment Links setup + +Usage: + export STRIPE_SECRET_KEY=sk_live_... + export STRIPE_PAYMENT_METHOD_CONFIG=pmc_... + python scripts/inspect_stripe_config.py +""" +import json +import os +import sys + +try: + import stripe +except ImportError: + print("Error: stripe package not installed. Run: pip install stripe") + sys.exit(1) + + +def main(): + secret_key = os.getenv("STRIPE_SECRET_KEY") + pmc_id = os.getenv("STRIPE_PAYMENT_METHOD_CONFIG") + + if not secret_key: + print("Error: STRIPE_SECRET_KEY not set") + sys.exit(1) + + stripe.api_key = secret_key + is_test = secret_key.startswith("sk_test_") + print(f"Mode: {'TEST' if is_test else 'LIVE'}") + print("=" * 70) + + # 1. List payment method configurations + print("\n1. PAYMENT METHOD CONFIGURATIONS") + print("-" * 70) + try: + configs = stripe.PaymentMethodConfiguration.list(limit=10) + for config in configs.data: + is_default = " (DEFAULT)" if config.get("is_default") else "" + active = "Active" if config.get("active") else "Inactive" + print(f"\n ID: {config.id}{is_default}") + print(f" Name: {config.get('name', 'Unnamed')}") + print(f" Status: {active}") + + # Show key payment methods + for pm in ['google_pay', 'apple_pay', 'link', 'card']: + pm_config = config.get(pm, {}) + if pm_config: + available = pm_config.get('available', False) + display_pref = pm_config.get('display_preference', {}).get('preference', 'none') + print(f" {pm}: available={available}, preference={display_pref}") + except Exception as e: + print(f" Error listing configs: {e}") + + # 2. Inspect the specific payment method configuration + if pmc_id: + print(f"\n2. YOUR PAYMENT METHOD CONFIGURATION ({pmc_id})") + print("-" * 70) + try: + config = stripe.PaymentMethodConfiguration.retrieve(pmc_id) + print(f" Name: {config.get('name', 'Unnamed')}") + print(f" Active: {config.get('active')}") + print(f" Is Default: {config.get('is_default')}") + + print("\n Payment Methods:") + for pm in ['google_pay', 'apple_pay', 'link', 'card', 'cashapp', 'klarna']: + pm_config = config.get(pm, {}) + if pm_config: + available = pm_config.get('available', 'N/A') + display_pref = pm_config.get('display_preference', {}) + pref = display_pref.get('preference', 'N/A') + value = display_pref.get('value', 'N/A') + print(f" {pm}:") + print(f" available: {available}") + print(f" display_preference.preference: {pref}") + print(f" display_preference.value: {value}") + except Exception as e: + print(f" Error: {e}") + else: + print("\n2. STRIPE_PAYMENT_METHOD_CONFIG not set - skipping config inspection") + + # 3. Create a test checkout session and inspect it + print("\n3. TEST CHECKOUT SESSION") + print("-" * 70) + try: + session_params = { + 'line_items': [{ + 'price_data': { + 'currency': 'usd', + 'product_data': { + 'name': 'Test Product', + }, + 'unit_amount': 100, + }, + 'quantity': 1, + }], + 'mode': 'payment', + 'success_url': 'https://example.com/success', + 'cancel_url': 'https://example.com/cancel', + 'customer_email': 'test@example.com', + } + + if pmc_id: + session_params['payment_method_configuration'] = pmc_id + + session = stripe.checkout.Session.create(**session_params) + + print(f" Session ID: {session.id}") + print(f" URL: {session.url[:80]}...") + print(f"\n payment_method_types: {session.payment_method_types}") + print(f" payment_method_configuration_details: {session.get('payment_method_configuration_details')}") + + # Expire the test session to clean up + try: + stripe.checkout.Session.expire(session.id) + print(f"\n (Test session expired)") + except: + pass + + except Exception as e: + print(f" Error creating session: {e}") + + # 4. Check Payment Method Domains + print("\n4. PAYMENT METHOD DOMAINS") + print("-" * 70) + try: + domains = stripe.PaymentMethodDomain.list(limit=20) + for domain in domains.data: + print(f"\n Domain: {domain.domain_name}") + print(f" ID: {domain.id}") + print(f" Enabled: {domain.enabled}") + print(f" Google Pay: {domain.google_pay.get('status', 'N/A')}") + print(f" Apple Pay: {domain.apple_pay.get('status', 'N/A')}") + print(f" Link: {domain.link.get('status', 'N/A')}") + except Exception as e: + print(f" Error: {e}") + + # 5. List recent Payment Links for comparison + print("\n5. PAYMENT LINKS (for comparison)") + print("-" * 70) + try: + links = stripe.PaymentLink.list(limit=3, active=True) + for link in links.data: + print(f"\n Link ID: {link.id}") + print(f" URL: {link.url}") + print(f" payment_method_types: {link.payment_method_types}") + print(f" payment_method_collection: {link.get('payment_method_collection')}") + except Exception as e: + print(f" Error: {e}") + + print("\n" + "=" * 70) + print("ANALYSIS") + print("=" * 70) + print(""" +If Google Pay/Apple Pay/Link are not appearing: + +1. Check payment_method_configuration_details above - if null, the config + isn't being applied correctly. + +2. Check the Payment Method Domains - your checkout domain must be registered + with status 'active' for Google Pay, Apple Pay, and Link. + +3. Compare payment_method_types between your Checkout Session and Payment Links. + If Payment Links shows more methods, there may be a config difference. + +4. In your Payment Method Configuration, check display_preference.value: + - 'on' = enabled + - 'off' = disabled + - 'none' = use Stripe's default logic + +5. For Google Pay specifically, the user must have Google Pay set up on their + device/browser for it to appear. +""") + + +if __name__ == "__main__": + main() diff --git a/scripts/test_stripe_checkout.py b/scripts/test_stripe_checkout.py new file mode 100755 index 00000000..bfd3c005 --- /dev/null +++ b/scripts/test_stripe_checkout.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python3 +""" +Test Stripe checkout session creation with payment method configuration. + +This script creates a test checkout session and opens it in your browser +to verify that Google Pay, Apple Pay, Link, and other payment methods appear. + +Usage: + # Test with your live/test Stripe keys + export STRIPE_SECRET_KEY=sk_test_... + export STRIPE_PAYMENT_METHOD_CONFIG=pmc_... # Optional but recommended + + # Create a credit purchase checkout + python scripts/test_stripe_checkout.py + + # Create a made-for-you checkout + python scripts/test_stripe_checkout.py --made-for-you + + # Just print the URL without opening browser + python scripts/test_stripe_checkout.py --no-open + + # Test different credit packages + python scripts/test_stripe_checkout.py --package 3_credits + +Requirements: + pip install stripe +""" +import argparse +import os +import sys +import webbrowser + +# Add backend to path for imports +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +import stripe + + +def get_env_or_prompt(var_name: str, prompt: str, secret: bool = False) -> str: + """Get environment variable or prompt user.""" + value = os.getenv(var_name) + if value: + if secret: + print(f" {var_name}: {'*' * 8}...{value[-4:]}") + else: + print(f" {var_name}: {value}") + return value + + print(f"\n{var_name} not set in environment.") + if secret: + import getpass + return getpass.getpass(f"{prompt}: ") + else: + return input(f"{prompt}: ") + + +def create_credit_checkout( + secret_key: str, + payment_method_config: str | None, + package_id: str, + email: str, +) -> str: + """Create a credit purchase checkout session.""" + stripe.api_key = secret_key + + packages = { + "1_credit": {"credits": 1, "price_cents": 500, "name": "1 Karaoke Credit"}, + "3_credits": {"credits": 3, "price_cents": 1200, "name": "3 Karaoke Credits"}, + "5_credits": {"credits": 5, "price_cents": 1750, "name": "5 Karaoke Credits"}, + "10_credits": {"credits": 10, "price_cents": 3000, "name": "10 Karaoke Credits"}, + } + + package = packages.get(package_id) + if not package: + raise ValueError(f"Invalid package: {package_id}. Choose from: {list(packages.keys())}") + + session_params = { + 'line_items': [{ + 'price_data': { + 'currency': 'usd', + 'product_data': { + 'name': package['name'], + 'description': f"Create {package['credits']} professional karaoke video(s)", + 'images': ['https://gen.nomadkaraoke.com/nomad-logo.png'], + }, + 'unit_amount': package['price_cents'], + }, + 'quantity': 1, + }], + 'mode': 'payment', + 'success_url': 'https://gen.nomadkaraoke.com/payment/success?session_id={CHECKOUT_SESSION_ID}', + 'cancel_url': 'https://gen.nomadkaraoke.com/?cancelled=true', + 'customer_email': email, + 'metadata': { + 'package_id': package_id, + 'credits': str(package['credits']), + 'user_email': email, + 'test': 'true', + }, + 'allow_promotion_codes': True, + } + + if payment_method_config: + session_params['payment_method_configuration'] = payment_method_config + print(f"\n Using payment_method_configuration: {payment_method_config}") + else: + print("\n WARNING: No payment_method_configuration set!") + print(" Google Pay, Apple Pay, and Link may not appear.") + + session = stripe.checkout.Session.create(**session_params) + return session.url + + +def create_made_for_you_checkout( + secret_key: str, + payment_method_config: str | None, + email: str, + artist: str = "Test Artist", + title: str = "Test Song", +) -> str: + """Create a made-for-you checkout session.""" + stripe.api_key = secret_key + + session_params = { + 'line_items': [{ + 'price_data': { + 'currency': 'usd', + 'product_data': { + 'name': f"Karaoke Video: {artist} - {title}", + 'description': "Professional 4K karaoke video with perfectly synced lyrics", + 'images': ['https://gen.nomadkaraoke.com/nomad-logo.png'], + }, + 'unit_amount': 1500, # $15.00 + }, + 'quantity': 1, + }], + 'mode': 'payment', + 'success_url': 'https://nomadkaraoke.com/order/success/?session_id={CHECKOUT_SESSION_ID}', + 'cancel_url': 'https://nomadkaraoke.com/#do-it-for-me', + 'customer_email': email, + 'metadata': { + 'order_type': 'made_for_you', + 'customer_email': email, + 'artist': artist, + 'title': title, + 'source_type': 'search', + 'test': 'true', + }, + 'allow_promotion_codes': True, + } + + if payment_method_config: + session_params['payment_method_configuration'] = payment_method_config + print(f"\n Using payment_method_configuration: {payment_method_config}") + else: + print("\n WARNING: No payment_method_configuration set!") + print(" Google Pay, Apple Pay, and Link may not appear.") + + session = stripe.checkout.Session.create(**session_params) + return session.url + + +def main(): + parser = argparse.ArgumentParser( + description="Test Stripe checkout with payment method configuration" + ) + parser.add_argument( + "--made-for-you", + action="store_true", + help="Create a made-for-you checkout instead of credit purchase", + ) + parser.add_argument( + "--package", + default="1_credit", + choices=["1_credit", "3_credits", "5_credits", "10_credits"], + help="Credit package to test (default: 1_credit)", + ) + parser.add_argument( + "--email", + default="test@example.com", + help="Customer email for the checkout (default: test@example.com)", + ) + parser.add_argument( + "--artist", + default="Avril Lavigne", + help="Artist name for made-for-you checkout (default: Avril Lavigne)", + ) + parser.add_argument( + "--title", + default="Things I'll Never Say", + help="Song title for made-for-you checkout (default: Things I'll Never Say)", + ) + parser.add_argument( + "--no-open", + action="store_true", + help="Don't open the URL in browser, just print it", + ) + args = parser.parse_args() + + print("=" * 60) + print("Stripe Checkout Test") + print("=" * 60) + + # Get configuration + print("\nConfiguration:") + secret_key = get_env_or_prompt( + "STRIPE_SECRET_KEY", + "Enter your Stripe secret key", + secret=True, + ) + payment_method_config = os.getenv("STRIPE_PAYMENT_METHOD_CONFIG") + if payment_method_config: + print(f" STRIPE_PAYMENT_METHOD_CONFIG: {payment_method_config}") + else: + print(" STRIPE_PAYMENT_METHOD_CONFIG: (not set)") + + # Detect test vs live mode + is_test_mode = secret_key.startswith("sk_test_") + mode_str = "TEST MODE" if is_test_mode else "LIVE MODE" + print(f"\n Mode: {mode_str}") + + if not is_test_mode: + print("\n WARNING: You are using LIVE keys!") + confirm = input(" Type 'yes' to continue: ") + if confirm.lower() != 'yes': + print(" Aborted.") + sys.exit(1) + + # Create checkout session + print("\n" + "-" * 60) + if args.made_for_you: + print(f"Creating made-for-you checkout...") + print(f" Artist: {args.artist}") + print(f" Title: {args.title}") + print(f" Email: {args.email}") + checkout_url = create_made_for_you_checkout( + secret_key, + payment_method_config, + args.email, + args.artist, + args.title, + ) + else: + print(f"Creating credit purchase checkout...") + print(f" Package: {args.package}") + print(f" Email: {args.email}") + checkout_url = create_credit_checkout( + secret_key, + payment_method_config, + args.package, + args.email, + ) + + print("\n" + "=" * 60) + print("Checkout URL:") + print(checkout_url) + print("=" * 60) + + if not args.no_open: + print("\nOpening in browser...") + webbrowser.open(checkout_url) + print("\nCheck that you see:") + print(" - Google Pay (if you have it set up)") + print(" - Apple Pay (on Safari/iOS)") + print(" - Link (Stripe's one-click checkout)") + print(" - Other enabled payment methods") + else: + print("\nCopy the URL above and open it in your browser to test.") + + print("\nIf wallet methods don't appear:") + print(" 1. Ensure STRIPE_PAYMENT_METHOD_CONFIG is set to your config ID") + print(" 2. Verify wallets are enabled in Stripe Dashboard") + print(" 3. Google Pay requires Chrome + Google Pay setup on device") + print(" 4. Apple Pay requires Safari + Apple Pay setup on device") + + +if __name__ == "__main__": + main()