Ah, that's much simpler! Yes, this is a common approach. The application can check for payment status when internet is available, then allow offline usage until the next check is needed. Here's a basic implementation approach:
import datetime
import requests
import json
import os
from pathlib import Path
class LicenseManager:
def __init__(self, license_key, api_url):
self.license_key = license_key
self.api_url = api_url
self.cache_file = Path("license_cache.json")
def verify_license(self):
"""Verify license with server if online, otherwise check cached status"""
try:
# Try online verification first
response = requests.post(
f"{self.api_url}/verify",
json={"license_key": self.license_key},
timeout=5
)
if response.status_code == 200:
license_data = response.json()
# Cache the successful verification
self._cache_license_data(license_data)
return True
return False
except requests.RequestException:
# If offline, check cached license data
return self._check_cached_license()
def _cache_license_data(self, license_data):
"""Cache the license data locally"""
data = {
"license_key": self.license_key,
"last_verified": datetime.datetime.now().isoformat(),
"expiration_date": license_data["expiration_date"]
}
with open(self.cache_file, "w") as f:
json.dump(data, f)
def _check_cached_license(self):
"""Check if cached license is still valid"""
try:
with open(self.cache_file, "r") as f:
cached_data = json.load(f)
last_verified = datetime.datetime.fromisoformat(cached_data["last_verified"])
expiration_date = datetime.datetime.fromisoformat(cached_data["expiration_date"])
now = datetime.datetime.now()
# Allow offline usage for up to 30 days since last verification
if (now - last_verified).days <= 30 and now <= expiration_date:
return True
return False
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return False
def main():
# Initialize license manager
license_manager = LicenseManager(
license_key="USER_LICENSE_KEY",
api_url="https://your-license-server.com"
)
# Check license before running
if not license_manager.verify_license():
print("License verification failed. Please check your internet connection or license status.")
return
# Main application code goes here
print("Application running...")
if __name__ == "__main__":
main()
To package this as an executable:
pyinstaller --onefile your_script.py
Key features of this implementation:
-
Online Verification:
- Attempts to verify with server first
- Caches successful verification locally
- Stores expiration date and last verification time
-
Offline Usage:
- Checks cached license data when offline
- Allows offline usage for up to 30 days since last verification
- Prevents tampering by storing verification date
-
Security Considerations:
- Cache file should be encrypted in production
- Add checksum/signature verification
- Implement proper error handling
To make this production-ready, you would need to:
- Add Encryption:
from cryptography.fernet import Fernet
# Add encryption to cache file operations
def encrypt_data(data):
key = Fernet.generate_key() # Store this securely
f = Fernet(key)
return f.encrypt(json.dumps(data).encode())
def decrypt_data(encrypted_data):
key = get_stored_key() # Implement secure key storage
f = Fernet(key)
return json.loads(f.decrypt(encrypted_data))
- Implement Server-Side API:
- Verify license keys
- Track subscription status
- Handle payments
- Manage user accounts
- Add Error Handling:
def verify_license(self):
try:
# Existing verification code
except requests.RequestException as e:
logging.error(f"Network error: {e}")
return self._check_cached_license()
except Exception as e:
logging.error(f"Unexpected error: {e}")
return False
- Add Logging:
import logging
logging.basicConfig(
filename='application.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
This approach gives you:
- Reliable online verification
- Reasonable offline usage period
- Protection against basic tampering
- Flexibility in subscription management
The 30-day offline period is adjustable based on your needs. You could make it shorter for stricter control or longer for more flexibility.
Remember to implement proper server-side validation and secure your API endpoints. The server should maintain the source of truth for subscription status and handle edge cases like subscription cancellations or payment failures.