RedXAISecureToolkit 1.0.0
A unified toolkit for Firebase/Google Cloud, secure payments, and updates.
Requires Python: >=3.7

🔥 Red-XAI FireCloud

RedXAIFireCloud is a full-featured backend utility toolkit built by Red-XAI to simplify and enhance interaction with Firebase Realtime Database, Google Cloud Storage, and Cloud Run.

This library is perfect for developers who want clean, reliable, and smart abstractions over Firebase and Google Cloud without diving deep into low-level SDKs or dealing with brittle REST calls.
🧠 Project Philosophy

While building large-scale backend-integrated apps, we found ourselves rewriting the same Firebase and GCloud logic—initialization, reads, writes, exports, path parsing, and server syncs.

RedXAIFireCloud was born out of the need for smart, developer-friendly, and versatile functions that make common cloud operations intuitive, fast, and safe—across Firebase, GCP Storage, and Cloud Run.
📦 Installation

pip install RedXAIFireCloud

Import into your code:

from redxaifirecloud import *

⚙️ Initialization
🔐 RedXAIFirebaseInitialize()

db, app = RedXAIFirebaseInitialize(env_path=".env")

    Auto-loads from .env, or takes direct paths.

    Initializes Firebase Realtime DB.

    ✅ Superior to manual SDK boilerplate with env logic.

☁️ RedXAIGoogleCloudInitialize()

client = RedXAIGoogleCloudInitialize(env_path=".env")

    Loads Google Cloud credentials and returns a GCP client.

    ✅ Automatically sets required environment variables.

🔄 RedXAIFullInitialize()

db, app, client = RedXAIFullInitialize(env_path=".env")

    Initializes both Firebase and GCloud in one call.

    ✅ Perfect for hybrid cloud setups.

🌲 Firebase Utilities
🧭 RedXAIFirebaseTree()

RedXAIFirebaseTree("Users[Uid1]")

    Recursively prints Firebase path contents.

    ✅ Cleaner than manually navigating keys or using Firebase UI.

➕ RedXAIFireAddKey()

RedXAIFireAddKey("AppData[Settings]", "DarkMode", True)

    Adds or updates a key/value pair in Firebase.

🗑️ RedXAIFireRemoveKey()

RedXAIFireRemoveKey("AppData[Settings]", "OldKey")

    Deletes a key from a nested table.

🔁 RedXAIChangeFireTable()

RedXAIChangeFireTable("Users[Uid1][Stats]", "XP", 9000)

    Changes a key’s value or replaces an entire table.

    ✅ No need for repeated db.reference().set() chains.

🧩 RedXAIFireTableAdd()

RedXAIFireTableAdd("Logs[Daily]", "entry1", "Started App")

    Dynamically adds keys, even fallback "Value" entries.

❌ RedXAIFireTableRemove()

RedXAIFireTableRemove("Logs[Daily]")

    Removes full tables or individual keys.

🔎 RedXAIFireSearch()

results = RedXAIFireSearch("Users", key="Username", value="MainDirectory", detail_level="full")

    Recursively searches Firebase by key or value with path tracing.

    ✅ Replaces needing custom loops or Firestore.

🧱 Google Cloud Storage
📁 RedXAICloudCreateBucket()

RedXAICloudCreateBucket(client, "project-storage", main_folder="configs")

    Creates a GCP bucket + root folder + optional upload.

    ✅ Much faster than Cloud Console steps.

📂 RedXAICloudCreateFolder()

RedXAICloudCreateFolder(client, "my-bucket", "user1/config")

    Creates a folder prefix with .folder placeholder.

🔍 RedXAICloudSearch()

RedXAICloudSearch(client, "my-bucket/config", search_type="Folder")

    Searches buckets, folders, or files by path.

    ✅ Supports multiple detail levels like "full", "f", "p", etc.

🗑️ RedXAIDeleteBucket()

RedXAIDeleteBucket(client, "test-bucket", force=True)

    Deletes bucket and optionally wipes contents first.

🧹 RedXAICloudDeleteFolder()

RedXAICloudDeleteFolder(client, "main-bucket", "user123/cache")

    Removes an entire folder and all its files recursively.

⬆️ RedXAICloudUpload()

RedXAICloudUpload("main-bucket/user123", "./local_folder", client)

    Uploads files or folders into GCP bucket.

