import os, json, stripe, requests
from collections import defaultdict
stripe.api_key = os.environ["STRIPE_API_KEY"]
MAVERA_API_KEY = os.environ["MAVERA_API_KEY"]
MAVERA_BASE = "https://app.mavera.io/api/v1"
def fetch_disputes():
cats = defaultdict(lambda: {"count": 0, "examples": []})
for d in stripe.Dispute.list(limit=100).auto_paging_iter():
cats[d.reason]["count"] += 1
if len(cats[d.reason]["examples"]) < 3:
cats[d.reason]["examples"].append({"dispute_id": d.id, "amount": d.amount / 100,
"product_description": (d.evidence or {}).get("product_description", "")})
return dict(cats)
def rewrite_copy_for_reason(reason, data):
schema = {"type": "object", "properties": {
"reason_code": {"type": "string"},
"original_issues": {"type": "array", "items": {"type": "string"}},
"revised_product_description": {"type": "string"},
"revised_checkout_message": {"type": "string"},
"revised_confirmation_email_snippet": {"type": "string"},
}, "required": ["reason_code", "original_issues", "revised_product_description",
"revised_checkout_message", "revised_confirmation_email_snippet"]}
resp = requests.post(f"{MAVERA_BASE}/responses", json={
"input": [
{"role": "system", "content": "You are a conversion copywriter reducing chargebacks."},
{"role": "user", "content": f"{data['count']} disputes for '{reason}':\n"
f"{json.dumps(data['examples'], indent=2)}\n\n"
"Rewrite the product description, checkout message, and confirmation email."},
],
"response_format": {"type": "json_schema", "json_schema": {"name": "dispute_fix", "schema": schema}},
"max_tokens": 1500,
}, headers={"Authorization": f"Bearer {MAVERA_API_KEY}"})
resp.raise_for_status()
return json.loads(resp.json()["choices"][0]["message"]["content"])
for reason, data in fetch_disputes().items():
if data["count"] >= 2:
print(f"\n=== {reason} ({data['count']}) ===")
print(json.dumps(rewrite_copy_for_reason(reason, data), indent=2))