Browse Source

Added logic for adding/finding Stripe customers

master
Alan Woodman 3 months ago
parent
commit
15ec5b56e1
  1. 125
      blueprints/main.py
  2. 43
      test.py

125
blueprints/main.py

@ -379,11 +379,84 @@ def get_customer_data_for_notification(splynx_id):
except:
return {'name': 'Unknown Customer'}
def search_stripe_customer_by_email(email):
"""Search for a Stripe customer by email address."""
try:
import stripe
# Use appropriate API key based on config
if Config.PROCESS_LIVE:
stripe.api_key = "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"
else:
stripe.api_key = "sk_test_51Rsi9gPfYyg6zE1S4ZpaPI1ehpbsHRLsGhysYXKwAWCZ7w6KYgVXy4pV095Nd8tyjUw9AkBhqfxqsIiiWJg5fexI00Dw36vnvx"
customers = stripe.Customer.search(query=f"email:'{email}'")
if customers.get('data') and len(customers['data']) > 0:
# Return the most recent customer if multiple exist
return customers['data'][-1]['id']
else:
return None
except Exception as e:
print(f"Error searching Stripe customer by email {email}: {e}")
return None
def create_stripe_customer(customer_data, splynx_id):
"""Create a new Stripe customer with the provided data."""
try:
import stripe
# Use appropriate API key based on config
if Config.PROCESS_LIVE:
stripe.api_key = "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"
else:
stripe.api_key = "sk_test_51Rsi9gPfYyg6zE1S4ZpaPI1ehpbsHRLsGhysYXKwAWCZ7w6KYgVXy4pV095Nd8tyjUw9AkBhqfxqsIiiWJg5fexI00Dw36vnvx"
customer = stripe.Customer.create(
name=customer_data.get('name', ''),
description=customer_data.get('name', ''),
email=customer_data.get('billing_email', ''),
metadata={
'splynx_id': str(splynx_id)
}
)
return customer.id
except Exception as e:
print(f"Error creating Stripe customer for Splynx ID {splynx_id}: {e}")
return None
def update_splynx_customer_stripe_id(splynx_id, stripe_customer_id):
"""Update Splynx customer with Stripe customer ID."""
try:
params = {
'additional_attributes': {
'stripe_customer_id': stripe_customer_id
}
}
update_result = splynx.put(url=f"/api/2.0/admin/customers/customer/{splynx_id}", params=params)
return update_result is not None
except Exception as e:
print(f"Error updating Splynx customer {splynx_id} with Stripe ID {stripe_customer_id}: {e}")
return False
def get_stripe_customer_id(splynx_id):
"""Get Stripe customer ID from MySQL for a given Splynx customer ID."""
"""
Get Stripe customer ID for a given Splynx customer ID.
Enhanced logic:
1. First check MySQL database for existing Stripe customer ID
2. If not found, check Splynx additional_attributes for stripe_customer_id
3. If not valid, search Stripe by customer email
4. If still not found, create new Stripe customer
5. Store the Stripe customer ID back to Splynx
"""
connection = None
try:
# Connect to MySQL database
# Step 1: Check MySQL database first (existing logic)
connection = pymysql.connect(
host=Config.MYSQL_CONFIG['host'],
database=Config.MYSQL_CONFIG['database'],
@ -412,9 +485,55 @@ def get_stripe_customer_id(splynx_id):
result = cursor.fetchone()
if result and result['stripe_customer_id']:
print(f"Found Stripe customer ID in MySQL: {result['stripe_customer_id']}")
return result['stripe_customer_id']
# Step 2: MySQL lookup failed, get customer from Splynx
print(f"No Stripe customer ID found in MySQL for Splynx ID {splynx_id}, checking Splynx...")
cust = splynx.Customer(splynx_id)
if not cust or cust == 'unknown':
print(f"Customer {splynx_id} not found in Splynx")
return None
# Step 3: Check Splynx additional_attributes for stripe_customer_id
additional_attrs = cust.get('additional_attributes', {})
existing_stripe_id = additional_attrs.get('stripe_customer_id', '')
if existing_stripe_id and existing_stripe_id.startswith('cus_'):
print(f"Found valid Stripe customer ID in Splynx: {existing_stripe_id}")
return existing_stripe_id
# Step 4: Search Stripe by customer email
customer_email = cust.get('billing_email', '')
if customer_email:
print(f"Searching Stripe for customer with email: {customer_email}")
stripe_customer_id = search_stripe_customer_by_email(customer_email)
if stripe_customer_id:
print(f"Found existing Stripe customer: {stripe_customer_id}")
# Store the ID back to Splynx
if update_splynx_customer_stripe_id(splynx_id, stripe_customer_id):
print(f"Updated Splynx customer {splynx_id} with Stripe ID {stripe_customer_id}")
else:
print(f"Failed to update Splynx customer {splynx_id} with Stripe ID")
return stripe_customer_id
# Step 5: Create new Stripe customer if none found
print(f"No existing Stripe customer found, creating new customer for Splynx ID {splynx_id}")
stripe_customer_id = create_stripe_customer(cust, splynx_id)
if stripe_customer_id:
print(f"Created new Stripe customer: {stripe_customer_id}")
# Store the new ID back to Splynx
if update_splynx_customer_stripe_id(splynx_id, stripe_customer_id):
print(f"Updated Splynx customer {splynx_id} with new Stripe ID {stripe_customer_id}")
else:
return None
print(f"Failed to update Splynx customer {splynx_id} with new Stripe ID")
return stripe_customer_id
else:
print(f"Failed to create Stripe customer for Splynx ID {splynx_id}")
return None
except pymysql.Error as e:
print(f"MySQL Error in get_stripe_customer_id: {e}")

43
test.py

@ -1,42 +1,39 @@
import json
import stripe
from typing import List, Dict, Union, Any
from app import create_app, db
from models import Payments, PaymentBatch, SinglePayments, PaymentPlans
from splynx import Splynx, SPLYNX_URL, SPLYNX_KEY, SPLYNX_SECRET
from services import log_activity
from config import Config
splynx = Splynx(url=SPLYNX_URL, key=SPLYNX_KEY, secret=SPLYNX_SECRET)
results = {
"deleted": 0,
"error": 0
}
api_key = Config.STRIPE_LIVE_API_KEY
stripe.api_key = api_key
def splynx_invoices(splynx_id: int) -> List[Dict[str, Any]]:
#result = splynx.get(url=f"/api/2.0/admin/finance/invoices?main_attributes[customer_id]={splynx_id}&main_attributes[status]=paid&main_attributes[date]=2025-08-21")
params = {
'main_attributes': {
'customer_id': splynx_id,
'status': ['IN', ['not_paid', 'pending']]
},
}
query_string = splynx.build_splynx_query_params(params)
result = splynx.get(url=f"/api/2.0/admin/finance/invoices?{query_string}")
print(f"Count: {len(result)} - {json.dumps(result,indent=2)}")
if __name__ == "__main__":
customers = stripe.Customer.search(query="email:'tom.bj@icloud.com'")
print(customers)
cust = splynx.Customer(31)
print(f"cust: {json.dumps(cust,indent=2)}")
params = {
'additional_attributes': {
'stripe_customer_id': customers['data'][-1]['id']
}
}
update_cust = splynx.put(url=f"/api/2.0/admin/customers/customer/31", params=params)
if __name__ == "__main__":
app = create_app()
customer_id = '1219464'
results = splynx_invoices(customer_id)
print(f"update_cust: {update_cust}")
print(json.dumps(results,indent=2))
cust = splynx.Customer(31)
print(f"cust: {json.dumps(cust,indent=2)}")
print(cust['additional_attributes']['stripe_customer_id'])
Loading…
Cancel
Save