❌ RedXAICloudRemoveFile()

RedXAICloudRemoveFile(client, "main-bucket/docs/manual.pdf")

    Removes individual blob/file using direct path.

🌳 RedXAICloudTree()

RedXAICloudTree(client, "main-bucket/config")

    Visualizes the contents of any GCP bucket/folder.

🔄 Smart Server Communication
🌐 RedXAIServerExchange()

RedXAIServerExchange("user123/action", {"score": 200})

    Tries Firebase first, falls back to Cloud Run.

    ✅ Versatile and seamless cloud fallback logic.

📥 RedXAIReceiveFromServer()

RedXAIReceiveFromServer("user123", path_suffix="action")

    Pulls data from Firebase or Cloud Run.

🚀 RedXAISendFirebase()

RedXAISendFirebase("user123/game", {"HP": 120})

    Explicitly send to Firebase.

🚀 RedXAISendCloudRun()

RedXAISendCloudRun("https://api.run.app", "game/update", {"score": 999})

    Explicitly POST to a Cloud Run endpoint.

📤 Downloads & Exports
📥 RedXAICloudDownload()

RedXAICloudDownload("main-bucket/userdata", "./downloads", client)

    Downloads any folder or file structure locally.

📝 RedXAIExportFirebaseTree()

RedXAIExportFirebaseTree("firebase_tree.txt")

    Exports Firebase to a visual tree-style file.

📝 RedXAIExportCloudTree()

RedXAIExportCloudTree(client, "main-bucket", "cloud_tree.txt")

    Exports GCP folder/tree to text format.

📦 RedXAIExportAll()

RedXAIExportAll("ExportFolder", client)

    Dumps both Firebase and Cloud tree to one folder.

✅ Comparison to Standard Libraries
Feature	RedXAIFireCloud	Native Firebase SDK	GCP SDK	Manual REST APIs
Firebase + Cloud support	✅ Unified	❌	❌	❌
Smart fallback (Firebase/Cloud Run)	✅	❌	❌	❌
JSON-friendly tree exports	✅	❌	❌	❌
Zero boilerplate path parsing	✅	❌	❌	❌
Upload/download folders	✅	Partial	Partial	❌
Readable code	✅ Minimal	❌ Verbose	❌ Complex	❌ Tedious
📖 License

MIT License — Free to use for personal, open-source, or commercial projects.

    Copyright (c) 2025
    MainDirectory – Red-XAI

🔗 Links

    GitHub: github.com/MainDirectory/RedXAIFireCloud

    PyPI: pypi.org/project/RedXAIFireCloud

RedXAISecureUpdater

Installation

Install RedXAISecureUpdater via pip (Python Package Index):

pip install RedXAISecureUpdater

This will download and install the latest release from PyPI. The module supports Python 3.6+ and works on Windows, macOS, and Linux.
Usage

Using RedXAISecureUpdater in your project is straightforward. First, ensure you have an installer.cfg configuration file set up (see Configuration File section below). Then, import the module and call its functions to check for and perform updates.

For example, a basic usage scenario:

import RedXAISecureUpdater as updater

# Check if a newer version is available
update_available = updater.check_for_updates()
if update_available:
    # Fetch the latest build if an update is found
    updater.fetch_remote_build()
    # (Optional) Apply the update immediately
    updater.apply_update()

In this snippet:

    check_for_updates() reads your local version and checks the remote manifest to determine if a new version exists.

    fetch_remote_build() will download the update package (e.g., a zip or installer) from the remote URL specified in your config.

    apply_update() will initiate the installation of the downloaded update (this could involve replacing files, running an installer, etc., depending on your setup).

You can call these functions at the start of your application or at regular intervals to keep your software up-to-date.
Functions Overview

RedXAISecureUpdater provides a set of key functions to manage the update process. Here's a breakdown of each function, complete with descriptions, example code, and a fun emoji for easy identification:

    🔍 check_for_updates() – Check for a new version.
    This function compares the local version (from your config) with the latest version listed in the remote JSON manifest. It returns True if an update is available (remote version is higher), or False if you are up-to-date.
    Example:

if updater.check_for_updates():
    print("A new update is available!")
else:
    print("You have the latest version.")

