plateforme-tfjm2/tfjm/helloasso.py

87 lines
2.6 KiB
Python

# Copyright (C) 2024 by Animath
# SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timedelta
from django.conf import settings
import requests
_access_token = None
_refresh_token = None
_expires_at = None
def get_hello_asso_access_token():
global _access_token, _refresh_token, _expires_at
now = datetime.now()
if _access_token is None:
response = requests.post(
"https://api.helloasso.com/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": settings.HELLOASSO_CLIENT_ID,
"client_secret": settings.HELLOASSO_CLIENT_SECRET,
},
)
response.raise_for_status()
data = response.json()
_access_token = data["access_token"]
_refresh_token = data["refresh_token"]
_expires_at = now + timedelta(seconds=data["expires_in"])
elif now >= _expires_at:
response = requests.post(
"https://api.helloasso.com/oauth2/token",
data={
"grant_type": "refresh_token",
"refresh_token": _refresh_token,
},
)
response.raise_for_status()
data = response.json()
_access_token = data["access_token"]
_refresh_token = data["refresh_token"]
_expires_at = now + timedelta(seconds=data["expires_in"])
return _access_token
def get_checkout_intent(checkout_id):
token = get_hello_asso_access_token()
response = requests.get(
f"https://api.helloasso.com/v5/organizations/animath/checkout-intents/{checkout_id}",
headers={"Authorization": f"Bearer {token}"},
)
if response.status_code == 404:
return None
response.raise_for_status()
checkout_intent = response.json()
if requests.head(checkout_intent["redirectUrl"]).status_code == 404:
return None
return checkout_intent
def create_checkout_intent(amount, name, back_url, error_url, return_url, contains_donation=False, metadata=None):
token = get_hello_asso_access_token()
metadata = metadata or {}
response = requests.post(
"https://api.helloasso.com/v5/organizations/animath/checkout-intents/",
headers={"Authorization": f"Bearer {token}"},
json={
"totalAmount": amount,
"initialAmount": amount,
"itemName": name,
"backUrl": back_url,
"errorUrl": error_url,
"returnUrl": return_url,
"containsDonation": contains_donation,
"metadata": metadata,
},
)
print(response.text)
response.raise_for_status()
return response.json()