File size: 9,616 Bytes
625fd55
67fe275
013972e
625fd55
 
766b7fc
625fd55
6647a73
9a274ef
6647a73
4685d50
 
67fe275
4685d50
 
 
 
 
 
 
 
 
 
 
67fe275
625fd55
 
67fe275
d8d4b3f
 
 
 
f4b70f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55d075c
 
4685d50
 
625fd55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55d075c
 
625fd55
 
6f42628
625fd55
55d075c
625fd55
d48daa0
625fd55
 
 
 
 
f4b70f0
 
c0aaccd
 
 
 
 
f4b70f0
 
 
 
 
 
 
 
9a8e4f6
6f42628
 
2ffaca9
9a8e4f6
 
d48daa0
2ffaca9
625fd55
f4b70f0
 
 
 
 
4685d50
a5db2a7
4685d50
625fd55
4685d50
32c08f8
 
 
c0aaccd
32c08f8
 
 
 
 
 
 
 
 
 
 
 
4685d50
 
12e765e
 
9a8e4f6
d48daa0
55d075c
a5db2a7
4685d50
6f42628
9a8e4f6
f4b70f0
9a8e4f6
55d075c
9a8e4f6
 
d48daa0
55d075c
9a274ef
67fe275
 
 
868ad24
67fe275
11a36dc
868ad24
e2d80d5
9ebc709
868ad24
16b9fb9
e2d80d5
 
11a36dc
f97ef52
9d32818
 
85f7624
11a36dc
 
67fe275
 
 
 
c8800aa
6117b36
 
 
 
15a58fb
 
 
 
 
6117b36
 
 
 
4488955
67fe275
 
 
746edc4
 
 
 
 
4cd3fe5
746edc4
 
 
 
 
 
 
 
 
4cd3fe5
 
 
 
 
746edc4
 
 
 
9a274ef
67fe275
 
 
 
f3d4dfe
 
67fe275
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import os
import stripe
import requests
import logging
from fastapi import APIRouter, HTTPException, Header
from fastapi import Query
from pydantic import BaseModel

router = APIRouter()

# Configuração das chaves do Stripe e Supabase
stripe.api_key = os.getenv("STRIPE_KEY")
stripe.api_version = "2023-10-16"
SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
SUPABASE_KEY = os.getenv("SUPA_KEY")

if not stripe.api_key or not SUPABASE_KEY:
    raise ValueError("❌ STRIPE_KEY ou SUPA_KEY não foram definidos no ambiente!")

SUPABASE_HEADERS = {
    "apikey": SUPABASE_KEY,
    "Authorization": f"Bearer {SUPABASE_KEY}",
    "Content-Type": "application/json"
}

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class AccountRequest(BaseModel):
    email: str
    name: str  # Name of the individual account owner
    
class CreateCustomerRequest(BaseModel):
    email: str
    phone: str
    name: str

def verify_token(user_token: str) -> str:
    """
    Valida o token JWT no Supabase e retorna o user_id se for válido.
    """
    headers = {
        "Authorization": f"Bearer {user_token}",
        "apikey": SUPABASE_KEY,
        "Content-Type": "application/json"
    }

    response = requests.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers)

    if response.status_code == 200:
        user_data = response.json()
        user_id = user_data.get("id")
        if not user_id:
            raise HTTPException(status_code=400, detail="Invalid token: User ID not found")
        return user_id
    else:
        raise HTTPException(status_code=401, detail="Invalid or expired token")

import os
import stripe
import requests
import logging
from fastapi import APIRouter, HTTPException, Header
from pydantic import BaseModel

router = APIRouter()

# Configuração das chaves do Stripe e Supabase
stripe.api_key = os.getenv("STRIPE_KEY")
stripe.api_version = "2023-10-16"
SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
SUPABASE_KEY = os.getenv("SUPA_KEY")

if not stripe.api_key or not SUPABASE_KEY:
    raise ValueError("❌ STRIPE_KEY ou SUPA_KEY não foram definidos no ambiente!")

SUPABASE_HEADERS = {
    "apikey": SUPABASE_KEY,
    "Authorization": f"Bearer {SUPABASE_KEY}",
    "Content-Type": "application/json"
}

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class CreateCustomerRequest(BaseModel):
    email: str
    phone: str
    name: str

def verify_token(user_token: str) -> str:
    """
    Valida o token JWT no Supabase e retorna o user_id se for válido.
    """
    headers = {
        "Authorization": f"Bearer {user_token}",
        "apikey": SUPABASE_KEY,
        "Content-Type": "application/json"
    }

    response = requests.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers)

    if response.status_code == 200:
        user_data = response.json()
        user_id = user_data.get("id")
        if not user_id:
            raise HTTPException(status_code=400, detail="Invalid token: User ID not found")
        return user_id
    else:
        raise HTTPException(status_code=401, detail="Invalid or expired token")