🌐 fetch_remote_build() – Download the latest build.
Once you've detected an available update, use fetch_remote_build() to download the update package from the remote server. The URL is read from the remote manifest (for the new version). This function will save the file to the location specified in your config (e.g., a temp folder). It also verifies the file's checksum against the value provided in the manifest to ensure integrity.
Example:

if updater.check_for_updates():
    update_file_path = updater.fetch_remote_build()
    print(f"Update downloaded to {update_file_path}")

(In this example, fetch_remote_build() might return the file path of the downloaded update for further use.)

🔧 apply_update() – Apply the downloaded update.
After downloading the update package, apply_update() will perform the update installation. This could mean extracting files and replacing the old version, or running an installer file that was downloaded. The exact behavior may depend on how your application is meant to be updated (e.g., in-place file replacement, launching an installer, etc.). RedXAISecureUpdater handles common steps like stopping necessary services or processes before update and restarting them after, if applicable.
Example:

# Assuming an update has been downloaded already
success = updater.apply_update()
if success:
    print("Update applied successfully! Restarting application...")
else:
    print("Update failed. Please try again or contact support.")

🗄️ backup_current_version() (optional) – Backup existing installation.
Before applying an update, you may want to backup the current version of your application. backup_current_version() is an optional helper that archives the current installation (e.g., zipping the current app folder) so you can restore it if something goes wrong. This provides an extra safety net during the update process.
Example:

    updater.backup_current_version()
    updater.apply_update()

    (Call this function right before apply_update() to create a backup.)

All these functions work together to provide a smooth update experience. Typically, you'll call check_for_updates() and then, if needed, fetch_remote_build() and apply_update() in sequence. The module also handles exceptions and errors internally – for instance, if a download fails or a checksum mismatch is detected, it will notify you (through return values or exceptions) rather than applying a potentially corrupted update.
Configuration File: installer.cfg

RedXAISecureUpdater uses a configuration file (by default named installer.cfg) to store settings about your application’s update process. This allows you to change update parameters without modifying your code. The config file is in INI format and typically includes:

    Current version of your application.

    Remote manifest URL where the updater can check for the latest version info.

    Download path or file name for the update package.

    Optional settings like whether to auto-apply the update after download, etc.

Example installer.cfg:

[Updater]
current_version = 1.0.0
remote_manifest_url = https://updates.example.com/myapp/remote_build.json
download_path = ./updates/latest_update.zip
auto_apply = false

In this example:

    current_version is the version of your app that is currently installed. You should update this value whenever you successfully apply an update.

    remote_manifest_url is the web URL where RedXAISecureUpdater will fetch the JSON manifest (see next section) to check for the latest available version.

    download_path specifies where to save the downloaded update file. Here it's a local path (which could be a temporary directory or a specific updates folder).

    auto_apply is a setting that, if set to true, could tell the updater to automatically run apply_update() after a successful download. In the above configuration it’s false, meaning the update will be downloaded and then you can apply it manually or prompt the user.

Feel free to add other settings as needed. The module will read this config on each run to get the necessary parameters.

Using a Custom Config Path: By default, the module looks for installer.cfg in the current working directory. If you want to use a different config file name or location, you can specify it when calling the functions. For example: updater.check_for_updates(config_path="config/my_updater.cfg"). This gives you flexibility to manage multiple configs or different environments.
Remote Build Manifest: remote_build.json

The remote build manifest (often named remote_build.json) is a small JSON file hosted on your server. It tells RedXAISecureUpdater what the latest version of your software is and where to get it. When check_for_updates() runs, it fetches this JSON from the URL you provided in the config and reads the version information.

Example remote_build.json:

{
    "latest_version": "1.2.0",
    "download_url": "https://updates.example.com/myapp/MyApp_v1.2.0.zip",
    "checksum": "5f2d2e3a5d8f4b11c3e7d9a8b760a2e4",
    "release_date": "2025-03-01",
    "release_notes": "Added new features and fixed minor bugs."
}

Here’s what each field means:

    latest_version: The most recent version number of your application available for update. The updater will compare this with the current_version in your config.

    download_url: The direct link to the update package (installer or zip file) for this version. This is the URL that fetch_remote_build() will download.

    checksum: A hash (MD5/SHA256, etc.) of the update file for integrity verification. After downloading, RedXAISecureUpdater will compute the file’s hash and compare it to this value to ensure the download wasn’t corrupted or tampered with.

    release_date: (Optional) The date of the release, for your reference or to display to users.

    release_notes: (Optional) A short description of what’s new in this version, which you can use to inform users about changes.

Your manifest can include additional fields as needed, but at minimum latest_version and download_url are required for the updater to function. Including a checksum is highly recommended for security. Make sure to update this JSON on your server every time you release a new version of your app.
Comparison: RedXAISecureUpdater vs. Manual Update Scripts

Why use RedXAISecureUpdater instead of writing a custom update script? Here's a comparison that highlights the benefits of using this module over a traditional manual approach:
Aspect	Manual Update Script	RedXAISecureUpdater
Ease of Implementation	You have to write code to check versions, handle downloads, verify files, and manage errors all by yourself. This takes time and can be error-prone.	Provides out-of-the-box functions for checking versions, downloading updates, and verifying integrity. Minimal code needed to integrate.
Security & Integrity	You must manually implement any security checks (if at all). Many simple scripts skip checksum or signature verification, risking corrupted or malicious updates.	Built-in verification of update file via checksum (and optional additional checks). Uses secure HTTPS connections by default.
Configurability	Update URLs and settings are often hard-coded. Changing an update source means editing script code.	Uses an external config (installer.cfg) for update URL, version, and options. Adjust your update settings easily without touching code.
Error Handling	You need to add your own try/except blocks and fallback logic. If something fails, it might not be handled gracefully in a custom script.	Robust error handling is built into the module. It safely handles network failures, JSON parsing issues, and file errors, providing clear messages or exceptions.
Maintenance	Custom scripts require you to maintain and update them as your application evolves. Every new feature (like adding a backup, or logging) means more custom code.	The module is maintained as a reusable component. New features and fixes (like improved logging, backup support) come with updates to RedXAISecureUpdater, benefiting all your projects instantly.

In short, RedXAISecureUpdater abstracts the repetitive work of building an updater. It lets you focus on your application's core features, knowing that the update mechanism is reliable and secure.
License

This project is licensed under the MIT License. You are free to use, modify, and distribute this software as per the terms of the license. See the LICENSE file for details.
Links

    GitHub Repository: RedXAISecureUpdater on GitHub – Browse the source code, open issues, and contribute.

    PyPI Package: RedXAISecureUpdater on PyPI – View the package details and release history on PyPI.

(The GitHub and PyPI links above provide access to the project source, documentation, and distribution for convenient installation.)
Support & Contact

If you have any questions, issues, or suggestions regarding RedXAISecureUpdater, feel free to reach out:

    Issue Tracker: The best way to report problems or propose features is to open an issue on the GitHub repository. The maintainers will review and respond as soon as possible.

    Email: You can also send an email to support@redxai.org for direct support or inquiries.

We welcome feedback and contributions! By using RedXAISecureUpdater, you're helping us improve it. If you find this tool helpful, give the repository a star ⭐ on GitHub and let others know. Happy updating!


RedXAISecurePayments
🔐 Project Description and Overview

RedXAISecurePayments is a Python module that provides an all-in-one solution for managing users, handling secure payments via Stripe, generating license keys, and sending verification emails. It streamlines the process of integrating payment processing and licensing into your application, so you can focus on your core product instead of writing boilerplate for payments and email.

Key features include:

    💳 One-call Stripe checkout integration: Accept payments (one-time or subscription) with a single function call.

    🔑 Built-in license key generation: Create and manage lifetime license codes for your apps without custom logic.

    ✉️ Integrated email verification: Easily send verification emails to users to confirm accounts or purchases.

    🧩 Seamless integration: Designed to plug into your existing Python web app or backend with minimal configuration.

    ✅ Secure and efficient: Leverages Stripe’s PCI-compliant checkout and standard email protocols, reducing the risk of errors.

This module is ideal for SaaS products, software downloads, or any app that needs to sell access or licenses. With RedXAISecurePayments, you get a fully structured payment and user management system out-of-the-box.
🧠 Project Philosophy