@router.post("/create_customer")
def create_customer(
    data: CreateCustomerRequest, 
    user_token: str = Header(None, alias="User-key")
):
    try:
        if not user_token:
            raise HTTPException(status_code=401, detail="Missing User-key header")
        
        # 🔹 Validar o token e obter user_id
        user_id = verify_token(user_token)
        logger.info(f"🔹 User verified. user_id: {user_id}")

        # 🔹 Verificar se o usuário já tem um stripe_id no Supabase
        user_data_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
        response = requests.get(user_data_url, headers={
            "Authorization": f"Bearer {user_token}",  # Alterado para usar o token do usuário
            "apikey": SUPABASE_KEY,
            "Content-Type": "application/json"
        })
        
        if response.status_code == 200 and response.json():
            user_data = response.json()[0]
            stripe_id = user_data.get("stripe_id")
            if stripe_id:
                logger.info(f"✅ User already has a Stripe customer: {stripe_id}")
                return {"customer_id": stripe_id}

        # 🔹 Verificar se já existe um cliente com o mesmo e-mail no Stripe
        logger.info(f"🔹 Checking if email {data.email} already exists in Stripe...")
        existing_customers = stripe.Customer.list(email=data.email, limit=1)
        if existing_customers.data:
            error_message = f"Customer with email {data.email} already exists."
            logger.warning(f"⚠️ {error_message}")
            raise HTTPException(status_code=400, detail=error_message)

        # 🔹 Criar o cliente no Stripe
        customer = stripe.Customer.create(
            email=data.email,
            phone=data.phone,
            name=data.name
        )
        stripe_id = customer.id
        logger.info(f"✅ New Stripe customer created: {stripe_id}")

        # 🔹 Atualizar o usuário no Supabase com o stripe_id
        update_data = {"stripe_id": stripe_id}
        supabase_url = f"{SUPABASE_URL}/rest/v1/User"

        update_headers = {
            "Authorization": f"Bearer {user_token}",  # Alterado para usar o token do usuário
            "apikey": SUPABASE_KEY,
            "Content-Type": "application/json"
        }

        # 🔹 Adicionar query params corretamente
        response = requests.patch(
            f"{supabase_url}?id=eq.{user_id}",
            headers=update_headers,
            json=update_data
        )

        logger.info(f"🔹 Supabase PATCH response: {response.status_code} - {response.text}")

        if response.status_code not in [200, 204]:
            logger.warning(f"⚠️ Rolling back: Deleting Stripe customer {stripe_id} due to Supabase failure.")
            stripe.Customer.delete(stripe_id)
            error_message = f"Error updating Supabase: {response.text}"
            raise HTTPException(status_code=500, detail=error_message)

        logger.info(f"✅ Successfully updated user {user_id} with stripe_id {stripe_id}")
        return {"customer_id": stripe_id}

    except HTTPException as http_err:
        raise http_err  

    except Exception as e:
        error_message = str(e) if str(e) else "An unknown error occurred. Please try again."
        logger.error(f"❌ Error creating customer: {error_message}")
        raise HTTPException(status_code=500, detail=error_message)
        
@router.post("/create_account")
def create_account(account_data: AccountRequest):
    try:
        account = stripe.Account.create(
            type="express",  
            email=account_data.email,
            country="BR",  # 🇧🇷 Brasil (obrigatório para plataformas BR)
            business_type="individual",
            business_profile={
                "mcc": "7298",
                "name": account_data.name,
                "product_description": "We connect stylists with clients through subscription services.",
                "support_email": "[email protected]"
            },
            default_currency="brl",  # 💰 Real brasileiro
            capabilities={
                "transfers": {"requested": True},
                "card_payments": {"requested": True}
            }
            # ⚠️ Não incluindo settings de payout pois no Brasil apenas 'daily' é suportado
            # e é aplicado automaticamente pelo Stripe
        )
        return {"account_id": account.id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
        
@router.get("/check_onboarding/{account_id}")
def check_onboarding(account_id: str):
    try:
        account = stripe.Account.retrieve(account_id)
        
        if account.requirements.currently_due:
            return {"status": "incomplete", "pending_requirements": account.requirements.currently_due}
        
        return {"status": "complete"}
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

### **2️⃣ CREATE ACCOUNT LINK FOR ONBOARDING** ###
class AccountLinkRequest(BaseModel):
    account_id: str

@router.get("/terms")
def get_terms(type: str = Query(..., regex="^(use|privacy)$")):
    try:
        term_type = "Terms of Use" if type == "use" else "Privacy Policy"

        url = f"{SUPABASE_URL}/rest/v1/Configuration?type=eq.{term_type}&select=text,date"
        response = requests.get(url, headers=SUPABASE_HEADERS)

        if response.status_code != 200:
            raise HTTPException(status_code=500, detail="Erro ao acessar a tabela Configuration")

        data = response.json()
        if not data:
            raise HTTPException(status_code=404, detail="Termo não encontrado")

        return {
            "type": term_type,
            "text": data[0]["text"],
            "last_updated": data[0]["date"]
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
        
@router.post("/account_link")
def create_account_link(link_data: AccountLinkRequest):
    try:
        account_link = stripe.AccountLink.create(
            account=link_data.account_id,
            return_url="https://ameddes.com/onboarding?success=true",  # Updated return URL
            refresh_url="https://ameddes.com/onboarding?success=false",  # Updated refresh URL
            type="account_onboarding",
        )
        return {"url": account_link.url}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))