Modern developers shouldn’t have to reinvent the wheel for payments or user management. RedXAISecurePayments was created to eliminate the pain points of setting up Stripe payments, managing user licenses, and sending emails manually. Our philosophy is to provide high-level building blocks that cover common workflows end-to-end.

    ✅ Simplicity Over Boilerplate: Abstracts away dozens of API calls and checks. Fewer lines of code means fewer chances for bugs.

    ✅ Secure by Design: Uses battle-tested services (Stripe for payments, standard SMTP for email) so sensitive data (💳 card info) never touches your servers.

    ✅ Modular Integration: Fits into your stack like a puzzle piece (🧩) – use all of it or just the parts you need. It plays nicely with your existing user database or web framework.

    ✅ Developer Focused: Clear function APIs with sensible defaults. Spend minutes configuring, not weeks debugging payment flows or email servers.

By embracing these principles, RedXAISecurePayments lets you deliver features faster and with confidence in their reliability and security.
📦 Installation and Import

Install the package from PyPI using pip (Python 3.7+):

pip install RedXAISecurePayments

Then import the module in your project:

import RedXAISecurePayments as rsp

This will also install any necessary dependencies (e.g. the Stripe Python SDK). Before using payment or email features, make sure you have the required credentials (Stripe API key, SMTP email credentials) ready.
⚙️ Initialization

Before performing any operations, initialize the module with your configuration. You can either initialize each component individually or use the convenient InitializeAll function to set up everything at once.

For example, using InitializeAll to configure the Stripe API key and email server in one call:

rsp.InitializeAll(
    stripe_api_key="sk_test_51NbXs0YourStripeKey",
    smtp_host="smtp.example.com", smtp_port=587,
    smtp_user="no-reply@example.com", smtp_pass="yourEmailPassword"
)

This single call will internally set up Stripe integration (so QuickBuy knows your API key), prepare the user and license storage, and configure the email sender. After this, the system is ready to use.

If you prefer granular control, you can initialize components step-by-step:

rsp.InitializeUsers()               # Set up user management system (e.g., database or in-memory store)
rsp.InitializeLifetimeCodes()       # Prepare storage for lifetime license keys
rsp.InitializeSubscriptions()       # Prepare storage for subscription records
# (Also set Stripe API key separately, e.g., via InitializeAll or environment variable)
# (Also configure email settings if using SendVerificationEmail)

Use the approach that fits your needs – InitializeAll for quick setup, or individual initialization if you want to customize or omit certain features. Either way, initialization only needs to be done once (e.g., at application startup).
🔑 User and Purchase System Setup

To manage purchases and licenses, RedXAISecurePayments provides utilities to handle user accounts, license code generation, and subscription tracking.
InitializeUsers()

Sets up the user management system. This might create a local database or in-memory structure to store user information (such as emails, Stripe customer IDs, verification status, etc.). Call this at startup to enable user tracking.

    Usage: rsp.InitializeUsers(path="users.db") (path is optional; by default it may use an in-memory store or a default file).

    Expected behavior: Establishes an internal registry for users. If using persistent storage, it creates or opens the necessary file/table. After this, other functions like QuickBuy or SendVerificationEmail can refer to users by email or ID.

    Advantages:

        ✅ No custom user DB needed: Saves you from writing user storage code. The module handles creating and looking up users as needed.

        ✅ Auto-links with Stripe: Can store Stripe Customer IDs for each user to avoid creating duplicate customers on multiple purchases.

        ✅ Minimal setup: One call replaces setting up an entire users table or ORM model in a typical app.

InitializeLifetimeCodes()

Prepares the system for managing lifetime license codes (one-time purchase licenses). This will set up a structure (e.g., a table or list) to keep track of generated license keys, which users they belong to, and their validity.

    Usage: rsp.InitializeLifetimeCodes(store="lifetime_keys.json") (store path optional).

    Expected behavior: Initializes an internal repository for license codes. This ensures that when you generate or validate a license key, the data is stored consistently.

    Advantages:

        ✅ Ready-to-use license store: Eliminates the need to design a schema for license keys. It’s handled for you.

        ✅ Prevents duplicates: The system will ensure each generated key is unique and can track if it’s been issued or used.

        ✅ Focus on logic, not storage: You concentrate on when to issue a key, and the module manages how to store it.

InitializeSubscriptions()

Sets up subscription management. Use this if your app offers recurring subscriptions (e.g., monthly or annual plans). It will prepare an internal structure to record active subscriptions and their link to users.

    Usage: rsp.InitializeSubscriptions()

    Expected behavior: Creates a subscription log or table in the background. Later, when a user subscribes via QuickBuy, the module can record the subscription details (like plan, start date, status) here.

    Advantages:

        ✅ Subscription-ready: One call to enable subscription tracking instead of building a subscription model from scratch.

        ✅ Integrated with Stripe billing: Designed to work with Stripe’s subscription flow, so when a Stripe subscription is created, you can easily update or query it via this module.

        ✅ Reduce human error: Ensures that subscription data (like renewal dates or cancellation status) is stored consistently for your app to use.

Note: If you call InitializeAll(...), it will internally call the above three functions (Users, LifetimeCodes, Subscriptions) for you, so you don’t need to call them separately.
📦 App Licensing and Activation

These functions help you define what you’re selling (your “app” or product), generate license keys for purchases, and tie everything together.
AddApp(app_name, **kwargs)

Registers a new application or product in the secure payment system. Use this to define the item you are selling, along with any relevant details like price or plan identifiers.

    Usage: rsp.AddApp("MySoftware", lifetime_price="price_12345", subs_monthly="price_67890")

    Expected behavior: Stores a record of the application MySoftware with its associated Stripe price IDs (in this example, a one-time purchase price and a monthly subscription price). You can call AddApp for each product you plan to offer.

    Advantages:

        ✅ Single source of truth: Keep all product info (name, prices, etc.) in one place. No hardcoding price IDs throughout your code.

        ✅ Multiple pricing options: Supports multiple plans for one product (e.g., lifetime vs subscription) by accepting different price IDs in kwargs.

        ✅ Simplified references: After adding an app, you can just refer to it by name (e.g., "MySoftware") in other calls like QuickBuy, making the code more readable and less error-prone.

GenerateLifetimeKey(user_identifier, app_name)

Generates a new lifetime license key for a given user and application. This is typically used after a successful one-time purchase, or by an admin to grant a license manually.

    Usage: license_code = rsp.GenerateLifetimeKey("alice@test.com", "MySoftware")

    Expected behavior: Creates a unique license code (e.g., MYsoft-AB12-CD34-EF56) for MySoftware tied to the user "alice@test.com". The key is stored internally (via the LifetimeCodes system) and associated with that user and app.

    Advantages:

        ✅ Instant license generation: One call produces a ready-to-use key, without writing a key generator or ensuring uniqueness yourself.

        ✅ Secure and unique: The generated keys are cryptographically random or algorithmically unique, reducing chances of collision or guessability.

        ✅ Auto-managed: The module automatically records the new key in its database. You can later verify or list keys without extra bookkeeping.

After generating a key, you can present it to the user (e.g., display on a webpage or include in an email). The user can use this key to activate their product. (Optionally, if your application has an activation feature, you can build it to check against the stored keys via this module.)
InitializeAll(**kwargs)

Sets up all required systems in one go. This convenience function wraps the individual initialization functions and also applies global configurations (like API keys or email settings).

    Usage: See example in Initialization section above. You pass in your Stripe secret key, email SMTP settings, and any other configuration. For instance:
    rsp.InitializeAll(stripe_api_key="sk_test_...", smtp_host="smtp.example.com", smtp_user="you@example.com", smtp_pass="****")

    Expected behavior: Internally calls InitializeUsers(), InitializeLifetimeCodes(), and InitializeSubscriptions(), then configures the Stripe API key and email SMTP credentials for you. After this call, all subsystems are ready.

    Advantages:

        ✅ All-in-one setup: Perfect for quick start or testing, where you want everything initialized with one function call.

        ✅ Avoids omissions: Ensures you didn’t forget to initialize a component. This reduces runtime errors from missing setup.

        ✅ Config in one place: Accepts all necessary config parameters, so you don’t have to sprinkle setup code across your project.

Tip: You can mix and match the above functions. For example, you might call InitializeAll for a default setup, and later use AddApp to add products or call GenerateLifetimeKey when needed.
💳 Payment and Checkout

Integrating payment processing is often the hardest part of building a paid service. RedXAISecurePayments makes it straightforward by leveraging Stripe Checkout under the hood. The module handles creating Stripe sessions, linking them to your users, and even recording subscriptions — all with minimal code.

After initializing and adding your app with pricing, you can use the QuickBuy function to start a secure checkout in one step. Stripe will handle the payment collection (credit cards, etc.), and you can follow up with license activation or confirmation emails once payment succeeds.
QuickBuy with Stripe

The QuickBuy function initiates a Stripe Checkout for a given user and product (and plan). It abstracts away the Stripe API calls needed to create a checkout session.

    Usage: checkout_url = rsp.QuickBuy("alice@test.com", "MySoftware", plan="lifetime")

    Expected behavior:

        If the user "alice@test.com" is not already in the system, QuickBuy will create a new user entry (and optionally a Stripe Customer under the hood) automatically.

        It contacts Stripe using the configured API key to create a Checkout Session for MySoftware (lifetime plan in this case). Stripe knows the price and product from the AddApp configuration.

        Returns a URL (or session ID) for the secure Stripe checkout page. This URL can be sent to the front-end or redirected to so the user can complete payment.

        Optionally, QuickBuy might log or store the pending purchase info (like the session or order) in the user’s record for reference.

    What you do next: Redirect your user to the provided checkout_url. Stripe will handle the payment UI and security. After payment, Stripe will redirect the user to a success page.

    Advantages:

        ✅ Minimal code for checkout: Instead of writing 50+ lines of Stripe integration, one function call sets up the entire payment flow.

        ✅ Safe and PCI-compliant: Credit card data is handled by Stripe (💳), so you don’t touch sensitive info. QuickBuy ensures all required parameters (prices, customer, redirect URLs) are correctly set.

        ✅ Smart user handling: Reuses existing Stripe customer info if available (avoiding duplicate customers) and ties the checkout to your user record automatically.

        ✅ Flexible: Supports one-time charges (e.g., lifetime purchase) and recurring subscriptions (by specifying the plan or price). You can offer multiple plans without additional complexity.

Example: A user wants to buy a lifetime license for MySoftware. You call:

checkout_url = rsp.QuickBuy("alice@test.com", "MySoftware", plan="lifetime")
print("Redirecting user to:", checkout_url)

This might output a URL like https://checkout.stripe.com/pay/cs_test_ABC123... which you then use in your web frontend to redirect Alice for payment. That’s it — no manual Stripe calls or session management needed!
📋 Comparison with raw Stripe flows

How does QuickBuy simplify Stripe integration? Consider what a typical Stripe payment flow requires versus using RedXAISecurePayments:

    Standard Stripe Integration:

        Manually set API keys and initialize Stripe client.

        Create or retrieve a Customer for the user.

        Define the product and price in Stripe’s dashboard (or via API) ahead of time.

        Write backend code to create a Checkout Session or PaymentIntent with the correct price ID, quantity, customer, and success/cancel URLs.

        Handle webhooks or redirect callbacks to confirm the payment and then grant access (e.g., activate license, send email).

        Write additional code to save the order or subscription in your database for future reference.

    Using QuickBuy:

        Ensure InitializeAll (or Stripe config and AddApp) is done with your Stripe key and product price.

        Call rsp.QuickBuy(user, product, plan) to get a checkout URL.

        Redirect the user to Stripe Checkout – upon completion, you can directly call GenerateLifetimeKey and SendVerificationEmail (no need to wrangle low-level Stripe responses, as Stripe will ensure payment success on the success URL hit).

        (Optional:) Check Stripe’s webhook for ultimate confirmation if needed, but in most cases, if the user reaches your success page, you know the payment succeeded and can proceed to deliver the license.

As you can see, QuickBuy compresses multiple steps into one. It handles session creation and user linkage, so you write significantly less code. This leads to faster development and fewer opportunities to make mistakes in the payment flow. You get the benefit of Stripe’s robust system without dealing with its complexity directly.
✉️ Verification Tools

Verifying user emails is crucial for security and communication (for example, confirming a user’s address before sending them a license key or ensuring an account is valid). RedXAISecurePayments includes a convenient email verification function that works out-of-the-box after you provide email server settings (SMTP).
SendVerificationEmail(user_identifier)

Sends a verification email to the specified user. Typically, you’d call this when a new user signs up or after a purchase, to confirm that the provided email belongs to them. The function will generate a unique verification link or code and email it to the user.

    Usage: rsp.SendVerificationEmail("alice@test.com")

    Expected behavior:

        Looks up the user’s email (in this case it’s the identifier itself). If the user is new and not yet in the system, InitializeUsers may add them automatically.

        Generates a verification token (e.g., a random code or secure link with a token). This token is stored with the user’s record (to validate later).

        Composes an email with a verification link (or code) and sends it to alice@test.com using the SMTP settings you configured (via InitializeAll or similar).

        The email instructs the user to click the link or enter the code to verify their account.

    Advantages:

        ✅ One-call email setup: No need to manually connect via smtplib or use third-party email APIs in your code. Just call this function.

        ✅ Complete flow included: The module handles creating the token, crafting a well-formatted email message, and sending it. It can include your app name and a custom message by default (which you can configure).

        ✅ Enhances security: Encourages verification for important actions (like purchases) without adding any overhead for you. This helps prevent fake or mistyped emails from going unnoticed.

        ✅ Saves boilerplate: In a standard setup, you’d write email templates, handle SMTP connections, and ensure TLS – RedXAISecurePayments does all of that behind the scenes.

Note: To complete the verification loop, you’ll need to handle the verification link or code on your application side (e.g., a simple web route that calls a function to validate the token stored for the user). RedXAISecurePayments provides the sending and token generation; you can easily build a small handler using the same user data it manages to finish the process.
🔄 Function Examples and Embedded Combos

To illustrate how these functions come together in practice, here are a couple of real-world usage scenarios chaining 2–3 functions. These examples demonstrate the superior developer experience and reduced code achieved with RedXAISecurePayments.
Example 1: Initial Setup and Product Registration

Imagine you are setting up a new SaaS app. You need to configure payments and define the product being sold.

import RedXAISecurePayments as rsp

# 1. Initialize all systems with your keys and settings
rsp.InitializeAll(
    stripe_api_key="sk_test_51NbXs0YourStripeKey",
    smtp_host="smtp.example.com", smtp_port=587,
    smtp_user="no-reply@example.com", smtp_pass="yourEmailPassword"
)

# 2. Register your product and its pricing (one-time and subscription)
rsp.AddApp("MySoftware", lifetime_price="price_12345", subs_monthly="price_67890")

print("Setup complete. Ready to accept payments for MySoftware.")

What’s happening? In a few lines, we configured our Stripe and email integration (step 1) and told the system about MySoftware and its Stripe price IDs (step 2). Under the hood, this created the user/license database and prepared everything needed to start selling. ✅ Without this module, you might have to initialize multiple libraries and write a config parser – here it’s all done in one place.
Example 2: User Purchase Flow with License Delivery

Now, suppose a user wants to buy a lifetime license for MySoftware. Here’s how you can handle it with RedXAISecurePayments:

# 1. User initiates a purchase (backend creates a checkout session)
checkout_url = rsp.QuickBuy("alice@test.com", "MySoftware", plan="lifetime")
# Send this URL to the frontend or redirect the user to it:
print(f"Redirect user to {checkout_url} for payment...")

# ... Stripe handles payment, then redirects to your success URL ...

# 2. After successful payment, generate a license key for the user
license_key = rsp.GenerateLifetimeKey("alice@test.com", "MySoftware")
print(f"Generated license key: {license_key}")

# 3. Send a verification email with the license key to the user
rsp.SendVerificationEmail("alice@test.com")
print("Verification email sent to user.")

In this flow:

    We called QuickBuy to kick off the Stripe checkout. This one call created a Stripe session and took care of linking it to Alice’s user record. We then direct Alice to Stripe’s secure payment page.

    Once Stripe confirms the payment (user lands on our success page), we immediately issue a license with GenerateLifetimeKey. The key is uniquely generated and stored.

    We send Alice a verification email (SendVerificationEmail). The email contains a link for Alice to verify her email address. You can customize the email content to include the license_key or additional instructions (for example, how to use the key to activate MySoftware).

This example chain covers the entire purchase process: from checkout to delivering the license and verifying the user’s email — all in just three function calls. ✅ Compared to a traditional approach, we didn’t have to manually create a Stripe customer, handle checkout sessions, write email SMTP code, or generate a license by hand.